Reputation: 357
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:
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
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