Search code examples
c#powershellsha1hmac

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?


Solution

  • 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.