var crypto = require('crypto-browserify'); var convert = require('./convert'); TODO: Discuss behaviour with format and hashing
554475
function getSha256Hash (stringToSign, format) {
	if(!format) {
		stringToSign = naclInstance.encode_utf8(stringToSign);
	} else if(format === 'utf8') {
		stringToSign = naclInstance.encode_utf8(stringToSign);
	} else if(format === 'hex') {
		stringToSign = naclInstance.from_hex(stringToSign);
	}

	return naclInstance.crypto_hash_sha256(stringToSign);
	// return crypto.createHash('sha256').update(stringToSign, format).digest();
}
1275737
function(length) {
    var charset = "abcdef0123456789";
    var i;
    var result = "";
    var isOpera = Object.prototype.toString.call(window.opera) == '[object Opera]';
    if(window.crypto && window.crypto.getRandomValues) {
        values = new Uint32Array(length);
        window.crypto.getRandomValues(values);
        for(i=0; i<length; i++) {
            result += charset[values[i] % charset.length];
        }
        return result;
    } else if(isOpera) {//Opera's Math.random is secure, see http://lists.w3.org/Archives/Public/public-webcrypto/2013Jan/0063.html
        for(i=0; i<length; i++) {
            result += charset[Math.floor(Math.random()*charset.length)];
        }
        return result;
    }
    else throw new Error("Your browser sucks and can't generate secure random numbers");
}
671779
function md5Hash(val) {
        if (!val) { return val; }

        var str = _.isObject(val) ? JSON.stringify(val) : val;
        var md5 = crypto.createHash('md5');
        md5.update(str);
        return md5.digest('hex');
    }
1098262
function computeHash(filename, algo, callback) {
    var crypto = require('crypto');
    var fs = require('fs');

    var chksum = crypto.createHash(algo);

    var s = fs.ReadStream(filename);
    s.on('error', function (err) {
        //no file, hash will be zero
        callback(0, err);
    });
    s.on('data', function (d) {
        chksum.update(d);
    });

    s.on('end', function () {
        var d = chksum.digest('hex');
        //util.debug(d + '  ' + filename);
        callback(d);
    });
}
806474
function convert(opts) {
  let res = '';

  // eslint-disable-next-line
  for (const key in opts) {
    if (hasOwn(opts, key)) {
      if (/^expires$/i.test(key)) {
        let expires = opts[key];

        if (typeof expires !== 'object') {
          expires += typeof expires === 'number' ? 'D' : '';
          expires = computeExpires(expires);
        }
        res += `;${key}=${expires.toUTCString()}`;
      } else if (/^secure$/.test(key)) {
        if (opts[key]) {
          res += `;${key}`;
        }
      } else {
        res += `;${key}=${opts[key]}`;
      }
    }
  }

  if (!hasOwn(opts, 'path')) {
    res += ';path=/';
  }

  return res;
}
113494
function customHash(req, body) {
  const hash = crypto.createHash('md5');

  updateHash(hash, req);
  hash.write(body);

  return hash.digest('hex');
}
1063602
function(arg) {
    var hash = crypto.createHash('md5')
            .update(JSON.stringify(arg))
            .digest('hex');
    return path.join(this.dir, hash);
  }
578937
function hash(object) {
  return crypto
    .createHash('sha256')
    .update(typeof object === 'string' ? object : JSON.stringify(object))
    .digest('base64')
}
314624
function md5(value) {
    let ins = crypto.createHash('md5');
    ins.update(value);
    return ins.digest('hex');
}
39286
function encrypt (str) {
    var cipher = crypto.createCipher(algorithm, key)
      , crypted = cipher.update(str, from, to) + cipher.final(to)
    return crypted;
  }
