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)
| 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 | } |