Java Language Security & Cryptography Encrypt and Decrypt Data with Public / Private Keys

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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


Got any Java Language Question?