2016-11-22 60 views
0

散列在dotnet的核心 字符串時,我得到了奇怪的結果我發現這個類似的問題:Computing SHA1 with ASP.NET Core 並發現如何convert a byte array to string在.NET核心使用SHA-1在.NET核心

這是我的代碼:

private static string CalculateSha1(string text) 
{ 
    var enc = Encoding.GetEncoding(65001); // utf-8 code page 
    byte[] buffer = enc.GetBytes(text); 

    var sha1 = System.Security.Cryptography.SHA1.Create(); 

    var hash = sha1.ComputeHash(buffer); 

    return enc.GetString(hash); 
} 

,這是我的測試:

string test = "broodjepoep"; // forgive me 

string shouldBe = "b2bc870e4ddf0e15486effd19026def2c8a54753"; // according to http://www.sha1-online.com/ 

string wouldBe = CalculateSha1(test); 

System.Diagnostics.Debug.Assert(shouldBe.Equals(wouldBe)); 

輸出:

MHnѐ&ȥGS

enter image description here

我已在NuGet包System.Security.Cryptography.Algorithms安裝(V 4.3.0)

還與GetEncoding(0)試圖獲取系統默認編碼。也沒有工作。

+1

有點偏離主題,但SHA-1被棄用(例如參見https://blog.qualys.com/ssllabs/2014/ 09/09/sha1-deprecation-what-you-need-to-know和https://blogs.windows.com/msedgedev/2016/04/29/sha1-deprecation-roadmap等)。如果你需要強大的加密,你應該離開SHA-1。 – YSK

+0

我知道了,但請告訴我正在使用的外部服務;-)(荷蘭銀行) –

回答

3

我不確定'SHA-1 Online'如何表示你的散列,但由於它是一個散列,它可以包含不能用(UTF8)字符串表示的字符。我覺得你使用Convert.ToBase64String()輕鬆地表示字符串中的字節數組的哈希更好:

var hashString = Convert.ToBase64String(hash); 

要將其轉換回一個字節數組,使用Convert.FromBase64String()

var bytes = Convert.FromBase64String(hashString); 

另請參閱:Converting a md5 hash byte array to a string。其中顯示了在一個字符串中表示散列的多種方法。例如,hash.ToString("X")將使用十六進制表示法。順便說一下,

榮譽broodjepoep。 :-)

+0

謝謝,base64幾乎是正確的。 http://imgur.com/a/CnJbr –

+0

@JPHellemons我不知道'SHA-1 Online'用什麼方法將哈希轉換爲字符串,可能是別的。不過,只要應用程序知道它是哪種格式即可。 –

+0

@JPHollmons:你試過'hash.ToString(「X」)'? – Tseng

1

解決這個問題至今:

var enc = Encoding.GetEncoding(0); 

byte[] buffer = enc.GetBytes(text); 
var sha1 = SHA1.Create(); 
var hash = BitConverter.ToString(sha1.ComputeHash(buffer)).Replace("-",""); 
return hash; 
+0

到目前爲止的問題的解決方案? @Henk Mollema在2016年11月22日回答了這個問題。 –