RSA Encryption in Java
RSA Encryption in Java
As a one-off process, we need to generate an RSA key pair that from then on,
we'll use for all conversations between our clients and server.
Notice that we specify a key length of 2048 bits. Common values are 1024 or
2048. Choosing an RSA key length is a tradeoff between security and
performance.
In practice, we need to store the public and private keys somewhere. Typically,
the private key will be placed on our server, and the public key distributed to
clients. To store the key, we simply need to pull out the modulus and the public
and private exponents, then write these numbers to some file (or put in
whatever convenient place).
saveToFile("public.key", pub.getModulus(),
pub.getPublicExponent());
saveToFile("private.key", priv.getModulus(),
priv.getPrivateExponent());
To save the moduli and exponents to file, we can just use boring old
serialisation, since the modulus and exponents are just BigInteger objects:
Now we've got a mechanism to generate a key pair and save those keys for the
future, we're ready to consider how to actually perform RSA
encryption/decryption, reading in the key files we generated.
RSA.java
Below is the syntax highlighted version of RSA.java from §7.8 Intractability.
/*************************************************************************
* Compilation: javac RSA.java
* Execution: java RSA N
*
* Generate an N-bit public and private RSA key and use to encrypt
* and decrypt a random message.
*
* % java RSA 50
* public = 65537
* private = 553699199426609
* modulus = 825641896390631
* message = 48194775244950
* encrpyted = 321340212160104
* decrypted = 48194775244950
*
* Known bugs (not addressed for simplicity)
* -----------------------------------------
* - It could be the case that the message >= modulus. To avoid, use
* a do-while loop to generate key until modulus happen to be exactly N
bits.
*
* - It's possible that gcd(phi, publicKey) != 1 in which case
* the key generation fails. This will only happen if phi is a
* multiple of 65537. To avoid, use a do-while loop to generate
* keys until the gcd is 1.
*
*************************************************************************/
import java.math.BigInteger;
import java.security.SecureRandom;