解密错误填充错误

时间:2015-02-25 06:45:38

标签: java encryption rsa badpaddingexception

我正在尝试在两个代理之间发送加密消息。我有一个字符串,其中包含我转换为字节的信息,然后再将字符串加密以发送消息。但是,收到消息,在接收代理处我收到以下异常

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)

我在同一个容器中尝试了代理的代码,但它工作正常,但是如果它们在不同的容器上则没有。

这是我加密消息的方式:

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

这是我解密它的方式:

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

1 个答案:

答案 0 :(得分:3)

使用base64编码作为加密输出,不要使用new String(),因为某些字节值不能正确表示为字符串。所以当再次反转为字节时,它将不是正确的加密值

这就是我的意思:

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