如何在javascript中创buildHMAC
我绑定在nodejs中使用java函数作为参考实现hmac函数。 这是我需要模拟的Java函数:
private static String printMacAsBase64(byte[] macKey, String counter) throws Exception { // import AES 128 MAC_KEY SecretKeySpec signingKey = new SecretKeySpec(macKey, "AES"); // create new HMAC object with SHA-256 as the hashing algorithm Mac mac = Mac.getInstance("HmacSHA256"); mac.init(signingKey); // integer -> string -> bytes -> encrypted bytes byte[] counterMac = mac.doFinal(counter.getBytes("UTF-8")); // base 64 encoded string return DatatypeConverter.printBase64Binary(counterMac); }
从这我得到HMAC的Qze5cHfTOjNqwmSSEOd9nEISOobheV833AncGJLin9Y =
当通过节点中的HMACalgorithm传递相同的计数器和密钥时,我正在获得不同的HMAC值。 这是我的代码来生成hmac。
var decryptedMacKey = 'VJ/V173QE+4CrVvMQ2JqFg=='; var counter = 1; var hash = crypto .createHmac('SHA256',decryptedMacKey) .update(new Buffer(counter.toString(),'utf8'),'utf8') .digest('base64');
当我运行这个我得到一个MAC的nW5MKXhnGmgpYwV0qmQtkNBDrCbqQWQSkk02fiQBsGU =
我无法find任何等效于JavaScript中的SecretKeySpec类,以便可能是缺less的链接。
通过selectalgorithmSha-256并input解密的mac密钥和计数器,我也能够使用此https://quickhash.com/生成与我的程序相同的值。
任何帮助表示赞赏。
您忘记了从Base 64表示中decryptedMacKey
的MacKey:
var hash = crypto.createHmac('SHA256', new Buffer(decryptedMacKey, 'base64') ) .update(new Buffer(counter.toString(),'utf8'),'utf8') .digest('base64');
得到:
'Qze5cHfTOjNqwmSSEOd9nEISOobheV833AncGJLin9Y ='