简体   繁体   中英

iOS base64 encoding bug?

I want to base64 encode a NSString. But got the wrong result. Is it the bug of iOS base64 encoding? The int number in characters[] is ASCII code of the character.

int characters[] = {119,38,149,28,73,136,86,199,8,225,36,222,129,63,27,102,41,227,39,113,90, 
             92,150,117,130,106,134,255,182,11,0,198,110,41,175,208,158,57,211,197}; 
 int i = 0; 
 NSString *result = [[NSString alloc] init]; 
 while ( i < 40) { 

     NSString *tempString = [NSString stringWithFormat:@"%c", characters[i]]; 
     result = [result stringByAppendingString:tempString]; 
     i++; 
 } 

 NSData *tempData = [result dataUsingEncoding:NSISOLatin1StringEncoding]; 
 NSString *b64String = [tempData base64EncodedStringWithOptions:0]; 
 NSLog(@"%@",b64String); 

With the above code, I get the result of b64String:

dyaVHEmIVscI4STegT8bZinjJ3FaXJZ1gmqG/7YLxm4pr9CeOdPF

but the correct answer should be:

dyaVHEmIVscI4STegT8bZinjJ3FaXJZ1gmqG/7YLAMZuKa/QnjnTxQ==

Can someone help me to get the right answer ?

The problem is the value 0 in your array. The value 0 is converted to char 0 which is a special character ( null ) used for string termination. Obviously iOS Objective-C treats this special character differently than Python and this is why you get a different result.

The null character should not be found in the middle of a "normal" string. You also have the ASCII code 8 ( backspace ) that shouldn't be found inside a "normal" string.

When removing those special characters you should get the same result.

Edit :

Just to make it clear, the problem is not the base64 encoding. Base64 can handle binary data without problem (and, of course, values 0 and 8). The problem is your conversion from integer values to char values.

I'm not an Objective-C expert but since you seems to be dealing with binary data you might be interested trying something like this :

Byte bytes[] = {119,38,149,28,73,136,86,199,8,225,36,222,129,63,27,102,41,227,39,113,90, 
         92,150,117,130,106,134,255,182,11,0,198,110,41,175,208,158,57,211,197}; 
NSData *tempData = [NSData dataWithBytes:bytes length:40];
NSString *b64String = [tempData base64EncodedStringWithOptions:0]; 
NSLog(@"%@",b64String);   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM