Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 19 additions & 16 deletions lib/utils/crypto-util.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,25 @@
const crypto = require('crypto');

/**
* Export `StringUtil`.
* @module CryptoUtil
*/

module.exports = {
/**
*
* @param algorithm {String} the hash algorithm, default is 'sha256'
* @param data {Buffer|String|TypedArray|DataView} the data to hash
* @param encoding {String|undefined} optional, the encoding to calculate the
* digest
* @return {Buffer|String} if {encoding} undefined a {Buffer} is returned, otherwise a {String}
*/
createHash: function({ algorithm = 'sha256', data = undefined, encoding = undefined }) {
return crypto
.createHash(algorithm)
.update(data)
.digest(encoding);
}
/**
* Creates a new hash by given algorithm, data and digest encoding.
* Defaults to sha256.
*
* @function
* @param algorithm {string} the hash algorithm, default is 'sha256'
* @param data {Buffer|string|TypedArray|DataView} the data to hash
* @param encoding {string=} optional, the encoding of the input
* @param output {'base64'|'base64url'|'binary'|'hex'|undefined} optional, the desired output type
* @return {Buffer|string} if {output} is undefined, a {Buffer} is returned, otherwise a {String}
*/
const createHash = function({ algorithm = 'sha256', data, output, encoding }) {
return crypto
.createHash(algorithm)
.update(data, encoding)
.digest(output);
};

module.exports = { createHash };
2 changes: 1 addition & 1 deletion test/unit/utils/crypto-util_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ require('chai').should();
describe(cryptoUtil.createHash.name, function () {
it('creates a hash by given algorithm', function () {
const data = 'client-credentials-grant';
const hash = cryptoUtil.createHash({ data, encoding: 'hex' });
const hash = cryptoUtil.createHash({ data, output: 'hex' });
hash.should.equal('072726830f0aadd2d91f86f53e3a7ef40018c2626438152dd576e272bf2b8e60');
});
it('should throw if data is missing', function () {
Expand Down