Gee1983
Gee1983

Reputation: 37

Hash using a key in Powershell

I'm trying to create a hash in Powershell using a key but I seemed to be getting a different result compared when I'm doing it with Python.

Its a signature that I'm generating for an API call.

The Python code I use is as follows:

nonce         = "20"
client_id     = "mdfgfgkjl3456"
api_key       = "asdkjasdkljsomekey"
message       = nonce + client_id + api_key
secret        = "dsdklfjsdfkljsomesecret"
secret_bytes  = bytes(secret , 'latin-1')
message_bytes = bytes(message , 'latin-1')

signature = hmac.new(
    secret_bytes,
    msg=message_bytes,
    digestmod=hashlib.sha256
).hexdigest().upper()

The Powershell Code that I have is as follows:

$nonce    = "20"
$clientid = "mdfgfgkjl3456"
$apikey   = "asdkjasdkljsomekey"
$message  = $nonce + $clientid + $apikey
$secret   = "dsdklfjsdfkljsomesecret"

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

The Powershell runs but it produces a different Signature then the Python code.

Upvotes: 1

Views: 1887

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174690

In the PowerShell version you perform an additional operation - converting the byte array to a Base64 string - before converting it to upper case:

$signature = ([Convert]::ToBase64String($signature)).ToUpper()

Python on the other hand converts the array to a hexadecimal string.

Change the powershell version to:

$nonce    = "20"
$clientid = "mdfgfgkjl3456"
$apikey   = "asdkjasdkljsomekey"
$message  = $nonce + $clientid + $apikey
$secret   = "dsdklfjsdfkljsomesecret"

$hmacsha = New-Object System.Security.Cryptography.HMACSHA256
$hmacsha.key = [Text.Encoding]::ASCII.GetBytes($secret)
$signature = $hmacsha.ComputeHash([Text.Encoding]::ASCII.GetBytes($message))
$signature = -join($signature |ForEach-Object ToString X2).ToUpper()
$signature

-join($signature |ForEach-Object ToString X2).ToUpper() will produce the exact same format as .hexdigest().upper()

Upvotes: 2

Related Questions