Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

crypto.createCipheriv -> cipher.update + cipher.final does not return a Buffer?

I create a cipher passing two buffers. buf1 is they key, a 32 bytes buffer, and buf2, which is the IV, is also a 32 bytes buffer that I slice to only use 16 bytes. Documentation says that cipher.update and cipher.final return a buffer when nothing is specified. That is actually what I wish to happen. While I guess I can just do a new Buffer(crypted, 'binary') to convert it, I'm wondering if I might be doing something wrong.

> var cipher = crypto.createCipheriv('aes-256-cbc', buf1, buf2.slice(0,16));
undefined
> var crypted = cipher.update(new Buffer('this is some test'));
undefined
> crypted += cipher.final();
'!t\u001f\u0004>.\u0012\u0001���K\u001bSiA�]3\u0017�6�&�.��\u0015�V?'
0> Buffer.isBuffer(crypted)
false

http://nodejs.org/api/crypto.html#crypto_class_cipher

I'm using node.js version 0.10.10, which is latest stable and supposedly matches the documentation linked:

$ node -v
v0.10.10

Is this a documentation bug or a mistake from my part? I know that with v0.8 pbkdf2 returned a binary string instead of a buffer and now with 0.10.10 it returns a buffer as stated by the docs. I was hoping for cipher to also work it all with buffers instead of using binary... for consistency.

like image 312
Mamsaac Avatar asked Jun 07 '13 18:06

Mamsaac


People also ask

What does Cipher final do?

The cipher. final() is used to return a buffer or string containing the value of cipher object. It is one of the inbuilt method that is provided by the class Cipher within the crypto module. If an output encoding is specified, a String is returned.

What is crypto Createdecipher?

The crypto. createCipheriv() is a programming interface from the 'crypto' module. It will create and return the Decipher object as per the given algorithm, key, iv and options passed in the function.

Is crypto part of node?

crypto is built into Node. js, so it doesn't require rigorous implementation process and configurations.


1 Answers

You're concatenating them using += which turns buffers into strings. Your code should be something more like this :

var cipher = crypto.createCipheriv('aes-256-cbc', buf1, buf2.slice(0,16));
var cryptedBuffers = [cipher.update(new Buffer('this is some test'))];
cryptedBuffers.push(cipher.final());

// at this point `cryptedBuffers` is an array of buffers which you can turn 
// into a single buffer by doing

var crypted = Buffer.concat(cryptedBuffers);
like image 200
matehat Avatar answered Sep 24 '22 22:09

matehat