相同的字符串,从VB.net和PHP获得的不同SHA1哈希值

时间:2011-09-07 14:57:36

标签: php vb.net base64 sha1

我对字符串的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

1 个答案:

答案 0 :(得分:6)

嗯,问题是你在.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)));