简体   繁体   中英

Why does encrypting HMAC-SHA1 in exactly the same code in C# and PowerShell show different results?

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

This code outputs NcJQ1MapHbyRwC2FzvABYyte5uY= , which is incorrect according to our service provider's suggestion.

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();
}

Oddly enough, this time, the result is correct: 1S+/P9zgcCCyjwUK1bPKaKeya7A=

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?

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"

Should yield the expected result.

The post from @Igor was useful however I also had to create my HMACSHA1 instance like this:

$sha = New-Object System.Security.Cryptography.HMACSHA1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM