From 1d03df4c5e72c353ca36a44c0fb305ac62fee003 Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Thu, 10 Oct 2019 00:33:15 +0200 Subject: [PATCH] crypto: add Hash.prototype.copy() method MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Make it possible to clone the internal state of a Hash object into a new Hash object, i.e., to fork the state of the object. Fixes: https://github.com/nodejs/node/issues/29903 PR-URL: https://github.com/nodejs/node/pull/29910 Reviewed-By: Colin Ihrig Reviewed-By: Sam Roberts Reviewed-By: Tobias Nießen Reviewed-By: David Carlier Reviewed-By: James M Snell --- doc/api/crypto.md | 37 +++++++++++++++++++++++++++++++ lib/internal/crypto/hash.js | 11 ++++++++- src/node_crypto.cc | 23 ++++++++++++++----- src/node_crypto.h | 2 +- test/parallel/test-crypto-hash.js | 29 ++++++++++++++++++++++++ 5 files changed, 94 insertions(+), 8 deletions(-) diff --git a/doc/api/crypto.md b/doc/api/crypto.md index 345ce542962420..31fa812f915a6d 100644 --- a/doc/api/crypto.md +++ b/doc/api/crypto.md @@ -1041,6 +1041,43 @@ console.log(hash.digest('hex')); // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 ``` +### hash.copy(\[options\]) + + +* `options` {Object} [`stream.transform` options][] +* Returns: {Hash} + +Creates a new `Hash` object that contains a deep copy of the internal state +of the current `Hash` object. + +The optional `options` argument controls stream behavior. For XOF hash +functions such as `'shake256'`, the `outputLength` option can be used to +specify the desired output length in bytes. + +An error is thrown when an attempt is made to copy the `Hash` object after +its [`hash.digest()`][] method has been called. + +```js +// Calculate a rolling hash. +const crypto = require('crypto'); +const hash = crypto.createHash('sha256'); + +hash.update('one'); +console.log(hash.copy().digest('hex')); + +hash.update('two'); +console.log(hash.copy().digest('hex')); + +hash.update('three'); +console.log(hash.copy().digest('hex')); + +// Etc. +``` + ### hash.digest(\[encoding\])