How to generate RSA keys with Java

In Java, we can use native libraries to create RSA public and private keys. In this article we are going to create both keys, save keys, and load.

How to create public and private RSA Keys with Java

The algorithm RSA consists of three steps key generation, encryption and decryption

  1. Use KeyPairGenerator to generate a pair of keys.
  2. Get the keys and save
  3. Load keys and use to encrypt and decrypt

Create Key Pair. Private and Public

Returns a KeyPairGenerator object that generates public/private key pairs for the specified algorithm RSA. Initializes the key pair generator for a certain keysize. In this case the generated key will have a size of 2048 bits.

KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);

Once you have initialized, you can create a key pair.

KeyPair kp = kpg.generateKeyPair();
PrivateKey aPrivate = kp.getPrivate();
PublicKey aPublic = kp.getPublic();

Save Private and Public

Now, you save the keys

try (FileOutputStream outPrivate = new FileOutputStream("key.priv")) {
    outPrivate.write(aPrivate.getEncoded());
}

try (FileOutputStream outPublic = new FileOutputStream("key.pub")) {
    outPublic.write(aPublic.getEncoded());
}

Information about the keys. In the output of the console you can see that the keys are created in these codifications.

  • PKCS#8
  • X.509
System.out.println("Private key: " + aPrivate.getFormat());

System.out.println("Public key: " + aPublic.getFormat());

// output..
//        Private key: PKCS#8
//        Public key: X.509

Load Private and Public keys

To read the key files, you need the bytes of the file. From there you must use PKCS8EncodedKeySpec to read the private key and X509EncodedKeySpec for the public key. Note that PKCS8EncodedKeySpec and X509EncodedKeySpec corresponds to the encoding you obtained previously.

Load Private Key in PrivateKey using KeyFactory

File privateKeyFile = new File("key.priv");
byte[] privateKeyBytes = Files.readAllBytes(privateKeyFile.toPath());

KeyFactory privateKeyFactory = KeyFactory.getInstance("RSA");
EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
PrivateKey privateKey = privateKeyFactory.generatePrivate(privateKeySpec);

Load Public Key in PublicKey using KeyFactory

File publicKeyFile = new File("key.pub");
byte[] publicKeyBytes = Files.readAllBytes(publicKeyFile.toPath());

KeyFactory publicKeyFactory = KeyFactory.getInstance("RSA");
EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
PublicKey publicKey = publicKeyFactory.generatePublic(publicKeySpec);

Running this code

Both files are created at the root of the project. Then, you can move them where you need to use them.

Key-pair-files

Conclusion

In this post, you learned how to create RSA keys using Java standard libraries.

If you want to learn how to encrypt and decrypt using those keys visit this article.

You can see this code in GitHub

If you wish to send me any corrections or suggestions, please contact me.
Thanks for your feedback :)

See also