本文介绍了crypto.createCipheriv中的密钥长度无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在NodeJS v8.11.0中使用以下代码生成了base64编码的密钥:

I generated a base64-encoded key using this code in NodeJS v8.11.0:

const secret = 'shezhuansauce';
const key = crypto.createHash('sha256').update(String(secret)).digest('base64');
//output is REtgV24bDB7xQYoMuypiBASMEaJbc59nJWChoXbbmsA=

使用密钥,我尝试对字符串进行加密:

Using the key, I try to encrypt a string:

var tobeEncrypted = 'some secret string';
const iv = crypto.randomBytes(16).toString('hex').slice(0, 16);
const cipher = crypto.createCipheriv('aes-256-ctr', key, iv);
const encrypted = cipher.update(String(tobeEncrypted), 'utf8', 'hex') + cipher.final('hex');
console.log(encrypted);

但是,我收到一个错误:

However, I received an error:

crypto.js:219
this._handle.initiv(cipher, toBuf(key), toBuf(iv));
           ^
Error: Invalid key length

密钥必须为base64字符串,因为我会将其存储在Cloud服务中,并且只接收base64字符串.

The key needs to be base64 string as I will store it in a Cloud service and it only receives base64 string.

感谢您的帮助.

推荐答案

您需要的密钥长度为32字节(256位).因此,如果您将关键行更改为:

You need to have a key length of 32 byte (256 bit).So if you change your key line to:

let key = crypto.createHash('sha256').update(String(secret)).digest('base64').substr(0, 32);

它将起作用.

这篇关于crypto.createCipheriv中的密钥长度无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 06:56