SHA256在散列中返回无效字符

时间:2017-03-27 09:18:03

标签: c# unity3d hash

我试图在Unity的C#代码中使用SHA256获取字符串的哈希值。我做了以下事情:

using UnityEngine;
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

public class URLGenerator : MonoBehaviour {

    void Start () {

        Debug.Log("myString: " + myString);

        SHA256 mySHA256 = SHA256Managed.Create(); 
        myHashBytes = mySHA256.ComputeHash(Encoding.ASCII.GetBytes(myString)); 
        string myHash = Encoding.ASCII.GetString(myHashBytes); 

        Debug.Log("myHash: " + myHash);
    }
}

结果如下:

myString: 3272017110434AMbx78va23
myHash: ?)wP<??|-?)??V:?3?6"???????a??

?代表无效字符吗?如果是的话,他们为什么会出现?我忘记了什么吗?

1 个答案:

答案 0 :(得分:2)

而不是

myHashBytes = mySHA256.ComputeHash(Encoding.ASCII.GetBytes(myString)); 
string myHash = Encoding.ASCII.GetString(myHashBytes); 

你应该

static string GetHash(SHA256 hash, string input)
{

    // Convert the input string to a byte array and compute the hash.
    byte[] data = hash.ComputeHash(Encoding.UTF8.GetBytes(input));

    // Create a new Stringbuilder to collect the bytes
    // and create a string.
    StringBuilder sBuilder = new StringBuilder();

    // Loop through each byte of the hashed data 
    // and format each one as a hexadecimal string.
    for (int i = 0; i < data.Length; i++)
    {
        sBuilder.Append(data[i].ToString("x2"));
    }

    // Return the hexadecimal string.
    return sBuilder.ToString();
}

获取哈希的字符串表示。

请参阅HashAlgorithm.ComputeHash