简体   繁体   中英

Hmac sha256 base64 and CryptoJS diffrent for nodejs crypto

Let say we have simple msg and key:

message = 'simple'

private_key = '123456789'; Using that in angular project with CryptoJS:

const signature = CryptoJS.HmacSHA256('simple', '123456789');
const signatureBase = signature.toString(CryptoJS.enc.Base64);

result for me is:

lvs7rQTe1EDTLAS1GVWWsNG5ZaYVCh9aaYc+NoEunC4=

using that in msg and key in node:

var hmacsignature = crypto.createHmac('sha256', new Buffer("123456789", "base64"))
.update("simple")
.digest()
.toString('base64');

result is:

nYu2PGqfRDWnHbT649q0gc+7DcIq8iwcwHAQQa5T2HY=

Can you tell me which one is correct and how to get same thing is angular?

Thanks

In browser string encoding usually is UTF-8, so use UTF-8 as string encoding should fix it. BTW, you should explicitly set string encoding in both side to make sure you will get same result.

var hmacsignature = crypto.createHmac('sha256', Buffer.from('123456789', 'utf8'))
.update("simple")
.digest()
.toString('base64');

And new Buffer(string) is deprecated, use Buffer.from(string[, encoding]) if you can.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM