将crypto hmac转换为crypto-js hmac字符串

问题描述 投票:0回答:1

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

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

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

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

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

javascript node.js encryption hmac postman-pre-request-script
1个回答
0
投票

好吧终于明白了 - 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);
© www.soinside.com 2019 - 2024. All rights reserved.