简体   繁体   中英

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM