Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript crypto-js how to hash data using sha256 algorithm and key

I am using typescript version 3.7.2 to encrypt data using crypto-js.

Algorithm - sha256

But my code is generating wrong hashed data.

The code is working fine without using any key to hash data like

CryptoJS.SHA256(message).toString(CryptoJS.enc.Hex)

But when I use key it is doing wrong hashing

Here is the full code. Hope you can help. Thank you in advance

    import CryptoJS from 'crypto-js';

    let order_id = 'order_EFph1itQK4z1NQ',
    let payment_id = 'pay_EFph2XRs3vkaB8',

    let generated_signature = CryptoJS.SHA256(order_id + "|" + payment_id, secret).toString(CryptoJS.enc.Hex);
 // secret is some key

value of generated signature (our end)

1a45e3be48f64911d372bcccd9c4dbe7dca9dab716603e4e80c2e55f701bde7a

The hash value to compare with(sent by payment gateway)

e236e8fe62c54546b85dede32c432d4c73c27157840a8ba67cfc09270b53064a

The hash value generated by online website https://www.freeformatter.com/hmac-generator.html#ad-output

e236e8fe62c54546b85dede32c432d4c73c27157840a8ba67cfc09270b53064a

i.e.Hash value generated by online website and sent by payment gateway is matching, that means there is something wrong about our code. Thank you

like image 974
pratik jaiswal Avatar asked Feb 12 '20 10:02

pratik jaiswal


1 Answers

You are expecting to compute SHA256 HMAC, but you are actually computing the SHA256 hash of the message order_id + "|" + payment_id. The secret argument passed to SHA256 function is ignored.

Replace CryptoJS.SHA256 with CryptoJS.HmacSHA256 and your code will work as expected.

like image 177
Tomasz Avatar answered Nov 10 '22 06:11

Tomasz