Lee
Lee

Reputation: 1662

Convert HMAC function from Java to JavaScript

I am tying to implement an HMAC function in NodeJS using this Java function as a reference:

private static String printMacAsBase64(byte[] macKey, String counter) throws Exception {
    // import AES 128 MAC_KEY
    SecretKeySpec signingKey = new SecretKeySpec(macKey, "AES");

    // create new HMAC object with SHA-256 as the hashing algorithm
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(signingKey);

    // integer -> string -> bytes -> encrypted bytes
    byte[] counterMac = mac.doFinal(counter.getBytes("UTF-8"));

    // base 64 encoded string
    return DatatypeConverter.printBase64Binary(counterMac);
}

From this I get HMAC of Qze5cHfTOjNqwmSSEOd9nEISOobheV833AncGJLin9Y=

I am getting a different value for the HMAC when passing the same counter and key through the HMAC algorithm in node. Here is my code to generate the hmac.

var decryptedMacKey = 'VJ/V173QE+4CrVvMQ2JqFg==';
var counter = 1;

var hash = crypto
    .createHmac('SHA256',decryptedMacKey)
    .update(new Buffer(counter.toString(),'utf8'),'utf8')
    .digest('base64');

When I run this I get a MAC of nW5MKXhnGmgpYwV0qmQtkNBDrCbqQWQSkk02fiQBsGU=

I was unable to find any equivalent to the SecretKeySpec class in javascript so that may be the missing link.

I was also able to generate the same value as my program using this https://quickhash.com/ by selecting the algorithm Sha-256 and entering the decrypted mac key and counter.

Upvotes: 1

Views: 5352

Answers (1)

Artjom B.
Artjom B.

Reputation: 61892

You forgot to decode the decryptedMacKey from a Base 64 representation:

var hash = crypto.createHmac('SHA256', new Buffer(decryptedMacKey, 'base64'))
    .update(new Buffer(counter.toString(),'utf8'),'utf8')
    .digest('base64');

gives:

'Qze5cHfTOjNqwmSSEOd9nEISOobheV833AncGJLin9Y='

Upvotes: 5

Related Questions