1

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.

1 Answer 1

5

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='
Sign up to request clarification or add additional context in comments.

1 Comment

I knew I had to be overlooking something. I will give it a try. Thanks!

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.