简体   繁体   English

iOS base64编码错误?

[英]iOS base64 encoding bug?

I want to base64 encode a NSString. 我想base64编码一个NSString。 But got the wrong result. 但是得到了错误的结果。 Is it the bug of iOS base64 encoding? 是iOS base64编码的错误吗? The int number in characters[] is ASCII code of the character. 字符[]中的整数是字符的ASCII码。

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: 使用上面的代码,我得到b64String的结果:

dyaVHEmIVscI4STegT8bZinjJ3FaXJZ1gmqG/7YLxm4pr9CeOdPF dyaVHEmIVscI4STegT8bZinjJ3FaXJZ1gmqG / 7YLxm4pr9CeOdPF

but the correct answer should be: 但是正确的答案应该是:

dyaVHEmIVscI4STegT8bZinjJ3FaXJZ1gmqG/7YLAMZuKa/QnjnTxQ== dyaVHEmIVscI4STegT8bZinjJ3FaXJZ1gmqG / 7YLAMZuKa / QnjnTxQ ==

Can someone help me to get the right answer ? 有人可以帮助我找到正确的答案吗?

The problem is the value 0 in your array. 问题是数组中的值为0 The value 0 is converted to char 0 which is a special character ( null ) used for string termination. 0转换为char 0,这是用于字符串终止的特殊字符( null )。 Obviously iOS Objective-C treats this special character differently than Python and this is why you get a different result. 显然,iOS Objective-C对这种特殊字符的处理方式与Python不同,这就是为什么您得到不同结果的原因。

The null character should not be found in the middle of a "normal" string. null字符不应在“正常”字符串的中间找到。 You also have the ASCII code 8 ( backspace ) that shouldn't be found inside a "normal" string. 您还具有不应该在“普通”字符串中找到的ASCII码8backspace )。

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编码。 Base64 can handle binary data without problem (and, of course, values 0 and 8). Base64可以毫无问题地处理二进制数据(当然,值0和8)。 The problem is your conversion from integer values to char values. 问题是您从整数值转换为char值。

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 : 我不是Objective-C专家,但是由于您似乎正在处理二进制数据,因此您可能有兴趣尝试执行以下操作:

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);   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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