1
votes

I'm trying to generate HMAC of a message. The algo for HMAC generation is SHA256. The issue is i have a base64 encoded key(shared secret). How can i decode this secret to get the required hmac

Sample code:

var hmac = require('crypto').createHmac('SHA256', "SOME_BASE64_ENCODED_SHARED_SECRET").update("MESSAGE").digest('base64');

This hmac is sent to a java service. The way it does hmac generation is as follows:

Mac mac = Mac.getInstance("HmacSha256");
SecretKey sharedKey = new SecretKeySpec(Base64.getDecoder().decode("SOME_BASE64_ENCODED_SHARED_SECRET"), "TlsPremasterSecret");
mac.init(sharedKey);
byte[] messageBytes = "MESSAGE".getBytes("UTF-8");
byte[] expectedHmac = mac.doFinal(messageBytes);
String hmac = Base64.getEncoder().encodeToString(expectedHmac));

Now, the HMACs generated by my nodejs code does not match with Java service code. How do i solve this problem?

2
Did you try decoding the base64-encoded secret before passing it to createHmac() (e.g. crypto.createHmac('SHA256', new Buffer('base64-encoded-secret', 'base64')).update(...)?mscdex
Yay! That worked! Thanks a ton. :)nobrains

2 Answers

2
votes

The base64-encoded secret needs to be decoded before passing it to crypto.createHmac():

var secret = Buffer.from('SOME_BASE64_ENCODED_SHARED_SECRET', 'base64');
var hmac = require('crypto').createHmac('SHA256', secret)
                            .update('MESSAGE')
                            .digest('base64');
1
votes
//include crypto
var crypto = require('crypto');

var yourMessage = 'your signature to be hashed using HMAC SHA256';
var sharedSecret = 'your shared secret key';
//generate hmac sha256 hash
var hmacSignature = crypto.createHmac('SHA256', new Buffer(sharedSecret, 'base64')).update(yourMessage).digest('base64');

Above worked for me too.

Note: HMAC SHA256 is hash value, it cannot be decoded. Based on unique secret and unique message (generally date-time is used) a unique hash is created. Client sends this hash value and server generates its own hash value using same algorith, if both hash value match then authorization is successful.

I spent lot of time troubleshooting this. Hope above info help others.