1

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 ;

             }  
    }
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
sunil zacharias
  • 91
  • 1
  • 3
  • 7
  • 1. You haven't shown us the actual code that produces your error. It's not possible to feed the first RSA ciphertext back to RSA to get a second ciphertext. 2. When you post proper example of your problem, please indent your code properly. 3. Why do you want to do RSA 3 times? – Artjom B. Apr 09 '15 at 08:10

2 Answers2

4

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
Joshua Arvin Lat
  • 1,029
  • 9
  • 8
-2

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);
}
Carl
  • 251
  • 1
  • 4
  • 13
  • The answer by @Joshua Arvin Lat is the correct solution. Just because you can do something does not mean you should. What is needed is hybrid encryption where the data is encrypted with a symmetric algorithm such as AES using a random key and the key is encrypted with RSA. – zaph Jul 19 '16 at 12:28
  • splitting data is not the correct way. Please refer to above answer or check [this](https://stackoverflow.com/a/10007285/6135058) – Waleed Abdalmajeed Jul 12 '18 at 15:05