420179
function (password, opts) {
        /*jshint maxcomplexity:17 */

        opts = opts || {};
        var salt = opts.salt || cryptoUtils.crypto.randomBytes(32);
        var iv = opts.iv || cryptoUtils.crypto.randomBytes(16);
        var derivedKey;
        var kdf = opts.kdf || 'scrypt';
        var kdfparams = {
            dklen: opts.dklen || 32,
            salt: salt.toString('hex')
        };
        if (kdf === 'pbkdf2') {
            kdfparams.c = opts.c || 262144;
            kdfparams.prf = 'hmac-sha256';
            derivedKey = cryptoUtils.crypto.pbkdf2Sync(new Buffer(password), salt, kdfparams.c, kdfparams.dklen, 'sha256');
        } else if (kdf === 'scrypt') {
            kdfparams.n = opts.n || 4096;
            kdfparams.r = opts.r || 8;
            kdfparams.p = opts.p || 1;
            derivedKey = cryptoUtils.scrypt(new Buffer(password), salt, kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen);
        } else {
            throw new Error('Unsupported kdf');
        }
        var cipher = cryptoUtils.crypto.createCipheriv(opts.cipher || 'aes-128-ctr', derivedKey.slice(0, 16), iv);
        if (!cipher) {
            throw new Error('Unsupported cipher');
        }
        var ciphertext = Buffer.concat([cipher.update(this.privKey), cipher.final()]);
        // var mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), new Buffer(ciphertext, 'hex')]));   // KeyVersion3 deprecated
        var mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), new Buffer(ciphertext, 'hex'), iv, new Buffer(opts.cipher || 'aes-128-ctr')]));
        return {
            version: KeyCurrentVersion,
            id: cryptoUtils.uuid.v4({
                random: opts.uuid || cryptoUtils.crypto.randomBytes(16)
            }),
            address: this.getAddressString(),
            crypto: {
                ciphertext: ciphertext.toString('hex'),
                cipherparams: {
                    iv: iv.toString('hex')
                },
                cipher: opts.cipher || 'aes-128-ctr',
                kdf: kdf,
                kdfparams: kdfparams,
                mac: mac.toString('hex'),
                machash: "sha3256"
            }
        };
    }
1266700
function convertCookie (value, converter) {
  if (value.indexOf('"') === 0) {
    // this is a quoted cookied according to RFC2068
    // remove enclosing quotes and internal quotes and backslashes
    value = value.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
  }

  let parsedValue;
  try {
    parsedValue = decodeURIComponent(value.replace(/\+/g, ' '));
  } catch (e) {
    // no need to fail if we can't decode
    log.warn(e);
  }

  return converter ? converter(parsedValue) : parsedValue;
}
1047633
function getFormToken() {
		/*jshint validthis:true */
		if (this._csrfFormToken)
			return this._csrfFormToken;
		checkSecure(this.req);

		var cookieToken = getCookieToken(this) || createCookie(this);
		var salt = base64Random(saltSize);

		var hasher = crypto.createHmac(options.algorithm, formKey);
		hasher.update(cookieToken);
		hasher.update("|");
		hasher.update(salt);

		this._csrfFormToken = salt + "|" + hasher.digest('base64');
		return this._csrfFormToken;
	}
290208
function hashFile(filename, callback) {

    var calledBack = false,
        md5sum = crypto.createHash('md5'),
        stream = fs.ReadStream(filename);

    stream.on('data', function (data) {
      md5sum.update(data);
    });

    stream.on('end', function () {
      var hash = md5sum.digest('hex');
      callback(null, hash);
    });

    stream.on('error', function(err) {
      handleResponse(err);
    });

    function handleResponse(err, hash) {
      if (calledBack) {
        return;
      }

      calledBack = true;
      callback(err, hash);
    }
  }
