为什么在C#和PowerShell中以完全相同的代码加密HMAC-SHA1会显示不同的结果? [英] Why does encrypting HMAC-SHA1 in exactly the same code in C# and PowerShell show different results?
问题描述
我一直在尝试使用以下代码在PowerShell中使用HMAC-SHA1对类似于Amazon S3的授权密钥进行加密:
I've been trying to encrypt a Amazon S3-like authorization key with HMAC-SHA1 in PowerShell with the following code:
$str="PUT\n\napplication/x-zip-compressed\nThu, 09 Feb 2017 08:59:43 GMT\n/test-bucket/test-key"
$secret="c334da95a6734ff4a04abd99efca450f"
$sha = [System.Security.Cryptography.KeyedHashAlgorithm]::Create("HMACSHA1")
$sha.Key = [System.Text.Encoding]::UTF8.Getbytes($secret)
$sign = [Convert]::Tobase64String($sha.ComputeHash([System.Text.Encoding]::UTF8.Getbytes(${str})))
echo $sign
此代码输出NcJQ1MapHbyRwC2FzvABYyte5uY=
,根据我们的服务提供商的建议,这是不正确的.
This code outputs NcJQ1MapHbyRwC2FzvABYyte5uY=
, which is incorrect according to our service provider's suggestion.
然后我尝试在C#代码中使用完全相同的类:
Then I tried to use exactly the same classes in C# code:
static void Main(string[] args)
{
var str = "PUT\n\napplication/x-zip-compressed\nThu, 09 Feb 2017 08:59:43 GMT\n/test-bucket/test-key";
var secret = "c334da95a6734ff4a04abd99efca450f";
var sha = System.Security.Cryptography.KeyedHashAlgorithm.Create("HMACSHA1");
sha.Key = System.Text.Encoding.UTF8.GetBytes(secret);
Console.WriteLine(Convert.ToBase64String(sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(str)))); //1S+/P9zgcCCyjwUK1bPKaKeya7A=
Console.Read();
}
奇怪的是,这次,结果是正确的:1S+/P9zgcCCyjwUK1bPKaKeya7A=
Oddly enough, this time, the result is correct: 1S+/P9zgcCCyjwUK1bPKaKeya7A=
我还尝试了Python,它为C#代码辩护.即使输入,类和方法与C#代码中调用的输入,类和方法完全相同,为什么PowerShell仍然会给出错误的答案?
I also tried Python, and it vindicated the C# code. Why did PowerShell run into an incorrect answer even though the inputs, classes and the methods are exactly the same with those which are called in C# code?
推荐答案
这是因为PowerShell中的转义字符是`,而C#中的转义字符是\
.
It's because the escape character in PowerShell is ` while the one in C# is \
.
$str = "PUT`n`napplication/x-zip-compressed`nThu, 09 Feb 2017 08:59:43 GMT`n/test-bucket/test-key"
应该产生预期的结果.
这篇关于为什么在C#和PowerShell中以完全相同的代码加密HMAC-SHA1会显示不同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!