Home > Mobile >  Creating a HMAC SHA256 hash in PowerShell
Creating a HMAC SHA256 hash in PowerShell

Time:09-27

I am trying to create a hash using PowerShell code to confirm an webhook subscription using Kamstrup READy API. However, I get errors the following error when confirming a subscription.

PowerShell error code

Then I tried to recreate the example hash in their documentation (under Confirm). I keep getting a different result that do not match their example hash.

$message = @'
{
    "verificationToken" : "e6557603-9121-4c9b-9c38-1a33f56204b0"
}
'@
$secret = '6KVQ05mN9iLvCg=='

$hmacsha = New-Object System.Security.Cryptography.HMACSHA256
$hmacsha.key = [Convert]::FromBase64String($secret)
$signature = $hmacsha.ComputeHash([Text.Encoding]::ASCII.GetBytes($message.ToString()))
$signature = [Convert]::ToBase64String($signature)

echo $signature

$ExpectedHash = 'jm Inr5EVDgLHbpZaTVjInllgm8Ogs7Ok9mLePiciNc='
$ReturnedHash = 'Zo5DukhFluumI/RchKOPQOBheY7rlnzOFLD A0aBbDk='

I'm kind of stuck at this point. I expect that it has to do something with the formatting of the message.

CodePudding user response:

The documentation to which you link states that you must hash the verification token -- not the entire message.

First they must take the verificationToken and hash it using a client secret(Base64 value created in READyManager) and SHA256.

Correcting your code to use just the verification token, I get the expected hash back.

# $message = '{ "verificationToken" : "e6557603-9121-4c9b-9c38-1a33f56204b0" }'
$message = 'e6557603-9121-4c9b-9c38-1a33f56204b0'
$secret = '6KVQ05mN9iLvCg=='

$hmacsha = New-Object System.Security.Cryptography.HMACSHA256
$hmacsha.key = [Convert]::FromBase64String($secret)
$signature = $hmacsha.ComputeHash([Text.Encoding]::Default.GetBytes($message.ToString()))
$signature = [Convert]::ToBase64String($signature)

echo $signature

$ExpectedHash = 'jm Inr5EVDgLHbpZaTVjInllgm8Ogs7Ok9mLePiciNc='
$ReturnedHash = 'Zo5DukhFluumI/RchKOPQOBheY7rlnzOFLD A0aBbDk='

Output:

H:\Temp> .\testps.ps1
jm Inr5EVDgLHbpZaTVjInllgm8Ogs7Ok9mLePiciNc=

A simple case of RTFM :-)

  • Related