Generate a random RSA keypair.

@param numBits
key's length in bits, should be power of 2)
@return
@throws NoSuchAlgorithmException
193520
public static KeyPair generateKeys(int numBits) throws NoSuchAlgorithmException {
        int numBitsPow2 = 1;
        while (numBitsPow2 < numBits) {
            numBitsPow2 <<= 1;
        }

        KeyPairGenerator kpg = KeyPairGenerator.getInstance(CIPHER_ALGORITHM);
        kpg.initialize(numBitsPow2, SECURE_RNG);
        KeyPair keyPair = kpg.generateKeyPair();
        return keyPair;
    }
1227540
static RSAPublicKey from(final byte[] key)
      throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException {

    final String s = new String(key);
    final byte[] encoded;
    final String decoded;
    if (s.startsWith(RSA_LABEL)) {
      decoded = s.split(" ")[1];
      encoded = Base64.decodeBase64(decoded);
    } else {
      encoded = key;
      decoded = Base64.encodeBase64String(key);
    }

    final Iterator<byte[]> fields = new ByteIterator(encoded);
    final String sigType = new String(fields.next());
    if (!sigType.equals(RSA_LABEL)) {
      throw new RuntimeException(String.format(
          "Unknown key type %s. This code currently only supports %s.", sigType, RSA_LABEL));
    }

    final RSAPublicKeySpec keySpec =
        TraditionalKeyParser.parsePemPublicKey(RSA_LABEL + " " + decoded + " ");
    final KeyFactory keyFactory = KeyFactory.getInstance("Rsa");
    return (RSAPublicKey) keyFactory.generatePublic(keySpec);
  }
783705
public static function generateEncryptionKeyPair(): EncryptionKeyPair
    {
        // Encryption keypair
        $kp = \sodium_crypto_box_keypair();
        $secretKey = \sodium_crypto_box_secretkey($kp);
        
        // Let's wipe our $kp variable
        \sodium_memzero($kp);
        return new EncryptionKeyPair(
            new EncryptionSecretKey(
                new HiddenString($secretKey)
            )
        );
    }
612548
public static String hmac(String string) throws NoSuchAlgorithmException, InvalidKeyException {
        String code = "";
        KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacMD5");
        SecretKey secretKey = keyGenerator.generateKey();
        SecretKey secretKey2 = new SecretKeySpec(secretKey.getEncoded(), "HmacMD5");
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        mac.init(secretKey2);
        return code;
    }
132264
public static String hashSHA256asStringHex(String input, int salt) throws NoSuchAlgorithmException {
		byte[] in = input.getBytes();
		ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE + in.length);
		bb.putInt(salt);
		bb.put(input.getBytes());
		byte[] output = Hash.hashSHA256(bb.array());
		StringBuilder sb = new StringBuilder("0x");
		 for (byte b : output) {
		    sb.append(hexDigit[(b >> 4) & 0x0f]);
		    sb.append(hexDigit[b & 0x0f]);
		 }
		 return sb.toString();
	}
954333
private KeyPair createKeyPair() throws NoSuchAlgorithmException {
		final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
		final SecureRandom random  = SecureRandom.getInstance("SHA1PRNG");
		random.setSeed(Long.toString(System.currentTimeMillis()).getBytes());
		keyGen.initialize(2048, random);
		final KeyPair keypair = keyGen.generateKeyPair();
		return keypair;
	}
1272922
public static BigInteger createRandomModulusForSecret(BigInteger secret,
                                                          Random random)
    {
        final BigInteger ret;
        final int originalBitLength = secret.bitLength();

        final int ratioBigger = 5;  // 5 = 20% bigger
        final int numberOfBitsBigger = originalBitLength / ratioBigger;

        final int numbits = originalBitLength + numberOfBitsBigger;
        //System.out.println("Secret.bits=" + originalBitLength + " modulus.bits=" + numbits);

        // This could take a really long time, especially for 4000+ bits....
        ret = BigInteger.probablePrime(numbits, random);

        return ret;
    }
892256
public SecretKey generateSecretKey() throws NoSuchAlgorithmException {
        final KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        final SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        keyGen.init(256, random);
        return this.secretKey = keyGen.generateKey();
    }
296865
def generate_seeds(num, root_seed, secret):
        
        # Generate a starting seed from the root
        if num < 0:
            raise HeartbeatError('%s is not greater than 0' % num)

        if secret is None:
            raise HeartbeatError('secret can not be of type NoneType')

        seeds = []
        try:
            tmp_seed = hashlib.sha256(root_seed).digest()
        except TypeError:
            tmp_seed = hashlib.sha256(str(root_seed).encode()).digest()

        # Deterministically generate the rest of the seeds
        for x in range(num):
            seeds.append(tmp_seed)
            h = hashlib.sha256(tmp_seed)
            h.update(secret)
            tmp_seed = h.digest()

        return seeds
245569
def make_rsa_keypair(bits):
    
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=bits,
        backend=default_backend(),
    )
    private_pem = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption(),
    )
    public_pem = private_key.public_key().public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo,
    )
    return private_pem, public_pem
1133544
private SSLSocketFactory setUpSSLContext() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext ctx = SSLContext.getInstance("SSL");
        ctx.init(null, new TrustManager[] { createPromptingTrustManager() }, null);
        return ctx.getSocketFactory();
    }
1143540
public static RSAPrivateKey buildPrivateKey(final String base64KeyData)
            throws NoSuchAlgorithmException, InvalidKeySpecException {
        byte[] keyData = Base64.getDecoder().decode(base64KeyData);
        return buildPrivateKey(keyData);
    }
1010726
public static String generateRandomKey (Random rand, int length)
    {
        int numKeyChars = KEY_CHARS.length();
        StringBuilder buf = new StringBuilder();
        for (int ii = 0; ii < length; ii++) {
            buf.append(KEY_CHARS.charAt(rand.nextInt(numKeyChars)));
        }
        return buf.toString();
    }
55249
private static byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bytes) throws NoSuchAlgorithmException, InvalidKeySpecException {

    final PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8);
    final SecretKeyFactory skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);
    return skf.generateSecret(spec).getEncoded();
  }
14988
public static byte[] generateSalt() throws NoSuchAlgorithmException {
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        byte[] salt = new byte[8];
        random.nextBytes(salt);
        return salt;
    }
1350198
public static BloomFilter create(long expectedNumItems, long numBits) {
    if (expectedNumItems <= 0) {
      throw new IllegalArgumentException("Expected insertions must be positive");
    }

    if (numBits <= 0) {
      throw new IllegalArgumentException("Number of bits must be positive");
    }

    return new BloomFilterImpl(optimalNumOfHashFunctions(expectedNumItems, numBits), numBits);
  }
1298776
public static function generateSignatureKeyPair(): SignatureKeyPair
    {
        // Encryption keypair
        $kp = \sodium_crypto_sign_keypair();
        $secretKey = \sodium_crypto_sign_secretkey($kp);
        
        // Let's wipe our $kp variable
        \sodium_memzero($kp);
        return new SignatureKeyPair(
            new SignatureSecretKey(
                new HiddenString($secretKey)
            )
        );
    }