803613
function userPlugin (schema, options) {
  var crypto = require('crypto')

  /**
   * Authenticate by checking the hashed password and provided password
   *
   * @param {String} plainText
   * @return {Boolean}
   * @api private
   */

  schema.methods.authenticate = function(plainText) {
    return this.encryptPassword(plainText) === this.hashed_password
  }

  /**
   * Create password salt
   *
   * @return {String}
   * @api private
   */

  schema.methods.makeSalt = function() {
    return Math.round((new Date().valueOf() * Math.random())) + ''
  }

  /**
   * Encrypt password
   *
   * @param {String} password
   * @return {String}
   * @api private
   */

  schema.methods.encryptPassword = function (password) {
    if (!password) return ''
    return crypto.createHmac('sha1', this.salt).update(password).digest('hex')
  }

  /**
   * Reset auth token
   *
   * @param {String} token
   * @param {Function} cb
   * @api private
   */

  schema.methods.resetToken = function (token, cb) {
    var self = this
    crypto.randomBytes(48, function(ex, buf) {
      self[token] = buf.toString('hex')
      if (cb) cb()
    })
  }

  /**
   * Statics
   */

  /**
   * Load
   *
   * @param {Object} options
   * @param {Function} cb
   * @api private
   */

  schema.statics.load = function (options, cb) {
    var criteria = options.criteria || {}
    var populate = options.populate || []
    var select = options.select || ''

    this.findOne(criteria)
      .select(select)
      .populate(populate)
      .exec(cb)
  }

  /**
   * List
   *
   * The use of having `list` method is, you can create your own statics
   *
   * Example:
   *
   *      UserSchema.static({
   *        deleted: function (cb) {
   *          this.list({
   *            criteria: { deleted: true },
   *            sort: { name: 'desc' }
   *            limit: 20,
   *            populate: [{
   *              path: 'company', select: 'name', match: { deleted: false }
   *            }],
   *            select: 'name email'
   *          }, cb)
   *        }
   *      })
   *
   * @param {Object} options
   * @param {Function} cb
   * @api private
   */

  schema.statics.list = function (options, cb) {
    var criteria = options.criteria || {}
    var sort = options.sort || { createdAt: -1 }
    var limit = options.limit === 0 ? 0 : (options.limit || 10)
    var page = options.page || 0
    var populate = options.populate || []
    var select = options.select || ''

    this.find(criteria)
      .select(options.select)
      .populate(options.populate)
      .sort(sort)
      .limit(limit)
      .skip(limit * page)
      .exec(cb)
  }

  /**
   * Virtuals
   */

  /**
   * Password virtual
   */

  schema.virtual('password')
  .set(function(password) {
    this._password = password
    this.salt = this.makeSalt()
    this.hashed_password = this.encryptPassword(password)
  })
  .get(function() {
    return this._password
  })

  /**
   * Skip validation virtual.
   *
   * If skipValidation attribute is set to true, validations won't be performed
   */

  schema.virtual('skipValidation')
  .set(function(val) {
    this._skipValidation = val
  })
  .get(function() {
    return this._skipValidation
  })

  /**
   * Validations
   */

  schema.path('name').validate(function (name) {
    if (this.skipValidation) return true
    return name.trim().length
  }, 'Please provide a valid name')

  schema.path('email').validate(function (email) {
    if (this.skipValidation) return true
    return email.trim().length
  }, 'Please provide a valid email')

  schema.path('hashed_password').validate(function (hashed_password) {
    if (this.skipValidation) return true
    return hashed_password.length
  }, 'Please provide a password')
}
1172385
function parse_RC4CryptoHeader(blob, length/*:number*/) {
	var o = {};
	var vers = o.EncryptionVersionInfo = parse_CRYPTOVersion(blob, 4); length -= 4;
	if(vers.Minor != 2) throw new Error('unrecognized minor version code: ' + vers.Minor);
	if(vers.Major > 4 || vers.Major < 2) throw new Error('unrecognized major version code: ' + vers.Major);
	o.Flags = blob.read_shift(4); length -= 4;
	var sz = blob.read_shift(4); length -= 4;
	o.EncryptionHeader = parse_EncryptionHeader(blob, sz); length -= sz;
	o.EncryptionVerifier = parse_EncryptionVerifier(blob, length);
	return o;
}
1122088
function deumdify(browserify) {
  //
  // Bail out if there is no UMD wrapper.
  //
  if (!browserify._options.standalone) return;

  browserify.pipeline.push(createStream());
  browserify.on('reset', function reset() {
    browserify.pipeline.push(createStream());
  });
}