最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Hmac sha256 base64 and CryptoJS diffrent for nodejs crypto - Stack Overflow

matteradmin6PV0评论

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

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

Share Improve this question asked Feb 24, 2018 at 15:48 Adam AdamskiAdam Adamski 7673 gold badges11 silver badges20 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 1

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.

Post a comment

comment list (0)

  1. No comments so far