Skip to content

Commit 5a7d4a7

Browse files
authored
crypto: add cipher update/final methods encoding validation
Refs #45189 PR-URL: #45990 Refs: #45189 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Filip Skokan <panva.ip@gmail.com>
1 parent c62a860 commit 5a7d4a7

File tree

2 files changed

+60
-2
lines changed

2 files changed

+60
-2
lines changed

lib/internal/crypto/cipher.js

+8-2
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ const {
2727
ERR_CRYPTO_INVALID_STATE,
2828
ERR_INVALID_ARG_TYPE,
2929
ERR_INVALID_ARG_VALUE,
30+
ERR_UNKNOWN_ENCODING,
3031
}
3132
} = require('internal/errors');
3233

@@ -91,9 +92,14 @@ const privateDecrypt = rsaFunctionFor(_privateDecrypt, RSA_PKCS1_OAEP_PADDING,
9192
'private');
9293

9394
function getDecoder(decoder, encoding) {
94-
encoding = normalizeEncoding(encoding);
95+
const normalizedEncoding = normalizeEncoding(encoding);
9596
decoder = decoder || new StringDecoder(encoding);
96-
assert(decoder.encoding === encoding, 'Cannot change encoding');
97+
if (decoder.encoding !== normalizedEncoding) {
98+
if (normalizedEncoding === undefined) {
99+
throw new ERR_UNKNOWN_ENCODING(encoding);
100+
}
101+
assert(false, 'Cannot change encoding');
102+
}
97103
return decoder;
98104
}
99105

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
'use strict';
2+
const common = require('../common');
3+
if (!common.hasCrypto)
4+
common.skip('missing crypto');
5+
6+
// This test checks if error is thrown in case of wrong encoding provided into cipher.
7+
8+
const assert = require('assert');
9+
const { createCipheriv, randomBytes } = require('crypto');
10+
11+
const createCipher = () => {
12+
return createCipheriv('aes-256-cbc', randomBytes(32), randomBytes(16));
13+
};
14+
15+
{
16+
const cipher = createCipher();
17+
cipher.update('test', 'utf-8', 'utf-8');
18+
19+
assert.throws(
20+
() => cipher.update('666f6f', 'hex', 'hex'),
21+
{ message: /Cannot change encoding/ }
22+
);
23+
}
24+
25+
{
26+
const cipher = createCipher();
27+
cipher.update('test', 'utf-8', 'utf-8');
28+
29+
assert.throws(
30+
() => cipher.final('hex'),
31+
{ message: /Cannot change encoding/ }
32+
);
33+
}
34+
35+
{
36+
const cipher = createCipher();
37+
cipher.update('test', 'utf-8', 'utf-8');
38+
39+
assert.throws(
40+
() => cipher.final('bad2'),
41+
{ message: /^Unknown encoding: bad2$/, code: 'ERR_UNKNOWN_ENCODING' }
42+
);
43+
}
44+
45+
{
46+
const cipher = createCipher();
47+
48+
assert.throws(
49+
() => cipher.update('test', 'utf-8', 'bad3'),
50+
{ message: /^Unknown encoding: bad3$/, code: 'ERR_UNKNOWN_ENCODING' }
51+
);
52+
}

0 commit comments

Comments
 (0)