MCPcopy Create free account
hub / github.com/TheAlgorithms/Java / generateKeys

Method generateKeys

src/main/java/com/thealgorithms/ciphers/RSA.java:104–118  ·  view source on GitHub ↗

Generates a new RSA key pair (public and private keys) with the specified bit length. Steps: 1. Generate two large prime numbers p and q. 2. Compute the modulus n = p q. 3. Compute Euler's totient function: φ(n) = (p-1) (q-1). 4. Choose a public key e (starting from 3) that is coprime with φ(n). 5.

(int bits)

Source from the content-addressed store, hash-verified

102 * @param bits The bit length of the keys to be generated.
103 */
104 public final synchronized void generateKeys(int bits) {
105 SecureRandom random = new SecureRandom();
106 BigInteger p = new BigInteger(bits / 2, 100, random);
107 BigInteger q = new BigInteger(bits / 2, 100, random);
108 modulus = p.multiply(q);
109
110 BigInteger phi = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
111
112 publicKey = BigInteger.valueOf(3L);
113 while (phi.gcd(publicKey).intValue() > 1) {
114 publicKey = publicKey.add(BigInteger.TWO);
115 }
116
117 privateKey = publicKey.modInverse(phi);
118 }
119}

Callers 1

RSAMethod · 0.95

Calls 5

modInverseMethod · 0.80
multiplyMethod · 0.45
subtractMethod · 0.45
gcdMethod · 0.45
addMethod · 0.45

Tested by

no test coverage detected