Generates a random base32 secret key and optionally a qrcode

@param     {Object}    options
@return    {Object}
966628
function generateKey(options) {
  // Options
  options = _.extend({
    length: 32,
    name: '',
    symbols: false,
    google: false,
    qrCode: false,
    type: 'base32'
  }, options || {});

  // Generate the random string
  var key = randomString(options);

  if (options.type === 'ascii') {
    return key;
  } else if (options.type === 'base32') {
    // Encode the ascii string into base32 and remove any `=` signs which google
    // doesn't like
    key = base32.encode(key).toString().replace(/=/g, '');

    return key;
  } else {
    throw new Error('InvalidKeyType');
  }
}
1030200
function getRNG(){
	var randomBits, crypto;
	
	function construct(bits, arr, radix, size){
		var str = '',
			i = 0,
			len = arr.length-1;
		while( i<len || (str.length < bits) ){
			str += padLeft(parseInt(arr[i], radix).toString(2), size);
			i++;
		}
		str = str.substr(-bits);
		if( (str.match(/0/g)||[]).length === str.length){ // all zeros?
			return null;
		}else{
			return str;
		}
	}
	
	// node.js crypto.randomBytes()
	if(typeof require === 'function' && (crypto=require('crypto')) && (randomBits=crypto['randomBytes'])){
		return function(bits){
			var bytes = Math.ceil(bits/8),
				str = null;
		
			while( str === null ){
				str = construct(bits, randomBits(bytes).toString('hex'), 16, 4);
			}
			return str;
		}
	}
	
	// browsers with window.crypto.getRandomValues()
	if(global['crypto'] && typeof global['crypto']['getRandomValues'] === 'function' && typeof global['Uint32Array'] === 'function'){
		crypto = global['crypto'];
		return function(bits){
			var elems = Math.ceil(bits/32),
				str = null,
				arr = new global['Uint32Array'](elems);

			while( str === null ){
				crypto['getRandomValues'](arr);
				str = construct(bits, arr, 10, 32);
			}
			
			return str;	
		}
	}

	// A totally insecure RNG!!! (except in Safari)
	// Will produce a warning every time it is called.
	config.unsafePRNG = true;
	warn();
	
	var bitsPerNum = 32;
	var max = Math.pow(2,bitsPerNum)-1;
	return function(bits){
		var elems = Math.ceil(bits/bitsPerNum);
		var arr = [], str=null;
		while(str===null){
			for(var i=0; i<elems; i++){
				arr[i] = Math.floor(Math.random() * max + 1); 
			}
			str = construct(bits, arr, 10, bitsPerNum);
		}
		return str;
	};
}
1324196
function generateECDSA(curve) {
	var parts = [];
	var key;

	if (CRYPTO_HAVE_ECDH) {
		/*
		 * Node crypto doesn't expose key generation directly, but the
		 * ECDH instances can generate keys. It turns out this just
		 * calls into the OpenSSL generic key generator, and we can
		 * read its output happily without doing an actual DH. So we
		 * use that here.
		 */
		var osCurve = {
			'nistp256': 'prime256v1',
			'nistp384': 'secp384r1',
			'nistp521': 'secp521r1'
		}[curve];

		var dh = crypto.createECDH(osCurve);
		dh.generateKeys();

		parts.push({name: 'curve',
		    data: Buffer.from(curve)});
		parts.push({name: 'Q', data: dh.getPublicKey()});
		parts.push({name: 'd', data: dh.getPrivateKey()});

		key = new PrivateKey({
			type: 'ecdsa',
			curve: curve,
			parts: parts
		});
		return (key);
	} else {

		var ecParams = new X9ECParameters(curve);

		/* This algorithm taken from FIPS PUB 186-4 (section B.4.1) */
		var n = ecParams.getN();
		/*
		 * The crypto.randomBytes() function can only give us whole
		 * bytes, so taking a nod from X9.62, we round up.
		 */
		var cByteLen = Math.ceil((n.bitLength() + 64) / 8);
		var c = new jsbn(crypto.randomBytes(cByteLen));

		var n1 = n.subtract(jsbn.ONE);
		var priv = c.mod(n1).add(jsbn.ONE);
		var pub = ecParams.getG().multiply(priv);

		priv = Buffer.from(priv.toByteArray());
		pub = Buffer.from(ecParams.getCurve().
		    encodePointHex(pub), 'hex');

		parts.push({name: 'curve', data: Buffer.from(curve)});
		parts.push({name: 'Q', data: pub});
		parts.push({name: 'd', data: priv});

		key = new PrivateKey({
			type: 'ecdsa',
			curve: curve,
			parts: parts
		});
		return (key);
	}
}
13068
function uid (length) {
  return new Promise((resolve, reject) => {
    Crypto.randomBytes(length * 2, (err, bytes) => {
      if (err) return reject(err)
      resolve(bytes.toString('base64').replace(/\+/g, '').replace(/\//g, '').replace(/=/g, '').substring(0, length))
    })
  })
}
1064953
function generateRandomBytes (size, attempts, callback) {
  crypto.randomBytes(size, function onRandomBytes (err, buf) {
    if (!err) return callback(null, buf)
    if (!--attempts) return callback(err)
    setTimeout(generateRandomBytes.bind(null, size, attempts, callback), 10)
  })
}
181636
function (options, callback) {

        LOG.debug('preauth#createPreauth called');
        LOG.debug('Validating options');

        try {

            options = new preauthOptions.CreatePreauth().validate(options);

        } catch (err) {

            if (err.name === 'InvalidOption') {

                LOG.error('Invalid options specified: %s', err.message);

                callback(
                    commonErrors.InvalidOption(
                        undefined,
                        {
                            message: err.message
                        }
                    )
                );

            } else {

                LOG.error('System error: %s', err.message);

                callback(
                    commonErrors.SystemError(
                        undefined,
                        {
                            message: err.message
                        }
                    )
                );

            }

            return;

        }

        var timestamp = options.timestamp;

        if (!timestamp) {

            timestamp = new Date().getTime();

        }

        LOG.debug('Generating preauth key');

        var pakCreator = crypto.createHmac('sha1', options.key)
            .setEncoding('hex');

        pakCreator.write(
            util.format(
                '%s|%s|%s|%s',
                options.byValue,
                options.by,
                options.expires,
                timestamp
            )
        );
        pakCreator.end();
        var pak = pakCreator.read();

        LOG.debug('Returning preauth key %s', pak);

        callback(null, pak);

    }
454368
function RequestSigner(options) {
  assert.object(options, 'options');

  var alg = [];
  if (options.algorithm !== undefined) {
    assert.string(options.algorithm, 'options.algorithm');
    alg = validateAlgorithm(options.algorithm);
  }
  this.rs_alg = alg;

  /*
   * RequestSigners come in two varieties: ones with an rs_signFunc, and ones
   * with an rs_signer.
   *
   * rs_signFunc-based RequestSigners have to build up their entire signing
   * string within the rs_lines array and give it to rs_signFunc as a single
   * concat'd blob. rs_signer-based RequestSigners can add a line at a time to
   * their signing state by using rs_signer.update(), thus only needing to
   * buffer the hash function state and one line at a time.
   */
  if (options.sign !== undefined) {
    assert.func(options.sign, 'options.sign');
    this.rs_signFunc = options.sign;

  } else if (alg[0] === 'hmac' && options.key !== undefined) {
    assert.string(options.keyId, 'options.keyId');
    this.rs_keyId = options.keyId;

    if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key))
      throw (new TypeError('options.key for HMAC must be a string or Buffer'));

    /*
     * Make an rs_signer for HMACs, not a rs_signFunc -- HMACs digest their
     * data in chunks rather than requiring it all to be given in one go
     * at the end, so they are more similar to signers than signFuncs.
     */
    this.rs_signer = crypto.createHmac(alg[1].toUpperCase(), options.key);
    this.rs_signer.sign = function () {
      var digest = this.digest('base64');
      return ({
        hashAlgorithm: alg[1],
        toString: function () { return (digest); }
      });
    };

  } else if (options.key !== undefined) {
    var key = options.key;
    if (typeof (key) === 'string' || Buffer.isBuffer(key))
      key = sshpk.parsePrivateKey(key);

    assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]),
      'options.key must be a sshpk.PrivateKey');
    this.rs_key = key;

    assert.string(options.keyId, 'options.keyId');
    this.rs_keyId = options.keyId;

    if (!PK_ALGOS[key.type]) {
      throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' +
        'keys are not supported'));
    }

    if (alg[0] !== undefined && key.type !== alg[0]) {
      throw (new InvalidAlgorithmError('options.key must be a ' +
        alg[0].toUpperCase() + ' key, was given a ' +
        key.type.toUpperCase() + ' key instead'));
    }

    this.rs_signer = key.createSign(alg[1]);

  } else {
    throw (new TypeError('options.sign (func) or options.key is required'));
  }

  this.rs_headers = [];
  this.rs_lines = [];
}
77850
function getKey() {
      let paramString =
        width + 'x' + height + '-'
        + path
        + (is2x ? '-@2x' : '')
        + (bg ? `_${bg}` : '')
        + (crop ? '_crop' : '')
        + (mode ? `_${mode}` : '')
        + (trim ? '_trim' : '');

      return paramString + '-' + crypto.createHash('sha1').update(paramString).digest('hex');
    }
