在Windows窗体中使用SHA-256哈希文本

时间:2012-07-13 19:27:46

标签: c# winforms utf-8 sha

String inputPass = textBox2.Text;
byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(inputPass);
byte[] inputHashedBytes = Sha256.ComputeHash(inputBytes);
String inputHash = Convert.ToBase64String(inputHashedBytes);

我得到一些奇怪的输出:

  

Q9nXCEhAn7RkIOVgBbBeOd5LiH7FWFtDFJ22TMLSoH8 =

输出哈希看起来像这样:

  

43d9d70828409fb46420e56005b05e38de4b887ec5585b43149db64cc2d2a07f

2 个答案:

答案 0 :(得分:7)

Encoding.UTF8.GetString将字节解析为UTF8代码点。

SHA256哈希是一个任意的256位数字,与任何Unicode文本都不对应。

您可能希望通过调用BitConverter.ToString()以十六进制显示二进制值 您也可以致电Convert.ToBase64String()

答案 1 :(得分:6)

// this is where you get the actual binary hash
byte[] inputHashedBytes = Sha256.ComputeHash(inputBytes);

// but you want it in a string format, similar to a variety of UNIX tools
string result = BitConverter.ToString(inputHashedBytes)
   // this will remove all the dashes in between each two characters
   .Replace("-", string.Empty)
   // and make it lowercase
   .ToLower();