如何修复 google 闭包库上的 sha256 hmac 加密?

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

多个 Hmac 加密器输出 google 闭包库的不同结果。

我试过多个 Hmac 加密器,它们输出相同的结果。但是,当在 NodeJS 和 ClojureScript 中使用 google 闭包库时,它会输出完全不同的结果。

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' 在多个加密库上被证明是a4a21ba4ddef094c847d4a75ef9a026d329ee12563f3ab00e63261abae55c18d。

它工作得很好。 Hmac 需要 array of numbers,而不是字符串。

(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"