问题
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 from here in tweetnacl
since the crypto_secretbox_KEYBYTES
is defined as 32
here. 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?
回答1:
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)
来源:https://stackoverflow.com/questions/51978889/how-to-generate-a-sha256-hash-of-32-bytes-using-nodejs-crypto-in-order-to-avoi