File size: 1,923 Bytes
1abfaca | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | import { createHash } from 'crypto';
const AbstractPasswordEncoder = Jymfony.Component.Security.Encoder.AbstractPasswordEncoder;
/**
* PlaintextPasswordEncoder does not do any encoding.
*
* @memberOf Jymfony.Component.Security.Encoder
*/
export default class MessageDigestPasswordEncoder extends AbstractPasswordEncoder {
/**
* Constructor.
*
* @param {string} [algorithm = 'sha512'] The digest algorithm to use
* @param {boolean} [encodeHashAsBase64 = true] Whether to base64 encode the password hash
* @param {int} [iterations = 5000] The number of iterations to use to stretch the password hash
*/
__construct(algorithm = 'sha512', encodeHashAsBase64 = true, iterations = 5000) {
/**
* @type {string}
*
* @private
*/
this._algorithm = algorithm;
/**
* @type {boolean}
*
* @private
*/
this._encodeAsBase64 = encodeHashAsBase64;
/**
* @type {int}
*
* @private
*/
this._iterations = iterations;
}
/**
* @inheritdoc
*/
async encodePassword(raw, salt) {
const salted = this._mergePasswordAndSalt(raw, salt);
const hash = createHash(this._algorithm);
hash.update(salted);
let digest = hash.digest();
// "stretch" hash
for (let i = 1; i < this._iterations; ++i) {
const hash = createHash(this._algorithm);
hash.update(digest.toString('binary') + salted);
digest = hash.digest();
}
return this._encodeAsBase64 ? digest.toString('base64') : digest.toString('binary');
}
/**
* @inheritdoc
*/
async isPasswordValid(encoded, raw, salt) {
return this._comparePasswords(encoded, await this.encodePassword(raw, salt));
}
}
module.exports = MessageDigestPasswordEncoder;
|