From d3a84bea7b361e786b43f5a00c1dfcc0eadb07ea Mon Sep 17 00:00:00 2001 From: SAWADA Tadashi Date: Sun, 19 Jun 2011 16:54:34 +0900 Subject: [PATCH] Fix crypto encryption/decryption with Base64. Fixes #738. Fixes #1205. --- src/node_crypto.cc | 13 +++++++++++++ test/simple/test-crypto.js | 19 +++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/src/node_crypto.cc b/src/node_crypto.cc index e012a2f312e..05a11122124 100644 --- a/src/node_crypto.cc +++ b/src/node_crypto.cc @@ -1823,6 +1823,19 @@ class Cipher : public ObjectWrap { outString = Encode(out_hexdigest, out_hex_len, BINARY); delete [] out_hexdigest; } else if (strcasecmp(*encoding, "base64") == 0) { + // Check to see if we need to add in previous base64 overhang + if (cipher->incomplete_base64!=NULL){ + unsigned char* complete_base64 = new unsigned char[out_len+cipher->incomplete_base64_len+1]; + memcpy(complete_base64, cipher->incomplete_base64, cipher->incomplete_base64_len); + memcpy(&complete_base64[cipher->incomplete_base64_len], out_value, out_len); + delete [] out_value; + + delete [] cipher->incomplete_base64; + cipher->incomplete_base64=NULL; + + out_value=complete_base64; + out_len += cipher->incomplete_base64_len; + } base64(out_value, out_len, &out_hexdigest, &out_hex_len); outString = Encode(out_hexdigest, out_hex_len, BINARY); delete [] out_hexdigest; diff --git a/test/simple/test-crypto.js b/test/simple/test-crypto.js index 0ccf19a0914..b761b431ce6 100644 --- a/test/simple/test-crypto.js +++ b/test/simple/test-crypto.js @@ -308,6 +308,25 @@ txt += decipher.final('utf8'); assert.equal(txt, plaintext, 'encryption and decryption'); +// encryption and decryption with Base64 +// reported in https://github.com/joyent/node/issues/738 +var plaintext = + '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + + 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJjAfaFg**'; +var cipher = crypto.createCipher('aes256', '0123456789abcdef'); + +// encrypt plaintext which is in utf8 format +// to a ciphertext which will be in Base64 +var ciph = cipher.update(plaintext, 'utf8', 'base64'); +ciph += cipher.final('base64'); + +var decipher = crypto.createDecipher('aes256', '0123456789abcdef'); +var txt = decipher.update(ciph, 'base64', 'utf8'); +txt += decipher.final('utf8'); + +assert.equal(txt, plaintext, 'encryption and decryption with Base64'); + + // Test encyrption and decryption with explicit key and iv var encryption_key = '0123456789abcd0123456789'; var iv = '12345678';