我有一个包含以下Java代码的项目,该项目可以正常工作...
static String generateHashKey (String apiKey, String msg) throws GeneralSecurityException{
Mac hmacSha256 = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKey = new SecretKeySpec(apiKey.getBytes(), "HmacSHA256");
hmacSha256.init(secretKey);
byte[] bytes = hmacSha256.doFinal(msg.getBytes());
return Hex.encodeHexString(bytes).replace("-","");
}
我正试图用js函数代替它,
import crypto from "crypto";
...
const eMessage = crypto.createHmac("SHA256", apiKey).update(message).digest("base64");
但是它看起来会产生不同的哈希值。如何确保两者的哈希相同?我想念什么?
更新
根据我尝试过的评论和链接
import crypto from "crypto";
import fs from "fs";
import moment from "moment";
import axios from "axios";
import hmacSHA256 from 'crypto-js/hmac-sha256';
import sha256 from 'crypto-js/sha256';
import Base64 from 'crypto-js/enc-base64';
....
const eMessage = Base64.stringify(hmacSHA256(message, key));
const eMessage2 = crypto.createHmac("SHA256", key).update(message).digest("base64");
console.log(eMessage)
console.log(eMessage2)
两个JS库都返回相同的代码(哪个是好的),但与Java的库不匹配,这是不好的。
答案 0 :(得分:0)
所以我遇到的问题是它不在base64中,而是在十六进制中...
import hmacSHA256 from 'crypto-js/hmac-sha256';
import sha256 from 'crypto-js/sha256';
import Hex from 'crypto-js/enc-hex'
const bytes = hmacSHA256(message, key);
const eMessage = bytes.toString(Hex);
答案 1 :(得分:0)
我能够在 node.js 上使用它:
const crypto = require('crypto')
const signature = crypto
.createHmac('sha256', key)
.update(message)
.digest('hex')
console.log('Signature:', signature)
希望这能在未来对其他人有所帮助!