I'm currently attempting to implement an encryption and decryption function for a basic Java program, using the following methods:
private static String encryptString(PublicKey publicKey, String message) throws Exception {
Cipher encrypt = Cipher.getInstance("RSA/ECB/PKCS1Padding");
encrypt.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encrypted = encrypt.doFinal(message.getBytes());
return Base64.getEncoder().encodeToString(encrypted);
}
private static String decryptString(PrivateKey privateKey, String message) throws Exception {
Cipher decrypt = Cipher.getInstance("RSA/ECB/PKCS1Padding");
decrypt.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decrypted = decrypt.doFinal(message.getBytes());
return Base64.getEncoder().encodeToString(decrypted);
}
Encoding the message using the public key appears to work correctly. However, when attempting to decrypt it using the private key, javax.crypto throws an IllegalBlockSizeException saying data must not be longer than 128 bytes.