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

 public byte[] sign_and_encrypt( SecretKey key ) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        cipher.init(Cipher.WRAP_MODE, priv_key);
        byte [] signed = cipher.wrap(key);

        cipher.init(Cipher.ENCRYPT_MODE, their_pub_key);
        System.out.println("Signed length: " + signed.length);

        return cipher.doFinal(signed);
 }

I'm having an issue signing and encrypting a session key in java. byte[] signed is 256 bytes in length, but the doFinal at the bottom can only take blocks of size 245 or less.

Is there a way to set the amount of padding added? Or another way to get this working without encrypting two slices of signed?

The exception I'm getting is

javax.crypto.IllegalBlockSizeException: Data must not be longer than 245 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 Crypto.JEncrypRSA.sign_and_encrypt(JEncrypRSA.java:76)
    at Chat.Client.get_session_key(Client.java:115)
    at Chat.Client.main(Client.java:131)
ggb667
  • 1,881
  • 2
  • 20
  • 44
  • https://stackoverflow.com/questions/10007147/getting-a-illegalblocksizeexception-data-must-not-be-longer-than-256-bytes-when does this help? – shihabudheenk Feb 26 '20 at 18:03
  • Use an RSA key with 3072 or 4096 bits. Then your key will fit in. – Robert Feb 26 '20 at 18:55
  • If anyone is looking the solution is to have different size keys for the server and client. Ie. If you are signing the session key with the client private key make the server rsa key pair larger. With generator.init(X);. – Raymond123 Feb 28 '20 at 18:50

0 Answers0