159
rated 0 times
[
161]
[
2]
/ answers: 1 / hits: 51037
/ 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') + 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
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