0

I am struggling here to make this work, i have to detect the string which i am receiving in the response is base64 encoded or not and handle it accordingly.

I have tried two ways so far:

1.

if ([input length] % 4 == 0 && input.length >= 3) {
    static NSCharacterSet *invertedBase64CharacterSet = nil;
    if (invertedBase64CharacterSet == nil) {
        invertedBase64CharacterSet = [[NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="]invertedSet];
    }
    return [input rangeOfCharacterFromSet:invertedBase64CharacterSet options:NSLiteralSearch].location == NSNotFound;
}
return NO;

2.

NSString *expression = regexString;
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression options:NSRegularExpressionCaseInsensitive error:&error];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:self options:0 range:NSMakeRange(0, [self length])];

if (numberOfMatches > 0) {
    return YES;
} else {
    return NO;
}

Everything is working fine except when the string is 4 characters in length like 'Adam' both above snippets considers this as a base64 string which is not correct.

If anyone know better way to detect the Base64 string please let me know and it should work for string of 4 characters in length also.

Thanks in advance.

Bharat Modi
  • 4,158
  • 2
  • 16
  • 27
  • Try this...http://stackoverflow.com/questions/8571501/how-to-check-whether-the-string-is-base64-encoded-or-not, http://stackoverflow.com/questions/10320186/checking-if-an-nsstring-contains-base64-data – Sailendra Nov 09 '16 at 05:58
  • @SailendraKumar Not working. – Bharat Modi Nov 09 '16 at 06:03
  • 'Adam' is a valid base64 string, in that case you can put a check for the length of base64 string – Rajat Nov 09 '16 at 06:05
  • @Rajat I think Adam is not valid string as i have tried to encode some random strings and observed that every base64 encoded string consist '=' (equals) symbol which is not present in 'Adam'. Also can you explain how can i put length check, as in the regex i have tried it already has length check but it is 4. Should i change it? – Bharat Modi Nov 09 '16 at 06:13
  • I am saying as per your regex 'Adam' is a valid string – Rajat Nov 09 '16 at 06:15
  • Why not simply use `NSData initWithBase64EncodedString:options:` and see if you get `nil` back or not? – rmaddy Nov 09 '16 at 06:51
  • @rmaddy Tried, not working for 4 char word english word it returns data. – Bharat Modi Nov 10 '16 at 05:31
  • Your assertion that `Adam` is not a valid base64 encoding is incorrect. As long as the string's length is a multiple of 4 (and it uses the proper 64 characters), then it is valid. Adding `=` to the end to make it a multiple of 4 makes it valid. – rmaddy Nov 10 '16 at 05:41

0 Answers0