Skip to content

Commit

Permalink
crypto: fix getDecoder() encoding check
Browse files Browse the repository at this point in the history
Normalize the encoding in getDecoder() before using it. Fixes an
AssertionError: "Cannot change encoding" when encoding is "ucs2",
"ucs-2" or "utf-16le"

Fixes: #8236
PR-URL: #8301
Reviewed-By: Anna Henningsen <[email protected]>
Reviewed-By: James M Snell <[email protected]>
  • Loading branch information
atstoyanov authored and addaleax committed Sep 4, 2016
1 parent 983775d commit a6f7b13
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/crypto.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ Hmac.prototype._transform = Hash.prototype._transform;


function getDecoder(decoder, encoding) {
if (encoding === 'utf-8') encoding = 'utf8'; // Normalize encoding.
encoding = internalUtil.normalizeEncoding(encoding);
decoder = decoder || new StringDecoder(encoding);
assert(decoder.encoding === encoding, 'Cannot change encoding');
return decoder;
Expand Down
26 changes: 26 additions & 0 deletions test/parallel/test-crypto-cipher-decipher.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,29 @@ testCipher2(Buffer.from('0123456789abcdef'));
c.update('update', 'utf-8');
c.final('utf8'); // Should not throw.
}

// Regression tests for https://github.com/nodejs/node/issues/8236.
{
const key = '0123456789abcdef';
const plaintext = 'Top secret!!!';
const c = crypto.createCipher('aes192', key);
var ciph = c.update(plaintext, 'utf16le', 'base64');
ciph += c.final('base64');

var decipher = crypto.createDecipher('aes192', key);

var txt;
assert.doesNotThrow(() => txt = decipher.update(ciph, 'base64', 'ucs2'));
assert.doesNotThrow(() => txt += decipher.final('ucs2'));
assert.strictEqual(txt, plaintext, 'decrypted result in ucs2');

decipher = crypto.createDecipher('aes192', key);
assert.doesNotThrow(() => txt = decipher.update(ciph, 'base64', 'ucs-2'));
assert.doesNotThrow(() => txt += decipher.final('ucs-2'));
assert.strictEqual(txt, plaintext, 'decrypted result in ucs-2');

decipher = crypto.createDecipher('aes192', key);
assert.doesNotThrow(() => txt = decipher.update(ciph, 'base64', 'utf-16le'));
assert.doesNotThrow(() => txt += decipher.final('utf-16le'));
assert.strictEqual(txt, plaintext, 'decrypted result in utf-16le');
}

0 comments on commit a6f7b13

Please sign in to comment.