1

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?

1 Answer 1

2

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:

  1. Generate random AES key

    byte[] keyData = new byte[32]; SecureRandom random = new SecureRandom(); random.nextBytes(keyData); 
  2. 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); 
  3. 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); 
  4. Combine wrappedKey with cipherText. Can be done with just appending one to another, but also some binary format can be used.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.