Generate a private RSA key

@param {number} [size] Size of the key, default: `2048`
@returns {Promise<buffer>} Private RSA key
198378
async function createPrivateKey(size = 2048) {
    let pemKey;

    /* Native implementation */
    if (nativeGenKeyPair) {
        const result = await nativeGenKeyPair('rsa', {
            modulusLength: size,
            publicKeyEncoding: { type: 'spki', format: 'pem' },
            privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
        });

        pemKey = result[1];
    }
    /* Forge implementation */
    else {
        const keyPair = await forgeGenKeyPair({ bits: size });
        pemKey = forge.pki.privateKeyToPem(keyPair.privateKey);
    }

    return Buffer.from(pemKey);
}
1203790
function rsaEncrypt(messageBuffer, publicKey) {
    var logger = getLogger('security.cipher.rsaEncrypt');
    var messageLength = messageBuffer.length;
    if (!messageBuffer || messageLength > 255) {
        logger.warn('Message is undefined or exceeds 255 bytes length.');
        return;
    } else if (messageLength < 255) {
        // Add random bytes as padding
        var paddingLength = 255 - messageLength;
        messageBuffer = Buffer.concat([messageBuffer, utility.createRandomBuffer(paddingLength)]);
    }
    // Encrypt the message
    var modulus = new BigInteger(publicKey.getModulus(), 16);
    var exponent = new BigInteger(publicKey.getExponent(), 16);
    var message = new BigInteger(messageBuffer);
    var encryptedMessage = new Buffer(message.modPowInt(exponent, modulus).toByteArray());
    if (encryptedMessage.length > 256) {
        encryptedMessage = encryptedMessage.slice(encryptedMessage.length - 256);
    }
    if (logger.isDebugEnabled()) {
        logger.debug('Plain-text message(%s) = %s', messageBuffer.length, messageBuffer.toString('hex'));
        logger.debug('Encrypted message(%s) = %s', encryptedMessage.length, encryptedMessage.toString('hex'));
    }
    return encryptedMessage;
}
528900
public static PrivateKey generatePrivateKey(String algorithm, KeySpec keySpec) {
		return KeyUtil.generatePrivateKey(algorithm, keySpec);
	}
93892
function rsaPublicKeyPem(modulus_b64, exponent_b64) {
 
    var modulus = new Buffer(modulus_b64, 'base64');
    var exponent = new Buffer(exponent_b64, 'base64');
 
    var modulus_hex = modulus.toString('hex')
    var exponent_hex = exponent.toString('hex')
 
    modulus_hex = prepadSigned(modulus_hex)
    exponent_hex = prepadSigned(exponent_hex)
 
    var modlen = modulus_hex.length/2
    var explen = exponent_hex.length/2
 
    var encoded_modlen = encodeLengthHex(modlen)
    var encoded_explen = encodeLengthHex(explen)
    var encoded_pubkey = '30' + 
        encodeLengthHex(
            modlen + 
            explen + 
            encoded_modlen.length/2 + 
            encoded_explen.length/2 + 2
        ) + 
        '02' + encoded_modlen + modulus_hex +
        '02' + encoded_explen + exponent_hex;

    var der_b64 = new Buffer(encoded_pubkey, 'hex').toString('base64');

    var pem = '-----BEGIN RSA PUBLIC KEY-----\n' 
        + der_b64.match(/.{1,64}/g).join('\n') 
        + '\n-----END RSA PUBLIC KEY-----\n';
 
    return pem
}
348317
function _rsapem_privateKeyToPkcs1HexString(rsaKey) {
    var result = _rsapem_derEncodeNumber(0);
    result += _rsapem_derEncodeNumber(rsaKey.n);
    result += _rsapem_derEncodeNumber(rsaKey.e);
    result += _rsapem_derEncodeNumber(rsaKey.d);
    result += _rsapem_derEncodeNumber(rsaKey.p);
    result += _rsapem_derEncodeNumber(rsaKey.q);
    result += _rsapem_derEncodeNumber(rsaKey.dmp1);
    result += _rsapem_derEncodeNumber(rsaKey.dmq1);
    result += _rsapem_derEncodeNumber(rsaKey.coeff);

    var fullLen = _rsapem_encodeLength(result.length / 2);
    return '30' + fullLen + result;
}
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))
    })
  })
}
1179019
function aes(length) {
  const C = function(key) {
    const aes_ecb = new AES_ECB(key);

    this.encrypt = function(block) {
      return aes_ecb.encrypt(block);
    };

    this.decrypt = function(block) {
      return aes_ecb.decrypt(block);
    };
  };

  C.blockSize = C.prototype.blockSize = 16;
  C.keySize = C.prototype.keySize = length / 8;

  return C;
}
1054317
private static byte[] generateKey(int size) throws SymmetricKeyException {
        if (size <= 0)
            throw new IllegalArgumentException("Size cannot be zero or less than zero.");

        try {
            SecureRandom secureRandom = new SecureRandom();
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            keyGenerator.init(size * 8, secureRandom);
            return keyGenerator.generateKey().getEncoded();
        } catch (NoSuchAlgorithmException e) {
            throw new SymmetricKeyException(e);
        }
    }
