使用 JavaScript 计算 HMAC-SHA256 签名

Using JavaScipt for calculating HMAC-SHA256 signature

我需要在 Java脚本中计算 HMAC-sha256 签名。我正在使用以下代码。

crypto.createHmac('sha256','abc123').update('{"video-id":"212zpS6bjN77eixPUMUEjR", "exp-time": 1458396066}').digest('hex');
console.log( '1458396066' + '~'+ res);

我得到的结果哈希是:1458396066~d87d121117b46dc28ffec1117cd44cb114b32c1d7bfe5db30ebee7cb89221d3e

这不是我期望的散列。我已经在 PHP 和 Java 中实现了代码,这似乎工作正常。

PHP代码

<?php

 $videoId = "212zpS6bjN77eixPUMUEjR";
 $sharedSecret = "abc123";

function generateToken($videoId, $sharedSecret, $lifeTime)
{
$expiryTime = "1458396066";
$data = sprintf("{\"video-id\":\"%s\", \"exp-time\": %s}" , $videoId, "1458396066");
$hash = hash_hmac ( "sha256", $data , hex2bin($sharedSecret) );
$token = sprintf ("%s~%s","1458396066" , $hash);
return $token;
}

$token = generateToken($videoId, $sharedSecret, 5);
echo $token;
?>

JAVA代码

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.math.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;

public class VMProToken {

public static void main(String[] args) {
    final String videoID = "212zpS6bjN77eixPUMUEjR";
    final String sharedSecret = "abc123";

    try {
        final String token = generateToken(videoID, sharedSecret);
        System.out.println(token);
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        e.printStackTrace();
    }
}

private static String generateToken(String videoId, String sharedSecret)
        throws NoSuchAlgorithmException, InvalidKeyException {
    final String HASH_PATTERN = "{\"video-id\":\"%s\", \"exp-time\": %s}";
    final String HASH_ALGORITHM = "HmacSHA256";

    final String tokenCalcBase = String.format(HASH_PATTERN, videoId, 1458396066);
    System.out.println(tokenCalcBase);
    final Mac hmac = Mac.getInstance(HASH_ALGORITHM);
    final byte[] keyBytes = DatatypeConverter.parseHexBinary(sharedSecret);
    final SecretKeySpec secretKey = new SecretKeySpec(keyBytes, HASH_ALGORITHM);

    hmac.init(secretKey);
    final byte[] hmacBytes = hmac.doFinal(tokenCalcBase.getBytes());
    System.out.println(String.format("%064x", new BigInteger(1, hmacBytes)));
    final String hash = String.format("%064x", new BigInteger(1, hmacBytes));

    return 1458396066 + "~" + hash;
}
}

以上两个代码的正确答案是

1458396066~62dcbe0e20827245454280c51129a9f30d1122eaeafc5ce88f0fec527631f1b5

有人可以告诉我我做错了什么吗?

密钥在PHP和Java代码中被处理为十六进制编码的字符串,但在NodeJS代码中没有。要在 NodeJS 代码中执行相同的操作,请在 createHmac 调用中将 'abc123' 替换为 Buffer.from('abc123', 'hex')