问题描述
我正在使用node.js的模块来生成这样的SHA256哈希:
I am using the crypto module of node.js to generate a SHA256 hash like this:
const key = crypto.createHmac('sha256', data).digest('hex');
现在,在 secretbox $ c中传递密钥时抛出错误:
错误密钥大小
$ c>:
Now, tweetnacl throws the error: bad key size
when the key is passed in the secretbox
:
nacl.secretbox(data, Rnonc, key);
由于 secretbox
要求参数为Uint8Array。
The parameters are converted into Uint8Array since the secretbox
requires arguments to be Uint8Array.
错误:错误密钥大小
从 tweetnacl
由于 crypto_secretbox_KEYBYTES
被定义为 32
。问题是从 crypto
返回的密钥大小不是32字节。
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.
我搜索了SO和相关网站,但找不到任何可行的解决办法,但根据 - 转换为十六进制的SHA256哈希产生:
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:
如何使用node.js生成32字节的SHA256密钥以避免此错误?在生成SHA256哈希时,我有什么问题吗?
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?
推荐答案
以下代码片段解决了生成32字节SHA256哈希的问题,避免了从tweetnacl.js抛出的错误密钥大小错误:
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);
这总是生成一个32字节的 Uint8Array
尺寸。请注意,我必须使用 crypto-js
模块,尽管我更喜欢使用原生加密
模块,但我猜我它现在只是使用它,因为它是一个有效的解决方案。
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.
感谢@Arihant指向(查看评论部分)
Thanks to @Arihant for pointing to this (check the comment section)
这篇关于如何使用nodejs(crypto)生成32字节的SHA256哈希,以避免从tweetnacl.js抛出错误的密钥大小错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!