BadPaddingException RSA加密/解密错误

时间:2010-05-27 07:23:14

标签: java rsa padding encryption

我目前正面临BadPaddingException错误。我将加密数据从客户端发送到服务器。服务器将根据收到的数据进行解密 请问有人帮我看看代码并指出错误。

客户端

try{
    Cipher c = Cipher.getInstance("RSA");
    c.init(Cipher.ENCRYPT_MODE, servPubKey);
    String myMessage = "this is a secret message";
    byte[] msgByte = myMessage.getBytes();
    ObjectOutputStream outVehicle3 = new ObjectOutputStream(socket.getOutputStream());
    ParamClass print4 = new ParamClass (cipherText);
    outVehicle3.writeObject(print4);
}  catch (Throwable e) {
    // TODO Auto-generated catch block
    tv.append("\nUnable to perform RSA encryption!");
    e.printStackTrace();
}

服务器端

ObjectInputStream inServ3 = new ObjectInputStream(socket.getInputStream());
try{
    ParamClass print5 = (ParamClass) (inServ3.readObject());
    Cipher dec = Cipher.getInstance("RSA");
    dec.init(Cipher.DECRYPT_MODE, serverPrivateKey);
    byte[] dectyptedText = dec.doFinal(print5.cipherText);
    String decipherText = dectyptedText.toString();
    System.out.println("\nDecrypted Message to string: " + decipherText);
}catch (Throwable e) {
    e.printStackTrace();
    System.out.println("Unable to perform RSA decryption!");
}

它说错误发生在以下行。

byte[] dectyptedText = dec.doFinal(print5.cipherText);

提前感谢您的帮助和指导。

1 个答案:

答案 0 :(得分:2)

我假设您在客户端代码中缺少此行:

byte[] cipherText = c.doFinal(msgByte);

除此之外,最可能的错误是servPubKeyserverPrivateKey不匹配(即它们不是同一RSA密钥对的两半)。

检查它们是否匹配的快速方法是打印servPubKey.getModulus()和serverPrivateKey.getModulus()并检查它们是否相同。