1178013
public static PrivateKey stringToRSAPrivateKey (String str)
    {
        try {
            BigInteger mod = new BigInteger(str.substring(0, str.indexOf(SPLIT)), 16);
            BigInteger exp = new BigInteger(str.substring(str.indexOf(SPLIT) + 1), 16);
            RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(mod, exp);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            return kf.generatePrivate(keySpec);
        } catch (NumberFormatException nfe) {
            log.warning("Failed to read key from string.", "str", str, nfe);
        } catch (GeneralSecurityException gse) {
            log.warning("Failed to read key from string.", "str", str, gse);
        }
        return null;
    }
1161816
function AESKey(key, bits) {
  if (!(this instanceof AESKey))
    return new AESKey(key, bits);

  this.rounds = null;
  this.userKey = key;
  this.bits = bits;

  switch (this.bits) {
    case 128:
      this.rounds = 10;
      break;
    case 192:
      this.rounds = 12;
      break;
    case 256:
      this.rounds = 14;
      break;
    default:
      throw new Error('Bad key size.');
  }

  assert(Buffer.isBuffer(key));
  assert(key.length === this.bits / 8);

  this.decryptKey = null;
  this.encryptKey = null;
}
1233579
function diffieHellman(prime) {
  var dhObj = null;
  var wrapper = {};

  if(!!prime)
    dhObj = crypto.createDiffieHellman(prime, 'base64');
  else
    dhObj = crypto.createDiffieHellman(64);

  wrapper.prime = dhObj.getPrime('base64');
  wrapper.publicKey = dhObj.generateKeys('base64');

  wrapper.computeSecret = function(remotePublicKey) {
    return dhObj.computeSecret(remotePublicKey.toString(), 'base64', 'base64');
  };

  return wrapper;
}
929478
public static SecretKey generateKey(String algorithm, int keySize) {
        KeyGenerator secretKeyGenerator;
        try {
            secretKeyGenerator = KeyGenerator.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException(e);
        }
        secretKeyGenerator.init(keySize);
        return secretKeyGenerator.generateKey();
    }
1302880
function generateKeyPair (name, { output }) {
  const { publicKey, secretKey } = Crypto.generateKeyPair()

  const data = [
    [path.join(output, name), secretKey],
    [path.join(output, `${name}.pub`), publicKey]
  ]

  data.forEach(([path, data]) => {
    fs.writeFileSync(path, data)
    console.log(`Wrote ${path}`)
  })
}
107420
function genPrivKey(){
	var privKey;
	do {
		console.log("generating new priv key");
		privKey = crypto.randomBytes(32);
	}
	while (!ecdsa.privateKeyVerify(privKey));
	return privKey;
}
1256918
public static KeySize getKeySize(final PrivateKey privateKey)
	{
		int length = getKeyLength(privateKey);
		if (length == 1024)
		{
			return KeySize.KEYSIZE_1024;
		}
		if (length == 2048)
		{
			return KeySize.KEYSIZE_2048;
		}
		if (length == 4096)
		{
			return KeySize.KEYSIZE_4096;
		}
		if (length == 8192)
		{
			return KeySize.KEYSIZE_8192;
		}
		return null;
	}
15770
def generate_urlsafe_key(size=48)
      seed = Time.now.to_i
      size = size - seed.to_s.length
      Base64.encode64("#{ OpenSSL::Random.random_bytes(size) }#{ seed }").gsub(/\W/, '')
    end
142847
def generate_private_key(key_size=2048):
    """"""
    return cryptography.hazmat.primitives.asymmetric.rsa.generate_private_key(
        public_exponent=65537,
        key_size=key_size,
        backend=cryptography.hazmat.backends.default_backend(),
    )