Thursday, April 25, 2024
 Popular · Latest · Hot · Upcoming
rated 0 times [  161] [ 2]  / answers: 1 / hits: 51029  / 6 Years ago, thu, june 21, 2018, 12:00:00

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') +'hex');

However, I received an error:

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

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

Any help is appreciated.

More From » node.js


You said you stored a key in BASE 64 and the key is 256 bits (or 32 bytes) (which we see that you computed sha256), so simply get that base64 key, then you can get the bytes easily like this:

const key_in_bytes = Buffer.from(BASE_64_KEY, 'base64')

And you can use this key in bytes as your key as:

const cipher = crypto.createCipheriv('aes-256-ctr', key_in_bytes, iv);

[#54154] Monday, June 18, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.

Total Points: 234
Total Questions: 115
Total Answers: 94

Location: India
Member since Wed, Aug 26, 2020
4 Years ago