我需要在JavaScript中计算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
有人能告诉我我哪里做错了吗?
发布于 2020-03-31 23:07:17
在PHP和Java代码中,键被作为十六进制编码的字符串处理,但在NodeJS代码中却不是。要在NodeJS代码中执行相同的操作,请在createHmac调用中将'abc123'替换为Buffer.from('abc123', 'hex')。
https://stackoverflow.com/questions/60953215
复制相似问题