Decryption Error bad padding

我的梦境 提交于 2019-12-13 05:43:42

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/28712847/decryption-error-bad-padding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!