16

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?

1
  • Do you have a repo with the full solution? I keep getting AccessDenied :( Commented Apr 9, 2021 at 12:35

2 Answers 2

22

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.

Sign up to request clarification or add additional context in comments.

5 Comments

That's what i thought too, but when I test it that way I still don't get the expected result.
Tested with powershell it does return 1S+/P9zgcCCyjwUK1bPKaKeya7A=
The original question had a different expected result. This answer is correct. I didn't bother to check the C# version...
Thanks @Igor , you are right, I got the correct result.
Sorry @DanField, since I changed the key, I forgot to update the output.
0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.