c# - MD5 哈希在 C# 和 Objective C 中不相似

标签 c# objective-c hash md5

我的 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# 版本。我错过了什么?

最佳答案

有两个问题:

  1. C# Unicode 函数返回使用小端字节顺序的 UTF-16 格式。因此,在 Objective-C 中使用 NSUTF16LittleEndianStringEncoding

  2. 由于这是一个 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/

相关文章:

c# - Resources.ApplyResources 上的 System.Resources.MissingManifestResourceException

iOS 钥匙串(keychain)替代方案,无法在另一台设备上恢复

javascript - 如何防止在 $location 哈希搜索参数更改时创建新的 Controller 实例。

c++ - C++中的哈希函数,用于将字符串转换为int

c# - 带有 CDN 的 ASP.NET MVC 多虚拟路径 bundle

c# - 使用结构作为类型检查基元的包装器的开销?

c# - 尝试从 AJAX 帖子重定向

ios - Google Maps API-如何从坐标获取最近的地名,而忽略非特定结果

iphone - iPod 中的重要位置更改通知

security - 为什么盐会造成字典攻击 'impossible' ?