Ari*_*ies 13 c# powershell sha1 hmac
我一直在尝试使用PowerShell中的HMAC-SHA1加密类似Amazon S3的授权密钥,代码如下:
$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
Run Code Online (Sandbox Code Playgroud)
此代码输出NcJQ1MapHbyRwC2FzvABYyte5uY=,根据我们服务提供商的建议不正确.
然后我尝试在C#代码中使用完全相同的类:
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();
}
Run Code Online (Sandbox Code Playgroud)
奇怪的是,这一次,结果是正确的: 1S+/P9zgcCCyjwUK1bPKaKeya7A=
我也试过Python,它证明了C#代码.为什么PowerShell遇到错误的答案,即使输入,类和方法与C#代码中调用的那些完全相同?
Igo*_*gor 19
这是因为PowerShell中的转义字符是`而C#中的转义字符是\.
$str = "PUT`n`napplication/x-zip-compressed`nThu, 09 Feb 2017 08:59:43 GMT`n/test-bucket/test-key"
Run Code Online (Sandbox Code Playgroud)
应该产生预期的结果.
| 归档时间: |
|
| 查看次数: |
1722 次 |
| 最近记录: |