我对字符串的SHA1哈希值有一些问题.我正在尝试将用VB.net编写的客户端的文件发送到用 PHP编写的服务器.我的问题是,当我将相同的字符串传递给VB.net和PHP时,VB.net计算的SHA1值与PHP计算的值
例如,我想在Base64中编码一个字符串,然后计算Base64字符串的SHA1哈希值.当计算机从vb.net版本和PHP版本执行此任务时,我得到两个不同的SHA1值,即使显然Base64编码的字符串是相同的:
VB.net:2E97A53B09C482A831540B532845BCAC79BFACCF
PHP:350A2080264E2724D4BCBC521C35264D264A1DAF
我肯定错过了什么,你能指出我正确的方向并告诉我这里我做错了什么吗?
非常感谢你
这是VB.net代码:
Dim cInput As String Dim cBase64 As String Dim objSHA1 As New SHA1CryptoServiceProvider() Dim abBytesToHash() As Byte Dim cHash As String cInput = "the quick brown fox jumps over the lazy dog" cBase64 = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(cInput)) abBytesToHash = System.Text.Encoding.ASCII.GetBytes(cBase64) abBytesToHash = objSHA1.ComputeHash(abBytesToHash) cHash = BitConverter.ToString(objSHA1.ComputeHash(abBytesToHash)) cHash = Replace(cHash, "-", "") MsgBox("BASE64: " + cBase64 + vbNewLine + "SHA1: " + cHash) ' Result is: ' BASE64: dGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZw== ' SHA1: 2E97A53B09C482A831540B532845BCAC79BFACCF
这是PHP代码:
$cInput = "the quick brown fox jumps over the lazy dog"; $cBase64 = base64_encode($cInput); echo("BASE64: " . $cBase64 . "<br />" . "SHA1: " . strtoupper(sha1($cBase64))); // Result is: // BASE64: dGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZw== // SHA1: 350A2080264E2724D4BCBC521C35264D264A1DAF好吧,问题是你在.NET中进行了双重散列,而在PHP中只进行了单次散列.以下是您在.NET中转换为PHP所做的工作:
$cInput = "the quick brown fox jumps over the lazy dog"; $cBase64 = base64_encode($cInput); $sha = sha1($cBase64, true); // The true param returns the raw bytes instead of hex $chash = sha1($sha);
所以你要对它进行双重扫描.要解决此问题,您只需将算法更改为:
cInput = "the quick brown fox jumps over the lazy dog" cBase64 = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(cInput)) abBytesToHash = System.Text.Encoding.ASCII.GetBytes(cBase64) cHash = BitConverter.ToString(objSHA1.ComputeHash(abBytesToHash)) cHash = Replace(cHash, "-", "")
请注意,我所做的就是删除abBytesToHash = objSHA1.ComputeHash(abBytesToHash)行…
或者,您可以更改PHP以执行此操作:
$cInput = "the quick brown fox jumps over the lazy dog"; $cBase64 = base64_encode($cInput); echo "BASE64: " . $cBase64 . "<br />"; echo "SHA1: " . strtoupper(sha1(sha1($cBase64, true)));