Reputation: 91
An Exception caught at the line
encryptedData = cipher.doFinal(data);
javax.crypto.IllegalBlockSizeException: Data must not be longer than 501 bytes
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:344)
The key size is given by: keyPairGenerator.initialize(4096);
How to solve this problem without increasing the size of key?
Upvotes: 1
Views: 5386
Reputation: 6339
With asymmetric encryption there is no way to encrypt data longer than key minus padding. Since it's 11 bytes for you I can conclude you use PKCS#1 padding. What you can do is try to compress data, but depending on data length and nature it easily can fail. Another option is to combine symmetric block ciphers (which has no limitation for the size of data) and asymmetric encryption:
Generate random AES key
byte[] keyData = new byte[32];
SecureRandom random = new SecureRandom();
random.nextBytes(keyData);
Encrypt data with AES.
// zero filled input vector
byte[] ivData = new byte[32];
IvParameterSpec iv = new IvParameterSpec(ivData);
SecretKeySpec keySpec = new SecretKeySpec(keyData, "AES");
Cipher aes = Cipher.getInstance("AES/CBC/PKCS5Padding");
aes.init(Cipher.ENCRYPT_MODE, keySpec, iv);
byte[] cipherText = aes.doFinal(data);
Encrypt AES key (for AES-256 it's 32 bytes) with RSA private key.
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.WRAP_MODE, rsaKeyPair.getPublic());
byte[] wrappedKey = cipher.doFinal(keyData);
Combine wrappedKey with cipherText. Can be done with just appending one to another, but also some binary format can be used.
Upvotes: 2