.net 与 Objective c SHA-512 不匹配

2024-02-27

我正在尝试编写用于从 .net 函数在目标中创建 sha512 字符串的函数,该函数是

public static string GetSHA512(string strPlain)
{
    UnicodeEncoding UE = new UnicodeEncoding();
    byte[] HashValue = null;
    byte[] MessageBytes = UE.GetBytes(strPlain);
    System.Security.Cryptography.SHA512Managed SHhash = new System.Security.Cryptography.SHA512Managed();
    string strHex = string.Empty;

    HashValue = SHhash.ComputeHash(MessageBytes);
    foreach (byte b in HashValue)
    {
        strHex += String.Format("{0:x2}", b);
    }
    return strHex;
}

这给出的结果为

input : pass123
output: 2a6353744cc2914c602265f50d2e413d0561368775756392517abb340ef75d52ee0c5d3623ddd1826fd768a13dca8961f5957c75df0d793b9d7537aabe050705

我尝试过如下

-(NSString *)createSHA512:(NSString *)string
{
    const char *cstr = [string cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:string.length];
    uint8_t digest[CC_SHA512_DIGEST_LENGTH];
    CC_SHA512(data.bytes, data.length, digest);
    NSMutableString* output = [NSMutableString  stringWithCapacity:CC_SHA512_DIGEST_LENGTH];

    for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    return output;
}

结果如下

input : pass123
output: fd37ca5ca8763ae077a5e9740212319591603c42a08a60dcc91d12e7e457b024f6bdfdc10cdc1383e1602ff2092b4bc1bb8cac9306a9965eb352435f5dfe8bb0

谁能建议我做错了什么?

为什么这两个值不同?

请纠正我的错误。

EDIT

意思是虽然我尝试将编码更改为NSUTF16StringEncoding and NSUnicodeStringEncoding结果仍然不同,如下

input : pass123
output: 514331e3f7ca0a295539347ebccc4e4f095fe5f3c1df10d43b4d550144c7b30ba9507831893ea63ea22e62e993be529b0d14be7800a90aa0de199d6be62a5f1b

在 Objective C 版本中,您使用 UTF-8 将文本转换为二进制。在 .NET 版本中,您使用的是 UTF-16。那可能不是only差异,但它肯定是相关的。

我将你的 .NET 方法重写为:

public static string GetSHA512(string text)
{
    byte[] messageBytes = Encoding.UTF8.GetBytes(text);

    byte[] hash;
    using (SHA512 hashAlgorithm = SHA512.Create())
    {
        hash = hashAlgorithm.ComputeHash(messageBytes);
    }

    StringBuilder builder = new StringBuilder();
    foreach (byte b in hash)
    {
        builder.AppendFormat("{0:x2}", b);
    }        
    return builder.ToString();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

.net 与 Objective c SHA-512 不匹配 的相关文章

随机推荐