最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Converting crypto hmac to crypto-js hmac string - Stack Overflow

programmeradmin1浏览0评论

I'm trying to take the process of converting a secret hmac string to allow me to test my api in postman. Postman comes pre-installed with cryptojs. This is the process I've got on my test server using 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;
}

This does not match the string generated with cryptojs within postman:

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

Not sure what I'm doing wrong here. Thanks in advance!

I'm trying to take the process of converting a secret hmac string to allow me to test my api in postman. Postman comes pre-installed with cryptojs. This is the process I've got on my test server using 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;
}

This does not match the string generated with cryptojs within postman:

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

Not sure what I'm doing wrong here. Thanks in advance!

Share Improve this question asked Apr 16, 2019 at 23:50 Atlante AvilaAtlante Avila 1,4883 gold badges19 silver badges40 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 15

Okay finally figured it out - crypto-js does not provide actual bytes so encoding everything is necessary:

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);

I had a similar issue. Although a little different from the question, since in my own case the frontend application I was building was not producing the same hash signature as the backend api. Hence, I had to use the following method

function hmacSha256Hex(secret : string, message : any) : string {
        let hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, secret);
        hmac.update(message);
        return CryptoJS.enc.Hex.stringify(hmac.finalize());
}

Ref: CryptoJS Documentation - Hashing: HMAC

发布评论

评论列表(0)

  1. 暂无评论