SHA512 Compute Hash返回乱码

时间:2015-02-01 21:49:11

标签: c# hash ascii sha512

我试图编写一个函数来计算字符串和salt的哈希值,但是它会继续返回看起来像某些编码值的东西,这是完全不可读的。

这是我的方法:

public string HashAndSaltString(string stringtohash, string salt)
{
    byte[] data = System.Text.Encoding.ASCII.GetBytes(stringtohash + salt);
    System.Security.Cryptography.SHA512 hashed = new System.Security.Cryptography.SHA512Managed();
    byte[] result = hashed.ComputeHash(data);
    string final = System.Text.Encoding.ASCII.GetString(result);
    return final;
}

这是它返回的样本:

?mJv?v??a ? ??v??g???s?1t?F?v?6(H????????f.???z??H??(?????
%?O??7J??p4??s=`??&p?u?6?????FX!&????????'???!|?"b??c??
?\w[??2ZB????}??_???P?&^??`r???pw?'???0a???#?!Df??????S+

我认为这与方法的GetBytesGetString部分有关,将其编码为ASCII?

非常感谢一些帮助。

2 个答案:

答案 0 :(得分:9)

散列函数通常将其输入处理为固定长度的字节块,这不是人类可读的。

将此字节数组转换为char序列的常用方法是将base64应用于它。

在C#中你可以这样做:

string final = Convert.ToBase64String(result);

获取字符串,并且:

byte[]backToByteArray = Convert.FromBase64String(final);

获取一个字节数组。

答案 1 :(得分:0)

SHA只是为某些数据创建了一个hash-sum,但没有加密它。 该程序以十六进制模式显示SHA512散列和。

class Program
{
    static void Main(string[] args)
    {
        string text = "This is random text!";

        var sha = new SHA512Managed();
        byte[] hash = sha.ComputeHash(Encoding.ASCII.GetBytes(text));

        Console.WriteLine("Input text: " + text);

        Console.WriteLine("SHA512: ");
        for (int i = 0; i < hash.Length; i += 4)
        {
            Console.Write(" {0}{1}{2}{3} ",
                Convert.ToString(hash[i], 16),
                Convert.ToString(hash[i + 1], 16),
                Convert.ToString(hash[i + 2], 16),
                Convert.ToString(hash[i + 3], 16));
        }

        Console.ReadLine();
    }
}

更多关于wiki