Skip to content

Commit 41d63aa

Browse files
Lukas Möllerzvictor
authored andcommitted
crypto: fix default encoding of LazyTransform
Change the default encoding from latin1 to utf8 and extend the test-crypto tests.
1 parent 82a9afe commit 41d63aa

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed

lib/internal/crypto/lazy_transform.js

Lines changed: 6 additions & 1 deletion
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

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,6 @@ assert.throws(function() {
5353
crypto.createHash('sha1').update({foo: 'bar'});
5454
}, /buffer/);
5555

56-
5756
function assertSorted(list) {
5857
// Array#sort() modifies the list in place so make a copy.
5958
var sorted = util._extend([], list).sort();
@@ -141,3 +140,42 @@ assert.throws(function() {
141140

142141
// Make sure memory isn't released before being returned
143142
console.log(crypto.randomBytes(16));
143+
144+
/**
145+
* Check if the stream function uses utf8 as a default encoding.
146+
**/
147+
148+
function testEncoding(options, assertionHash) {
149+
const hash = crypto.createHash('sha256', options);
150+
let hashValue = '';
151+
152+
hash.on('data', (data) => {
153+
hashValue += data.toString('hex');
154+
});
155+
156+
hash.on('end', () => {
157+
assert.equal(hashValue, assertionHash);
158+
});
159+
160+
hash.write('öäü');
161+
hash.end();
162+
}
163+
164+
// Hash of "öäü" in utf8 format
165+
const assertionHashUtf8 =
166+
'4f53d15bee524f082380e6d7247cc541e7cb0d10c64efdcc935ceeb1e7ea345c';
167+
168+
// Hash of "öäü" in ascii format
169+
const assertionHashAscii =
170+
'cd37bccd5786e2e76d9b18c871e919e6eb11cc12d868f5ae41c40ccff8e44830';
171+
172+
testEncoding(undefined, assertionHashUtf8);
173+
testEncoding({}, assertionHashUtf8);
174+
175+
testEncoding({
176+
defaultEncoding: 'utf8'
177+
}, assertionHashUtf8);
178+
179+
testEncoding({
180+
defaultEncoding: 'ascii'
181+
}, assertionHashAscii);

0 commit comments

Comments
 (0)