Skip to content

Commit a6f7b13

Browse files
atstoyanovaddaleax
authored andcommitted
crypto: fix getDecoder() encoding check
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]>
1 parent 983775d commit a6f7b13

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

lib/crypto.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ Hmac.prototype._transform = Hash.prototype._transform;
100100

101101

102102
function getDecoder(decoder, encoding) {
103-
if (encoding === 'utf-8') encoding = 'utf8'; // Normalize encoding.
103+
encoding = internalUtil.normalizeEncoding(encoding);
104104
decoder = decoder || new StringDecoder(encoding);
105105
assert(decoder.encoding === encoding, 'Cannot change encoding');
106106
return decoder;

test/parallel/test-crypto-cipher-decipher.js

+26
Original file line numberDiff line numberDiff line change
@@ -113,3 +113,29 @@ testCipher2(Buffer.from('0123456789abcdef'));
113113
c.update('update', 'utf-8');
114114
c.final('utf8'); // Should not throw.
115115
}
116+
117+
// Regression tests for https://github.com/nodejs/node/issues/8236.
118+
{
119+
const key = '0123456789abcdef';
120+
const plaintext = 'Top secret!!!';
121+
const c = crypto.createCipher('aes192', key);
122+
var ciph = c.update(plaintext, 'utf16le', 'base64');
123+
ciph += c.final('base64');
124+
125+
var decipher = crypto.createDecipher('aes192', key);
126+
127+
var txt;
128+
assert.doesNotThrow(() => txt = decipher.update(ciph, 'base64', 'ucs2'));
129+
assert.doesNotThrow(() => txt += decipher.final('ucs2'));
130+
assert.strictEqual(txt, plaintext, 'decrypted result in ucs2');
131+
132+
decipher = crypto.createDecipher('aes192', key);
133+
assert.doesNotThrow(() => txt = decipher.update(ciph, 'base64', 'ucs-2'));
134+
assert.doesNotThrow(() => txt += decipher.final('ucs-2'));
135+
assert.strictEqual(txt, plaintext, 'decrypted result in ucs-2');
136+
137+
decipher = crypto.createDecipher('aes192', key);
138+
assert.doesNotThrow(() => txt = decipher.update(ciph, 'base64', 'utf-16le'));
139+
assert.doesNotThrow(() => txt += decipher.final('utf-16le'));
140+
assert.strictEqual(txt, plaintext, 'decrypted result in utf-16le');
141+
}

0 commit comments

Comments
 (0)