Skip to content

Commit

Permalink
crypto: fix Hash and Cipher abort on end
Browse files Browse the repository at this point in the history
fix Hash and Cipher aborting when using end with
hex and specific lengths of chunks

fixes: nodejs#38015
  • Loading branch information
Linkgoron committed Apr 27, 2021
1 parent 0577fe3 commit b89f9ab
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 4 deletions.
12 changes: 10 additions & 2 deletions lib/internal/crypto/cipher.js
Original file line number Diff line number Diff line change
Expand Up @@ -154,8 +154,16 @@ ObjectSetPrototypeOf(Cipher.prototype, LazyTransform.prototype);
ObjectSetPrototypeOf(Cipher, LazyTransform);

Cipher.prototype._transform = function _transform(chunk, encoding, callback) {
this.push(this[kHandle].update(chunk, encoding));
callback();
let error = null;
try {
if (typeof chunk === 'string') {
validateEncoding(chunk, encoding);
}
this.push(this[kHandle].update(chunk, encoding));
} catch (err) {
error = err;
}
callback(error);
};

Cipher.prototype._flush = function _flush(callback) {
Expand Down
9 changes: 7 additions & 2 deletions lib/internal/crypto/hash.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,13 @@ Hash.prototype.copy = function copy(options) {
};

Hash.prototype._transform = function _transform(chunk, encoding, callback) {
this[kHandle].update(chunk, encoding);
callback();
let error = null;
try {
this.update(chunk, encoding);
} catch (err) {
error = err;
}
callback(error);
};

Hash.prototype._flush = function _flush(callback) {
Expand Down
25 changes: 25 additions & 0 deletions test/parallel/test-crypto-binary-default.js
Original file line number Diff line number Diff line change
Expand Up @@ -579,6 +579,31 @@ assert.throws(
name: 'TypeError'
});

{
const hash = crypto.createHash('sha1');
hash.on('error', common.mustCall((err) => {
assert.strictEqual(err.code, 'ERR_INVALID_ARG_VALUE');
assert.strictEqual(err.name, 'TypeError');
}));
hash.end('str', 'hex', common.mustCall((err) => {
assert.ok(err instanceof Error, 'err should be an error');
assert.strictEqual(err.code, 'ERR_STREAM_DESTROYED');
assert.strictEqual(err.name, 'Error');
}));
}

{
const decipher = crypto.createDecipher('des-ede3-cbc', '');
decipher.on('error', common.mustCall((err) => {
assert.strictEqual(err.code, 'ERR_INVALID_ARG_VALUE');
assert.strictEqual(err.name, 'TypeError');
}));
decipher.end('str', 'hex', common.mustCall((err) => {
assert.ok(err instanceof Error, 'err should be an error');
assert.strictEqual(err.code, 'ERR_STREAM_DESTROYED');
assert.strictEqual(err.name, 'Error');
}));
}

// Test Diffie-Hellman with two parties sharing a secret,
// using various encodings as we go along
Expand Down

0 comments on commit b89f9ab

Please sign in to comment.