我的 MD5 哈希字符串在 C# 和 Objective C 中是相同的。
在 C# 中:
GetMD5("password123") // Equals: "f22ec811b8bf1cb6ac3aea13d3fcfebf"
private static string GetMD5(string text)
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] hashValue;
byte[] message = UE.GetBytes(text);
MD5 hashString = new MD5CryptoServiceProvider();
string hex = "";
hashValue = hashString.ComputeHash(message);
foreach (byte x in hashValue)
{
hex += String.Format("{0:x2}", x);
}
return hex;
}
在 Objective-C 中:
[self md5HexDigest:@"password123"] // Equals: @"83878c91171338902e0fe0fb97a8c47a"
+ (NSString*)md5HexDigest:(NSString*)input {
const char* str = [input cStringUsingEncoding:NSUnicodeStringEncoding];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(str, strlen(str), result);
NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2];
for(int i = 0; i<CC_MD5_DIGEST_LENGTH; i++) {
[ret appendFormat:@"%02x",result[i]];
}
return ret;
}
我需要修改 Objective C 版本以匹配 C# 版本。我错过了什么?
最佳答案
有两个问题:
C#
Unicode
函数返回使用小端字节顺序的 UTF-16 格式。因此,在 Objective-C 中使用NSUTF16LittleEndianStringEncoding
。由于这是一个 UTF16 字符串,因此使用
strlen
将不起作用。您应该使用NSData
,然后可以使用length
方法:- (NSString*)md5HexDigest:(NSString*)input { NSData *data = [input dataUsingEncoding:NSUTF16LittleEndianStringEncoding]; unsigned char result[CC_MD5_DIGEST_LENGTH]; CC_MD5([data bytes], [data length], result); NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2]; for(int i = 0; i<CC_MD5_DIGEST_LENGTH; i++) { [ret appendFormat:@"%02x",result[i]]; } return ret; }
这将生成您的 f22ec811b8bf1cb6ac3aea13d3fcfebf
值。
关于c# - MD5 哈希在 C# 和 Objective C 中不相似,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20924822/