簡體   English   中英

Sha256正在創建錯誤的哈希

[英]Sha256 is creating wrong hash

我正在嘗試計算sha256 ,並且這段代碼似乎做錯了。

private static string GetSHA256(string text){
    UnicodeEncoding UE = new UnicodeEncoding();
    byte[] hashValue;
    byte[] message = UE.GetBytes(text);

    SHA256Managed hashString = new SHA256Managed();
    string hex = "";

    hashValue = hashString.ComputeHash(message);
    foreach (byte x in hashValue){
        hex += string.Format("{0:x2}", x);
    }
    return hex;
}

我有一台服務器,該服務器根據發送給它的數據生成sha256 ,並且此sha256的值與服務器上的值不匹配。 我嘗試使用PHPJavaScript生成相同的PHP ,並且它們都與服務器生成相同的sha256 ,因此我得出的結論是這一定是錯的。

與PHP我正在使用這個:

$time = time();
$str = "5550d868c5242fb3299a2604|$time|1431619392-36e2d4f3b5de0bfd5f26e3efabbbd99dc2503dab";

$hash = hash("sha256", $str);

這是C#散列的內容

string time = ((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds).ToString();
GetSHA256("5550d868c5242fb3299a2604|"+time+"|1431619392-36e2d4f3b5de0bfd5f26e3efabbbd99dc2503dab")

如您所見,它們都是相同的格式,所以我認為這就是問題所在。 誰能看到我在C#中的散列方式有何不同?

UnicodeEncoding使用UTF-16編碼。 您的編碼應與PHP使用的編碼匹配,可能是UTF-8ASCII (如果僅使用示例中使用的普通,簡單字符,則等效)。

private static string GetSHA256(string text){
    byte[] message = Encoding.UTF8.GetBytes(text);

    SHA256Managed hashString = new SHA256Managed();

    byte[] hashValue = hashString.ComputeHash(message);
    string hex = "";
    foreach (var x in hashValue){
        hex += string.Format("{0:x2}", x);
    }
    return hex;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM