简体   繁体   中英

How to generate a SHA256 hash of 32 bytes using nodejs (crypto) in order to avoid bad key size error thrown from tweetnacl.js?

I am using the crypto module of node.js to generate a SHA256 hash like this:

const key = crypto.createHmac('sha256', data).digest('hex');

Now, tweetnacl throws the error: bad key size when the key is passed in the secretbox :

nacl.secretbox(data, Rnonc, key);

The parameters are converted into Uint8Array since the secretbox requires arguments to be Uint8Array.

The error: bad key size is throw fromhere in tweetnacl since the crypto_secretbox_KEYBYTES is defined as 32here . The problem is the key returned from crypto is in not 32 bytes size.

I have searched SO and relevant sites, but couldn't find any feasible solution but according to this - the SHA256 hash converted to hex produces:

32 separate hexadecimal numbers (or 32 bytes)

How can I generate a SHA256 key of 32 bytes in order to avoid this error using node.js? Is there something I am doing wrong in generating the SHA256 hash?

The following code snippet solved the issue of generating a 32 bytes SHA256 hash avoiding the bad key size error thrown from tweetnacl.js:

const CryptoJS = require('crypto-js');

let hash   = CryptoJS.SHA256('hello world');
let buffer = Buffer.from(hash.toString(CryptoJS.enc.Hex), 'hex');
let array  = new Uint8Array(buffer);

This always generates a Uint8Array of 32 bytes size. Notice here I had to use the crypto-js module although I preferred to use the native crypto module but I guess I would just use it for now as it is a working solution.

Thanks to @Arihant for pointing to this (check the comment section)

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