Encrypt and Decrypt Data with Public Private Keys

suggest change

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Security and Cryptograhy:
* Encrypt and Decrypt Data with Public Private Keys

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
136 Security and Cryptograhy
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap