Encrypt and Decrypt Data with Public Private Keys
suggest changeTo encrypt data with a public key:
final Cipher rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
final byte[] result = rsa.doFinal(message.getBytes());
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.) "RSA" selects the provider default, usually RSA/ECB/PKCS1Padding. SunJCE’s RSA implementation rejects update for that transform, so the bytes are passed to doFinal. With PKCS#1 v1.5 padding the plaintext must be at least 11 bytes shorter than the modulus. getBytes() and new String(byte[]) use the platform default charset. cipherText is the encrypted bytes. javax.xml.bind.DatatypeConverter was removed from the JDK in Java 11. keyPair and message are assumed to exist. See this SO answer for details.
To decrypt the data:
final Cipher rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
final String result = new String(rsa.doFinal(cipherText));
System.out.println("Decrypted: " + result);
Produces the following output:
Decrypted: Hello