javascript – 如何在谷歌关闭库上修复sha256 hmac的加密?

多个Hmac加密器输出谷歌闭包库的不同结果.

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

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关键’ac13’的Hmac和消息’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"
上一篇:在c#中使用SHA 256的哈希X509证书


下一篇:MD5