BadPaddingException: Decryption error when trying to decrypt a byte array?

2.7k Views Asked by At
public static String decrypt(byte[] text, PrivateKey key) {
    byte[] decryptedText = null;
    try {
        final Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, key);
        decryptedText = cipher.doFinal(text);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return new String(decryptedText);
}

There is my code, for some reason I get this error and I think it is something to do with using the default constructor of the Cipher class.

Why am I getting this error?

1

There are 1 best solutions below

2
On

In order to lead to reasonable results, you often don't want to encrypt an arbitrary number of bytes.

Instead: you enlarge the number of bytes to encrypt using padding.

See here on the "why to pad?"