Reputation: 163
I want to use aes-128-cbc to decode , but it goes to Invaid key length, what's the matter?
below is the code :
const crypto = require('crypto');
var key = 'DoCKvdLslTuB4y3EZlKate7XMottHski1LmyqJHvUhs'+'=';
var iv = crypto.randomBytes(16) //key.substr(0,16)
var keyhex = new Buffer(key,'base64').toString('hex')
var decipher = crypto.createDecipheriv('aes-128-cbc',keyhex,iv)
next is the error report: crypto.js:267 this._handle.initiv(cipher, toBuf(key), toBuf(iv)); ^
Error: Invalid key length
at new Decipheriv (crypto.js:267:16)
at Object.createDecipheriv (crypto.js:627:10)
at Object.<anonymous> (/home/sheen/workspace/app/base64.js:8:23)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)
at startup (bootstrap_node.js:187:16)
How can I do to solve the problem?
Upvotes: 3
Views: 12527
Reputation: 41
Make sure your secretKey
has string of length 32. In my case, I changed it to something else, and it was causing this "Invalid key length" error:
const cipher = createCipheriv(algorithm, secretKey, iv);
Upvotes: 1
Reputation: 94068
You are mixing up binary and hexadecimals. Hexadecimals is a textual representation or encoding of bytes.
Your key is 32 bytes / 256 bits in size after base 64 decoding. However, then you create a hexadecimal representation of it consisting of 64 characters. These get translated into bytes again, so now your key is 64 bytes / 512 bits in size - and that's an invalid key size.
To use binary, just remove .toString('hex')
and you should be fine.
Upvotes: 3