0

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.

luk2302
  • 55,258
  • 23
  • 97
  • 137
ed-ict
  • 1
  • Does this answer your question? [How to Encrypt String With Public Key and Decrypt with Private key ?](https://stackoverflow.com/questions/31915617/how-to-encrypt-string-with-public-key-and-decrypt-with-private-key) – pringi Oct 25 '22 at 08:45
  • @pringi Sorry, it does not appear to help unless I'm misunderstanding something. I changed the Cipher algorithm to RSA and still received the same error, and the rest of the code is not as useful since I'm using pre-existing keys. – ed-ict Oct 25 '22 at 08:50
  • 1
    There are tens of posts on SO about this, e.g. [getting a IllegalBlockSizeException: Data must not be longer than 256 bytes when using rsa](https://stackoverflow.com/questions/10007147/getting-a-illegalblocksizeexception-data-must-not-be-longer-than-256-bytes-when) – Topaco Oct 25 '22 at 09:06
  • @Topaco Thanks for the link. The issue is that the data encrypts perfectly fine - which it shouldn't if it were over 117 bytes, unless I'm misunderstanding. Hence my confusion about the IllegalBlockSizeException, as I'm encrypting and decrypting the same data. – ed-ict Oct 25 '22 at 09:20
  • 2
    You must Base64 decode the ciphertext before decrypting it: `byte[] decrypted = decrypt.doFinal(Base64.getDecoder().decode(message))`. The decrypted data must be decoded with the appropriate charset encoding: `return new String(decrypted, )`. The charset encoding should be specified explicitly when encrypting, e.g. `byte[] encrypted = encrypt.doFinal(message.getBytes(StandardCharsets.UTF_8))`. – Topaco Oct 25 '22 at 09:34

0 Answers0