How to Encrypt and Decrypt using RSA keys with Java

In this article we are going to use public and private RSA keys for encryption and decryption.

How to encrypt and decrypt RSA encryption algorithm with Java

The first thing you have to do is to read the keys.

  1. Read public key and use it to encryption.
  2. Read private key and use it to decryption.

The process to encrypt or decrypt

For encrypting and decrypting you need:

  • Load de key using KeyFactory
  • Create a Cipher instance with de algorithm (in this example RSA)
  • Define the mode and set the key.
  • Call to cipher.doFinal to encrypt or decrypt.

Load public key and encrypt with RSA

To load a public RSA key you have to use KeyFactory class and know how the file had encoded. The typically encode is X509.

private PublicKey loadPublicKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {

    // reading from resource folder
    byte[] publicKeyBytes = getClass().getResourceAsStream("/key.pub").readAllBytes();

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

Now, with this public key you can encrypt. In this case, you are going to encrypt a text.

public String encode(String toEncode) throws Exception {

    PublicKey publicKey = loadPublicKey();

    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);

    byte[] bytes = cipher.doFinal(toEncode.getBytes(StandardCharsets.UTF_8));
    return new String(Base64.getEncoder().encode(bytes));
    }

Load private key and decrypt with RSA

To load a private RSA key you have to use KeyFactory class and know how the file had encoded. The typically encode for decrypt is PKCS8.

private PrivateKey loadPrivateKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {

    // reading from resource folder
    byte[] privateKeyBytes = getClass().getResourceAsStream("/key.priv").readAllBytes();

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

With this private key you can decrypt a text that was encrypted with the private pair.

public String decode(String toDecode) throws Exception {

    PrivateKey privateKey = loadPrivateKey();

    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, privateKey);

    byte[] bytes = cipher.doFinal(Base64.getDecoder().decode(toDecode));
    return new String(bytes);

    }

Running the example

Encryp-Decrypt

Conclusion

In this post, you learned how to use RSA keys to encrypt and decrypt.

If you want to learn how to create RSA keys with standard Java libraries 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