且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

转换哈希的十六进制字符串

更新时间:2023-02-03 09:25:25

要获得散列,使用的 System.Security.Cryptography.SHA1Managed

To get the hash, use the System.Security.Cryptography.SHA1Managed class.

修改:是这样的:

byte[] hashBytes = new SHA1Managed().ComputeHash(Encoding.UTF8.GetBytes(str));

要哈希转换为十六进制字符串,使用下面的代码:

To convert the hash to a hex string, use the following code:

BitConverter.ToString(hashBytes).Replace("-", "");

如果你想有一个更快的实现,使用下面的函数:

If you want a faster implementation, use the following function:

private static char ToHexDigit(int i) {
    if (i < 10) 
        return (char)(i + '0');
    return (char)(i - 10 + 'A');
}
public static string ToHexString(byte[] bytes) {
    var chars = new char[bytes.Length * 2 + 2];

    chars[0] = '0';
    chars[1] = 'x';

    for (int i = 0; i < bytes.Length; i++) {
        chars[2 * i + 2] = ToHexDigit(bytes[i] / 16);
        chars[2 * i + 3] = ToHexDigit(bytes[i] % 16);
    }

    return new string(chars);
}