sunil zacharias
sunil zacharias

Reputation: 91

how to solve javax.crypto.IllegalBlockSizeException: Data must not be longer than 256 bytes

enter image description here I have An AES key of 16 byte length.I wanted to encrypt the 16 byte key 3 times. At first iteration the key size is changed to 16 to 256 bytes.The the next iteration the key size is changed to 256 to 689 bytes.next iteration raises an exception shown in the sreenshot. This is because of my RSA algorithm donot support keysize longer than 256 bytes .RSA Encryption source code shown below

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;
import java.sql.SQLException;

import javax.crypto.Cipher;

    public class RSAKeyPack implements Serializable {

      private static final long serialVersionUID = 2L;
      PublicKey publicKey;
      PrivateKey privateKey;
        //KeyPairGenerator keyPairGenerator;
        transient KeyPairGenerator keyPairGenerator;

        private  void getGenerator() throws NoSuchAlgorithmException {
           if (keyPairGenerator == null) {
               keyPairGenerator = KeyPairGenerator.getInstance("RSA");
               keyPairGenerator.initialize(1024); //1024 used for normal securities
               KeyPair keyPair = keyPairGenerator.generateKeyPair();  
               publicKey = keyPair.getPublic();  
               privateKey = keyPair.getPrivate();
           }

        }
        public RSAKeyPack()
        {

            try {
                getGenerator();
            } catch (NoSuchAlgorithmException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            /*try 
            {

                keyPairGenerator = KeyPairGenerator.getInstance("RSA");
                keyPairGenerator.initialize(2048); //1024 used for normal securities
                KeyPair keyPair = keyPairGenerator.generateKeyPair();  
                 publicKey = keyPair.getPublic();  
                privateKey = keyPair.getPrivate();          
            } 
            catch (NoSuchAlgorithmException e) 
            {
                e.printStackTrace();
            }*/
        }

        public PublicKey getPublicKey() {
            return publicKey;
        }

        public void setPublicKey(PublicKey publicKey) {
            this.publicKey = publicKey;
        }

        public PrivateKey getPrivateKey() {
            return privateKey;
        }

        public void setPrivateKey(PrivateKey privateKey) {
            this.privateKey = privateKey;
        }



        public   BigInteger  getParamModulus(PublicKey publickey) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException
        {

                 KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
                 RSAPublicKeySpec rsaPubKeySpec = keyFactory.getKeySpec(publicKey, RSAPublicKeySpec.class);  
                 //RSAPrivateKeySpec rsaPrivKeySpec = keyFactory.getKeySpec(privateKey, RSAPrivateKeySpec.class);  
                 System.out.println("PubKey Modulus : " + rsaPubKeySpec.getModulus());


            return rsaPubKeySpec.getModulus();
           }  

        public   BigInteger  getParamExponent(PublicKey publickey) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException
        {

                 KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
                 RSAPublicKeySpec rsaPubKeySpec = keyFactory.getKeySpec(publicKey, RSAPublicKeySpec.class);  
                 //RSAPrivateKeySpec rsaPrivKeySpec = keyFactory.getKeySpec(privateKey, RSAPrivateKeySpec.class);  
                 System.out.println("PubKey Modulus : " + rsaPubKeySpec.getPublicExponent());


            return rsaPubKeySpec.getPublicExponent();
           }  


         public static PublicKey readPublicKey(BigInteger modulus,BigInteger exponent) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException{  


                  //Get Public Key  
                  RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(modulus, exponent);  
                  KeyFactory fact = KeyFactory.getInstance("RSA");  
                  PublicKey publicKey = fact.generatePublic(rsaPublicKeySpec);  
                  return publicKey;  


         }   


         public  byte[] encryptData(byte[] data,PublicKey pubKey) throws IOException {  


                 byte[] encryptedData = null;  
                 try {  

                        Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");  
                        cipher.init(Cipher.ENCRYPT_MODE, pubKey);

                        System.out.println("data key length after encryption"+data.length);
                        encryptedData = cipher.doFinal(data);  
                        System.out.println("data key length after encryption"+encryptedData.length);

                 } catch (Exception e) {  
                     System.out.println("----------------ENCRYPTION ABANDONED!!!------------"); 
                        e.printStackTrace();  
                 }   


                 return (encryptedData);  
             }  


         public    byte[] decryptData(byte[] data,PrivateKey privateKey) throws IOException {  

              byte[] descryptedData = null;  

              try {  

               Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");

               cipher.init(Cipher.DECRYPT_MODE, privateKey);  
               descryptedData = cipher.doFinal(data);  
               System.out.println("data key length after decryption     "+data.length);

              } catch (Exception e) {  
               e.printStackTrace();  
              }   

              return descryptedData ;

             }  
    }

Upvotes: 1

Views: 14326

Answers (2)

Carl
Carl

Reputation: 250

you need split your data by the publicKey

int keyLength = publicKey.getModulus().bitLength() / 16;
String[] datas = splitString(data, keyLength - 11);
String mi = ""//the data after encrypted;
for (String s : datas) {
     mi += bcd2Str(cipher.doFinal(s.getBytes()));
}
return mi;


public static String bcd2Str(byte[] bytes) {
    char temp[] = new char[bytes.length * 2], val;

    for (int i = 0; i < bytes.length; i++) {
        val = (char) (((bytes[i] & 0xf0) >> 4) & 0x0f);
        temp[i * 2] = (char) (val > 9 ? val + 'A' - 10 : val + '0');

        val = (char) (bytes[i] & 0x0f);
        temp[i * 2 + 1] = (char) (val > 9 ? val + 'A' - 10 : val + '0');
    }
    return new String(temp);
}

Upvotes: -2

Joshua Arvin Lat
Joshua Arvin Lat

Reputation: 1039

You can use a symmetric key to encrypt and decrypt the data (> 256) to be transferred. RSA can only encrypt data up to a certain extent (e.g. 256 bytes) which depends on the RSA key length.

This means that if you want to transfer anything bigger than 256 bytes, you have to transfer a symmetric key < 256 bytes first so you can have the following:

  1. Generate a symmetric key (< 256 bytes)
  2. Encrypt symmetric key with RSA
  3. Transfer encrypted symmetric key
  4. Decrypt symmetric key with RSA
  5. Encrypt data (> 256 bytes) with symmetric key
  6. Transfer encrypted data
  7. Decrypt encrypted data with symmetric key

or (transfer encrypted symmetric key and encrypted data at the same time)

  1. Generate a symmetric key (< 256 bytes)
  2. Encrypt symmetric key with RSA
  3. Encrypt data (> 256 bytes) with symmetric key
  4. Transfer encrypted symmetric key & encrypted data
  5. Decrypt symmetric key with RSA
  6. Decrypt encrypted data with symmetric key

Upvotes: 4

Related Questions