使用Python和Powershell计算MD5哈希时,我得到了不同的结果。似乎Python代码返回正确的'版本
不使用多行变量时,结果是相同的。所以,如果我设置xml =' test'他们都给出了相同的结果。
我想也许它与格式化或换行符有关,但也许我的Powershell代码还有其他问题。
当我使用Powershell计算哈希时,我使用它:
Function Get-StringHash([String] $String,$HashName = "MD5")
{
$StringBuilder = New-Object System.Text.StringBuilder
[System.Security.Cryptography.HashAlgorithm]::Create($HashName).ComputeHash([System.Text.Encoding]::UTF8.GetBytes($String))|%{
[Void]$StringBuilder.Append($_.ToString("x2"))
}
$StringBuilder.ToString()
}
$xml = @"
<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<!DOCTYPE OPS_envelope SYSTEM 'ops.dtd'>
<OPS_envelope>
<header>
<version>0.9</version>
</header>
<body>
<data_block>
<dt_assoc>
<item key="protocol">XCP</item>
<item key="action">get</item>
<item key="object">nameserver</item>
<item key="domain">domainname</item>
<item key="attributes">
<dt_assoc>
<item key="name">all</item>
</dt_assoc>
</item>
</dt_assoc>
</data_block>
</body>
</OPS_envelope>
"@
$key = '12345'
$obj = $xml + $key
$signature = Get-StringHash $obj "MD5"
$signature
返回结果: 1680ea9b5d8b09ef6c9bd02641246fc4
当我使用Python时:
import hashlib
xml = '''
<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<!DOCTYPE OPS_envelope SYSTEM 'ops.dtd'>
<OPS_envelope>
<header>
<version>0.9</version>
</header>
<body>
<data_block>
<dt_assoc>
<item key="protocol">XCP</item>
<item key="action">get</item>
<item key="object">nameserver</item>
<item key="domain">domainname</item>
<item key="attributes">
<dt_assoc>
<item key="name">all</item>
</dt_assoc>
</item>
</dt_assoc>
</data_block>
</body>
</OPS_envelope>
'''
key = '12345'
md5_obj = hashlib.md5()
md5_obj.update(xml + key)
signature = md5_obj.hexdigest()
print("SIGNATURE: " + signature)
结果如下: d2faf89015178b2ed50ed4a90cbab9ff
答案 0 :(得分:2)
两个输入字符串实际上并不相同,原因有两个:
1)python中的三重引号字符串在引号的同一行开始和结束 - 此处 - PowerShell中的字符串从const routes: Routes = [
{
...
{ path: 'header-a', component: HeaderAComponent, outlet: 'header' },
^^^^^^
}
/ @"
下方的行开始,并在@'
上方的行上结束{1}} / "@
,请更改:
'@
2)PowerShell中的换行符 - 字符串默认为$xml = @'
<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<!DOCTYPE OPS_envelope SYSTEM 'ops.dtd'>
<OPS_envelope>
<header>
<version>0.9</version>
</header>
<body>
<data_block>
<dt_assoc>
<item key="protocol">XCP</item>
<item key="action">get</item>
<item key="object">nameserver</item>
<item key="domain">domainname</item>
<item key="attributes">
<dt_assoc>
<item key="name">all</item>
</dt_assoc>
</item>
</dt_assoc>
</data_block>
</body>
</OPS_envelope>
'@
,在Windows中为[Environment]::NewLine
,而python默认为\r\n
,因此请确保将其标准化:
\n