-
Notifications
You must be signed in to change notification settings - Fork 29.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
"Invalid key length" when generating a cipher from binary encoded string #6696
Comments
The default string encoding used by the |
Interesting. Based on your information, I was able to work around this by creating a const iv = crypto.randomBytes(16);
const salt = "foobar";
const hash = crypto.createHash("sha1");
hash.update(salt);
let key = Buffer.from(hash.digest("binary").substring(0, 16), "binary");//buffer from binary string.
const cipher = crypto.createCipheriv('aes-128-cbc', key, iv); //works Is this the recommended method of what I'm trying to do? Or am I over-complicating it? |
Yes, you want to use a Buffer, but you don't need to deal with binary strings at all here, just do this: const iv = crypto.randomBytes(16);
const salt = "foobar";
const hash = crypto.createHash("sha1");
hash.update(salt);
// `hash.digest()` returns a Buffer by default when no encoding is given
let key = hash.digest().slice(0, 16);
const cipher = crypto.createCipheriv('aes-128-cbc', key, iv); |
Ah! Much simpler. Thank you so much for your help. |
Basic failing example:
Passing in a binary encoded string with a length of
16
causes the last line to throw. Adding more or removing bytes has no effect.Passing a utf8 encoded line with a length of
16
doesn't throw.This behaviour showed up with Node v6 (v5 worked fine).
The text was updated successfully, but these errors were encountered: