javascriptclojurescriptsha256hmacgoogle-closure-library

How to fix encryption of sha256 hmac on google closure library?


Multiple Hmac encrypters ouput a different result of google closure library.

I've tried multiple Hmac encrypters and they output the same result. However, when using google closure library, both in NodeJS and ClojureScript, it outputs a totally different result.

require("google-closure-library");

function bytesToHex(b) {
    var hexchars = '0123456789abcdef';
    var hexrep = new Array(b.length * 2);
    for (var i = 0; i < b.length; ++i) {
      hexrep[i * 2] = hexchars.charAt((b[i] >> 4) & 15);
      hexrep[i * 2 + 1] = hexchars.charAt(b[i] & 15);
    }
    return hexrep.join('');
}

goog.require('goog.crypt.Hmac');
goog.require('goog.crypt.Sha256');

function getHmac(key, message) {
    var hasher = new goog.crypt.Sha256();
    var hmacer = new goog.crypt.Hmac(hasher, key, 64);
    return bytesToHex(hmacer.getHmac(message));
}

console.log(getHmac('ac13', 'msg'));

sha256 Hmac of key 'ac13' and message 'msg' has proven to be a4a21ba4ddef094c847d4a75ef9a026d329ee12563f3ab00e63261abae55c18d on multiple encryption libraries.


Solution

  • It works just fine. Hmac requires an array of numbers, not a string.

    (defn hmac [key message]
        (let [decode goog.crypt/stringToByteArray
              hasher (goog.crypt.Sha256.)
              hmacer (goog.crypt.Hmac. hasher (decode key))]
            (.getHmac hmacer (decode message))))
    
    (prn (goog.crypt/byteArrayToHex (hmac "ac13" "msg")))
    => "a4a21ba4ddef094c847d4a75ef9a026d329ee12563f3ab00e63261abae55c18d"