将 HMAC 函数从 Java 转换为 JavaScript

Lee*_*Lee 1 java cryptography hmac node.js

我打算使用这个 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);
}
Run Code Online (Sandbox Code Playgroud)

由此我得到 Qze5cHfTOjNqwmSSEOd9nEISOobheV833AncGJLin9Y= 的 HMAC

在 node.js 中通过 HMAC 算法传递相同的计数器和密钥时,我得到了不同的 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');
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我得到一个 MAC 为 nW5MKXhnGmgpYwV0qmQtkNBDrCbqQWQSkk02fiQBsGU=

我无法在 javascript 中找到与 SecretKeySpec 类等效的任何内容,因此这可能是缺少的链接。

通过选择算法 Sha-256 并输入解密的 mac 密钥和计数器,我还能够使用此https://quickhash.com/生成与我的程序相同的值 。

Art*_* B. 5

您忘记decryptedMacKey从 Base 64 表示中解码:

var hash = crypto.createHmac('SHA256', new Buffer(decryptedMacKey, 'base64'))
    .update(new Buffer(counter.toString(),'utf8'),'utf8')
    .digest('base64');
Run Code Online (Sandbox Code Playgroud)

给出:

'Qze5cHfTOjNqwmSSEOd9nEISOobheV833AncGJLin9Y='