4c74356b41
4c74356b41

Reputation: 72191

Failing to replicate CryptoJS.enc.Hex.parse(hash) in powershell

I'm trying to replicate this code in powershell:

const hmac = CryptoJS.HmacSHA256(CryptoJS.enc.Hex.parse(hash), salt);
seed = hmac.toString(CryptoJS.enc.Hex);

what I think it does - parse the hash variable into a binary representation and then uses that to create a new hash with HmacSHA256. My powershell code:

    $hmacsha = $hmacsha = New-Object System.Security.Cryptography.HMACSHA256
    $hmacsha.key = [Text.Encoding]::UTF8.GetBytes($salt)
    $signatureRaw = $hmacsha.ComputeHash([Text.Encoding]::UTF8.GetBytes($hash))
    $signature = [System.BitConverter]::ToString($signatureRaw).Replace('-','').ToLower()

as far as my understanding goes [Text.Encoding]::UTF8.GetBytes($hash) should achieve that exactly, but the results do not match. code uses same values for hash and salt across languages. JS results:

original hash: 1c46b79912c6109fe8ccf2dde7e8f931e7a95471e38e22865cd1df719a48d405
resulting hash: 4a9732c4a1f4bd2da1e59f3714c943ef662e664e11ea8364bee870916c42ac5c

Powershell results:

original hash: 1c46b79912c6109fe8ccf2dde7e8f931e7a95471e38e22865cd1df719a48d405
resulting hash: 58693c49074149321ec8f440e36f88a3369203c91df8a9c308f78f09ac66733f

Upvotes: 1

Views: 508

Answers (1)

Topaco
Topaco

Reputation: 49415

In the Powershell code the hash must not be UTF8 encoded, but hex decoded, e.g. with

$hash = [byte[]] -split ($hash -replace '..', '0x$& ')

from here.

Using the following code:

$hmacsha = $hmacsha = New-Object System.Security.Cryptography.HMACSHA256
$salt = "0000000000000000004d6ec16dafe9d8370958664c1dc422f452892264c59526"
$hmacsha.key = [Text.Encoding]::UTF8.GetBytes($salt)
$hash = "1c46b79912c6109fe8ccf2dde7e8f931e7a95471e38e22865cd1df719a48d405"
$hash = [byte[]] -split ($hash -replace '..', '0x$& ')
$signatureRaw = $hmacsha.ComputeHash($hash)
$signature = [System.BitConverter]::ToString($signatureRaw).Replace('-','').ToLower()
Write-Output $signature

the result is identical to that of the JavaScript code:

4a9732c4a1f4bd2da1e59f3714c943ef662e664e11ea8364bee870916c42ac5c

Upvotes: 2

Related Questions