cryptography - Issues with a Node.js implementation of AES256 CBC -
let me start off saying new cryptography. i'm trying implement cipher block chaining mode in node.js.
my problem after encryption without decryption stops working 1 decryption function call. here's code:
var crypto = require('crypto'); var encryptionmethod = 'aes-256-cbc'; var vector = new buffer([0xf1, 0x4c, 0xb6, 0xbd, 0x82, 0x93, 0x3c, 0x97, 0x6a, 0x4b, 0x4a, 0xd2, 0xad, 0xd5, 0xa8, 0x6d]); var key = new buffer([59, 92, 128, 239, 136, 26, 19, 26, 226, 234, 53, 71, 157, 113, 209, 96, 111, 83, 167, 123, 217, 107, 124, 31, 238, 176, 58, 110, 161, 82, 81, 69]); var cipher = crypto.createcipheriv(encryptionmethod, key, vector); cipher.setautopadding(false); var decipher = crypto.createdecipheriv(encryptionmethod, key, vector); decipher.setautopadding(false); var encrypt = function(array) { return cipher.update(new buffer(array)); }; var decrypt = function(buffer) { return decipher.update(buffer); }; var data = []; (var = 0; < 32; i++) { data.push(i); } // no problem here (probably because vector updates itself?) console.log(decrypt(encrypt(data))); // <buffer 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f> console.log(decrypt(encrypt(data))); // <buffer 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f> console.log(decrypt(encrypt(data))); // <buffer 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f> // after 1 encryption without decryption stops working. console.log((encrypt(data))); // why can't decrypted correctly? last 16 entries correct. console.log(decrypt(encrypt(data))); // <buffer e2 df 50 63 c7 eb 06 4c 28 19 6d 04 41 bd c0 db 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f> // expected result console.log(decrypt(encrypt(data))); // <buffer 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f>
please see comments above console.log
calls more information. how can make sure decrypt
function works time?
tl;dr: expected behavior.
you're using cipher-block chaining (cbc) mode. encryption , decryption 1 block (16 byte) depends on previous block. block cipher pseudo-random permutation means encrypt or decrypt long give 16 bytes of data.
with code console.log(decrypt(encrypt(data)));
you're encrypting 2 blocks , give them decryption. last ciphertext block processed remembered next update
or final
call.
now, when call console.log((encrypt(data)));
, you're not passing ciphertext decryption function doesn't know intermediate ciphertext block next console.log(decrypt(encrypt(data)));
.
here's illustration:
the last 16 entries correct.
that's because cbc not error-propagating mode. you've encrypting 2 blocks @ same time. since second ciphertext block of decrypt
intact, decrypt correctly.
Comments
Post a Comment