首页 > 解决方案 > 将加密 hmac 转换为 crypto-js hmac 字符串

问题描述

我正在尝试转换一个秘密的 hmac 字符串以允许我在邮递员中测试我的 api。Postman 预装了 cryptojs。这是我在测试服务器上使用加密的过程:

const crypto = require('crypto');
const generateHmac = (privateKey, ts) => {
    const hmac = crypto.createHmac('sha256', privateKey);
    hmac.update(ts);
    const signature = hmac.digest('hex');
    return signature;
}

这与 postman 中使用 cryptojs 生成的字符串不匹配:

const createHmacString = (privateKey, ts) => {
    const hmac = CryptoJS.HmacSHA256(ts, privateKey).toString(CryptoJS.enc.Hex)
    return hmac;
}

不知道我在这里做错了什么。提前致谢!

标签: javascriptnode.jsencryptionhmacpostman-pre-request-script

解决方案


好的,终于想通了——crypto-js 不提供实际的字节,因此对所有内容进行编码都是必要的:

const createHmacString = (privateKey, ts) => {
    const key = CryptoJS.enc.Utf8.parse(privateKey)
    const timestamp = CryptoJS.enc.Utf8.parse(ts)
    const hmac = CryptoJS.enc.Hex.stringify(CryptoJS.HmacSHA256(timestamp, key))

    //  const hmac = CryptoJS.HmacSHA256(ts, privateKey).toString(CryptoJS.enc.Hex)
    return hmac;
}

let ts = new Date().getTime();
const signature = createHmacString("your-private-key", ts);

推荐阅读