[英]Convert HMAC function from Java to JavaScript
I am tying to implement an HMAC function in NodeJS using this Java function as a reference: 我打算使用此Java函数作为参考在NodeJS中实现HMAC函数:
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);
}
From this I get HMAC of Qze5cHfTOjNqwmSSEOd9nEISOobheV833AncGJLin9Y= 由此得到Qze5cHfTOjNqwmSSEOd9nEISOobheV833AncGJLin9Y =的HMAC =
I am getting a different value for the HMAC when passing the same counter and key through the HMAC algorithm in node. 通过节点中的HMAC算法传递相同的计数器和密钥时,我得到的HMAC值不同。 Here is my code to generate the 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');
When I run this I get a MAC of nW5MKXhnGmgpYwV0qmQtkNBDrCbqQWQSkk02fiQBsGU= 运行此命令时,我得到的MAC为nW5MKXhnGmgpYwV0qmQtkNBDrCbqQWQSkk02fiQBsGU =
I was unable to find any equivalent to the SecretKeySpec class in javascript so that may be the missing link. 我无法在javascript中找到与SecretKeySpec类等效的任何东西,因此可能是缺少的链接。
I was also able to generate the same value as my program using this https://quickhash.com/ by selecting the algorithm Sha-256 and entering the decrypted mac key and counter. 通过选择算法Sha-256并输入解密的Mac密钥和计数器,我还能够使用此https://quickhash.com/生成与程序相同的值。
You forgot to decode the decryptedMacKey
from a Base 64 representation: 您忘记了从Base 64表示中解码decryptedMacKey
的MacKey:
var hash = crypto.createHmac('SHA256', new Buffer(decryptedMacKey, 'base64'))
.update(new Buffer(counter.toString(),'utf8'),'utf8')
.digest('base64');
gives: 给出:
'Qze5cHfTOjNqwmSSEOd9nEISOobheV833AncGJLin9Y='
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.