Objective C 中的 hash256 问题
当我使用此代码在我的iPhone应用程序中生成hash256时:
unsigned char hashedChars[32];
NSString *inputString;
inputString = [NSString stringWithFormat:@"hello"];
CC_SHA256([inputString UTF8String],
[inputString lengthOfBytesUsingEncoding:NSASCIIStringEncoding ],
hashedChars);
NSData * hashedData = [NSData dataWithBytes:hashedChars length:32];
inputString的hash256已正确创建,但如果我使用像这样的字符串@“\ x00 \ x25 \ x53 \ b4”,则hash256与真实的不同带有“\x”字符的字符串。 我认为问题在于编码“UTF8”而不是ascii。 谢谢!
when i use this code for generate an hash256 in my iPhone app:
unsigned char hashedChars[32];
NSString *inputString;
inputString = [NSString stringWithFormat:@"hello"];
CC_SHA256([inputString UTF8String],
[inputString lengthOfBytesUsingEncoding:NSASCIIStringEncoding ],
hashedChars);
NSData * hashedData = [NSData dataWithBytes:hashedChars length:32];
The hash256 of inputString, is created correctly, but if i use a string like this @"\x00\x25\x53\b4", the hash256 is different from the real string with "\x" characters.
I think that the problem is in encoding "UTF8" instead of ascii.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会对第一个字符“\x00”表示怀疑 - 这将终止任何认为它处理“常规 C 字符串”的内容。
不确定 lengthOfBytesUsingEncoding: 是否考虑到这些内容,但我会尝试一下。
I would be suspicious of the first character, "\x00" - thats going to terminate anything that thinks its dealing with "regular C strings".
Not sure whether lengthOfBytesUsingEncoding: takes that stuff into account, but its something I'd experiment with.
您将使用
[inputString UTF8String]
获取字节,但使用[inputString lengthOfBytesUsingEncoding:NSASCIIStringEncoding]
获取长度。这显然是错误的。此外(假设您的意思是“\xB4”并且它变成了非 ASCII 格式的内容),“\xB4”不太可能是 ASCII 格式的。 NSString 的文档说因此您正在计算空字符串的哈希值。当然是错误的。
如果只生成一次数据,则不太可能出现问题:
You're getting the bytes with
[inputString UTF8String]
but the length with[inputString lengthOfBytesUsingEncoding:NSASCIIStringEncoding]
. This is obviously wrong. Moreover (assuming you mean "\xB4" and that it turns into something not in ASCII), "\xB4" is not likely to be in ASCII. The docs for NSString saySo you're calculating the hash of the empty string. Of course it's wrong.
You're less likely to have problems if you only generate the data once: