Search code examples
javaencryptionrsabadpaddingexception

Decryption Error bad padding


I am trying to send encrypted messages between two agents .I have a string that contains information that I convert to bytes encrypt it and then to string again to send the message. Messages are received however, at the receiving agent I get the following exception

javax.crypto.BadPaddingException: Decryption error
at sun.security.rsa.RSAPadding.unpadV15(Unknown Source)
at sun.security.rsa.RSAPadding.unpad(Unknown Source)
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:354)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:380)
at javax.crypto.Cipher.doFinal(Cipher.java:2121)
at Hi$1.action(Hi.java:72)
at jade.core.behaviours.Behaviour.actionWrapper(Behaviour.java:344)
at jade.core.Agent$ActiveLifeCycle.execute(Agent.java:1532)
at jade.core.Agent.run(Agent.java:1471)
at java.lang.Thread.run(Unknown Source)

I tried the code for agents in the same container and it works fine however, if they are on different container it doesn't.

This is how I encrypt the message:

String msg1="Message from bob 1"; // message
MSGBOB = cipher.doFinal(msg1.getBytes("ISO-8859-1")); // encryption
msg.setContent(new String (MSGBOB,"ISO-8859-1")); // conversion to string

This is how I decrypt it :

mm = msg.getContent().getBytes("ISO-8859-1");// received message 
m = new String(cipher.doFinal(mm),"ISO-8859-1"); // decryption

Solution

  • use base64 encoding for the output of the encryption, don't use new String() as some byte-values will not be represented correctly as string. so when reversed to bytes again it will not be the correct ciphered value

    here is what i mean:

    String msg1="Message from bob 1"; // message
    MSGBOB = cipher.doFinal(msg1.getBytes("ISO-8859-1")); // encryption
    msg.setContent(Base64.encode(MSGBOB)); // conversion to string
    This is how I decrypt it :
    
    mm = Base64.decode(msg.getContent());// received message 
    m = new String(cipher.doFinal(mm),"ISO-8859-1"); // decryption