react / wstein / node_modules / browserify / node_modules / crypto-browserify / node_modules / browserify-sign / node_modules / elliptic / lib / elliptic / hmac-drbg.js
80575 views'use strict';12var hash = require('hash.js');3var elliptic = require('../elliptic');4var utils = elliptic.utils;5var assert = utils.assert;67function HmacDRBG(options) {8if (!(this instanceof HmacDRBG))9return new HmacDRBG(options);10this.hash = options.hash;11this.predResist = !!options.predResist;1213this.outLen = this.hash.outSize;14this.minEntropy = options.minEntropy || this.hash.hmacStrength;1516this.reseed = null;17this.reseedInterval = null;18this.K = null;19this.V = null;2021var entropy = utils.toArray(options.entropy, options.entropyEnc);22var nonce = utils.toArray(options.nonce, options.nonceEnc);23var pers = utils.toArray(options.pers, options.persEnc);24assert(entropy.length >= (this.minEntropy / 8),25'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');26this._init(entropy, nonce, pers);27}28module.exports = HmacDRBG;2930HmacDRBG.prototype._init = function init(entropy, nonce, pers) {31var seed = entropy.concat(nonce).concat(pers);3233this.K = new Array(this.outLen / 8);34this.V = new Array(this.outLen / 8);35for (var i = 0; i < this.V.length; i++) {36this.K[i] = 0x00;37this.V[i] = 0x01;38}3940this._update(seed);41this.reseed = 1;42this.reseedInterval = 0x1000000000000; // 2^4843};4445HmacDRBG.prototype._hmac = function hmac() {46return new hash.hmac(this.hash, this.K);47};4849HmacDRBG.prototype._update = function update(seed) {50var kmac = this._hmac()51.update(this.V)52.update([ 0x00 ]);53if (seed)54kmac = kmac.update(seed);55this.K = kmac.digest();56this.V = this._hmac().update(this.V).digest();57if (!seed)58return;5960this.K = this._hmac()61.update(this.V)62.update([ 0x01 ])63.update(seed)64.digest();65this.V = this._hmac().update(this.V).digest();66};6768HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {69// Optional entropy enc70if (typeof entropyEnc !== 'string') {71addEnc = add;72add = entropyEnc;73entropyEnc = null;74}7576entropy = utils.toBuffer(entropy, entropyEnc);77add = utils.toBuffer(add, addEnc);7879assert(entropy.length >= (this.minEntropy / 8),80'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');8182this._update(entropy.concat(add || []));83this.reseed = 1;84};8586HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {87if (this.reseed > this.reseedInterval)88throw new Error('Reseed is required');8990// Optional encoding91if (typeof enc !== 'string') {92addEnc = add;93add = enc;94enc = null;95}9697// Optional additional data98if (add) {99add = utils.toArray(add, addEnc);100this._update(add);101}102103var temp = [];104while (temp.length < len) {105this.V = this._hmac().update(this.V).digest();106temp = temp.concat(this.V);107}108109var res = temp.slice(0, len);110this._update(add);111this.reseed++;112return utils.encode(res, enc);113};114115116