Skip to content

Commit 443691a

Browse files
Lukas Mölleraddaleax
Lukas Möller
authored andcommitted
crypto: fix default encoding of LazyTransform
PullRequest #5522 and #5500 described the change of the default encoding into UTF8 in crypto functions. This however was only changed for the non-streaming API. The streaming API still used binary as the default encoding. This commit will change the default streaming API encoding to UTF8 to make both APIs behave the same. It will also add tests to validate the behavior. Refs: #5522 Refs: #5500 PR-URL: #8611 Reviewed-By: Fedor Indutny <fedor.indutny@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Anna Henningsen <anna@addaleax.net>
1 parent c672077 commit 443691a

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

lib/internal/streams/lazy_transform.js

+6-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
const stream = require('stream');
77
const util = require('util');
8+
const crypto = require('crypto');
89

910
module.exports = LazyTransform;
1011

@@ -22,7 +23,11 @@ util.inherits(LazyTransform, stream.Transform);
2223
get: function() {
2324
stream.Transform.call(this, this._options);
2425
this._writableState.decodeStrings = false;
25-
this._writableState.defaultEncoding = 'latin1';
26+
27+
if (!this._options || !this._options.defaultEncoding) {
28+
this._writableState.defaultEncoding = crypto.DEFAULT_ENCODING;
29+
}
30+
2631
return this[prop];
2732
},
2833
set: function(val) {

test/parallel/test-crypto.js

+39
Original file line numberDiff line numberDiff line change
@@ -189,3 +189,42 @@ console.log(crypto.randomBytes(16));
189189
assert.throws(function() {
190190
tls.createSecureContext({ crl: 'not a CRL' });
191191
}, /^Error: Failed to parse CRL$/);
192+
193+
/**
194+
* Check if the stream function uses utf8 as a default encoding.
195+
**/
196+
197+
function testEncoding(options, assertionHash) {
198+
const hash = crypto.createHash('sha256', options);
199+
let hashValue = '';
200+
201+
hash.on('data', (data) => {
202+
hashValue += data.toString('hex');
203+
});
204+
205+
hash.on('end', common.mustCall(() => {
206+
assert.strictEqual(hashValue, assertionHash);
207+
}));
208+
209+
hash.write('öäü');
210+
hash.end();
211+
}
212+
213+
// Hash of "öäü" in utf8 format
214+
const assertionHashUtf8 =
215+
'4f53d15bee524f082380e6d7247cc541e7cb0d10c64efdcc935ceeb1e7ea345c';
216+
217+
// Hash of "öäü" in latin1 format
218+
const assertionHashLatin1 =
219+
'cd37bccd5786e2e76d9b18c871e919e6eb11cc12d868f5ae41c40ccff8e44830';
220+
221+
testEncoding(undefined, assertionHashUtf8);
222+
testEncoding({}, assertionHashUtf8);
223+
224+
testEncoding({
225+
defaultEncoding: 'utf8'
226+
}, assertionHashUtf8);
227+
228+
testEncoding({
229+
defaultEncoding: 'latin1'
230+
}, assertionHashLatin1);

0 commit comments

Comments
 (0)