Arjun C
Arjun C

Reputation: 357

IllegalBlockSize Exception when using asymmetric encryption (Public Private Key Enc)

I have set up public and private key encryption in Java, and distributed the public keys of the two users (communication is between two users). I now want the users to exchange a symmetric key. What I am supposed to do:

  1. User A generates a key.
  2. User A encrypts the key with his private key and then encrypts it with B's public key.
  3. User A sends the encrypted key.
  4. User B receives the encrypted key.
  5. User B decrypts the key with his private key and then A's public key.

My code for user A to generate the key:

1. KeyGenerator keyGenerator = KeyGenerator.getInstance(ENCMETHOD);
2. SecureRandom secureRandom = new SecureRandom();
3. int keyBitSize = 128;
4. keyGenerator.init(keyBitSize, secureRandom);
5. secretKey = keyGenerator.generateKey();
6. encodedKey = Base64.getEncoder().encodeToString(secretKey.getEncoded());

// encrypt with public key of B and then my private key
7. String encryptedMessage = encodedKey;
8. encryptedMessage = ac.encryptText
               (
                        ac.encryptText(encryptedMessage, otherUserPublickey),
                        privateKey
                );

Line 8 throws the following error:

javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes
    at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:344)
    at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389)
    at javax.crypto.Cipher.doFinal(Cipher.java:2165)
    at driver.AsymmetricCryptography.encryptText(AsymmetricCryptography.java:73) // please refer to the code section below for this method
    at driver.ClientOne.main(ClientOne.java:158) // this is line 8 in the above code

The method AsymmetricCryptography.encryptText(String message, PrivateKey key):

public String encryptText(String msg, PrivateKey key)
        throws
        UnsupportedEncodingException, IllegalBlockSizeException,
        BadPaddingException, InvalidKeyException {
        this.cipher.init(Cipher.ENCRYPT_MODE, key);
        return Base64.encodeBase64String(cipher.doFinal(msg.getBytes("UTF-8")));
}

// this.cipher = Cipher.getInstance("RSA");

Any help is much appreciated. Thanks.

Upvotes: 1

Views: 153

Answers (1)

David Soroko
David Soroko

Reputation: 9096

Looks like you are exceeding the amount of data you can encrypt with RSA (see here https://security.stackexchange.com/questions/44702/whats-the-limit-on-the-size-of-the-data-that-public-key-cryptos-can-handle) which essentially is the modulus size, possibly due to Base 64 encoding.

Upvotes: 1

Related Questions