601311
function hotpOptions(options = {}) {
  return Object.assign(
    {
      algorithm: 'sha1',
      createHmacSecret: hotpSecret,
      crypto: null,
      digits: 6,
      encoding: 'ascii'
    },
    options
  );
}
1044478
function keyOptions (key, options) {
  const _key = options._key == null
    ? key
    : options._key + '.' + key
  return Object.assign({}, options, { _key: _key })
}
856366
function(data, key) {
    // Errors
    if (!data || !key) throw new Error('Missing argument !');
    // Processing
    let iv = nacl.randomBytes(16)
    let encKey = convert.ua2words(key, 32);
    let encIv = {
        iv: convert.ua2words(iv, 16)
    };
    let encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Hex.parse(data), encKey, encIv);
    // Result
    return {
        ciphertext: encrypted.ciphertext,
        iv: iv,
        key: key
    };
}
91880
public static Key generateKey(final Random random) {
        final byte[] signingKey = new byte[signingKeyBytes];
        random.nextBytes(signingKey);
        final byte[] encryptionKey = new byte[encryptionKeyBytes];
        random.nextBytes(encryptionKey);
        return new Key(signingKey, encryptionKey);
    }
666668
def generate_secret
      if defined?(SecureRandom)
        SecureRandom.urlsafe_base64(32)
      else
        Base64.encode64(
          Digest::SHA256.digest("#{Time.now}-#{Time.now.usec}-#{$$}-#{rand}")
        ).gsub('/','-').gsub('+','_').gsub('=','').strip
      end
    end
