簡體   English   中英

使用 JavaScipt 計算 HMAC-SHA256 簽名

[英]Using JavaScipt for calculating HMAC-SHA256 signature

我需要在 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;
?>

爪哇代碼

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,取代'abc123'Buffer.from('abc123', 'hex')createHmac通話。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM