Java Language Encrypt and Decrypt Data with Public / Private Keys


Example

To encrypt data with a public key:

final Cipher rsa = Cipher.getInstance("RSA");

rsa.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
rsa.update(message.getBytes());
final byte[] result = rsa.doFinal();

System.out.println("Message: " + message);
System.out.println("Encrypted: " + DatatypeConverter.printHexBinary(result));

Produces output similar to:

Message: Hello
Encrypted: 5641FBB9558ECFA9ED...

Note that when creating the Cipher object, you have to specify a transformation that is compatible with the type of key being used. (See JCA Standard Algorithm Names for a list of supported transformations.). For RSA encryption data message.getBytes() length must be smaller than the key size. See this SO Answer for detail.

To decrypt the data:

final Cipher rsa = Cipher.getInstance("RSA");

rsa.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
rsa.update(cipherText);
final String result = new String(rsa.doFinal());

System.out.println("Decrypted: " + result);

Produces the following output:

Decrypted: Hello