107420
function genPrivKey(){
	var privKey;
	do {
		console.log("generating new priv key");
		privKey = crypto.randomBytes(32);
	}
	while (!ecdsa.privateKeyVerify(privKey));
	return privKey;
}
776819
function keymage(scope, keychain, fn, options) {
        var args = parsed(scope, keychain, fn, options);
        fn = args[2];
        options = args[3];
        fn._keymage = options || {};
        fn._keymage.original = keychain;
        assignKey.apply(null, args);

        return function () {
            unassignKey.apply(null, args);
        };
    }
780854
function Tokens (options) {
  if (!(this instanceof Tokens)) {
    return new Tokens(options)
  }

  var opts = options || {}

  var saltLength = opts.saltLength !== undefined
    ? opts.saltLength
    : 8

  if (typeof saltLength !== 'number' || !isFinite(saltLength) || saltLength < 1) {
    throw new TypeError('option saltLength must be finite number > 1')
  }

  var secretLength = opts.secretLength !== undefined
    ? opts.secretLength
    : 18

  if (typeof secretLength !== 'number' || !isFinite(secretLength) || secretLength < 1) {
    throw new TypeError('option secretLength must be finite number > 1')
  }

  this.saltLength = saltLength
  this.secretLength = secretLength
}
554413
function random(len) {
    if (subtle) {
        return safeRandom(len);
    } else if (nodeCrypto) {
        return new Uint8Array(nodeCrypto.randomBytes(len));
    } else {
        throw new KdbxError(Consts.ErrorCodes.NotImplemented, 'Random not implemented');
    }
}