Search code examples
javaencryptionrsapki

Encrypt the encrypted message by using RSA in java


I have encrypted a String using AES. I have given a key for AES to do so. Now , i am trying to encrypt that given key with RSA(Till here everything went well), Now i need to encrypt this encrypted key with RSA once again. I am getting an error "Data must not be longer than 117 bytes".

public String encrypt(String DATA,String key_string) throws Exception {
    String separator = "//msit//";
    byte[] data = key_string.getBytes();
    MessageDigest sha = MessageDigest.getInstance("SHA-1");
    data = sha.digest(data);
    data = Arrays.copyOf(data, 16); // use only first 128 bit
    SecretKey key = new SecretKeySpec(data, "AES");
    String final_matter = DATA + separator;
    System.out.println(final_matter);
    ecipher = Cipher.getInstance("AES");
    ecipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] utf8 = final_matter.getBytes("UTF8");
    byte[] enc = ecipher.doFinal(utf8);
    return new sun.misc.BASE64Encoder().encode(enc);
    }

PUBLIC KEY INFRA STRUCTURE


Solution

  • The largest amount of data an RSA key can encrypt is equal to its modulus length. So a 1024-bit RSA key can only encrypt 128 bytes. You're probably using PKCS #1 padding, which further reduces the possible size to 117 bytes.

    Your AES key should be much smaller than the maximum. The largest possible AES key size is 256 bits, which is 32 bytes.

    Please inspect your code and ensure you are only attempting to encrypt the key data and nothing else.


    Based on your comment above, it seems you are encrypting too much data. Try the following:

    • Sign the AES key with the sender's private key, but keep the result separate.

    • Encrypt the AES key with the recipient's public key.

    • Send both parts to the recipient.

    The result of signing with a private key is a piece of data equal in size to the modulus of the key. So you cannot then encrypt that with a public key of the same length. Your scheme is broken and should be altered to work as I suggest above.

    I would strongly suggest you look for an existing PKI system to use in place of anything home-grown. Maybe EJBCA?