开发者

BadPaddingException Error in RSA enryption/decryption

开发者 https://www.devze.com 2023-01-01 00:39 出处:网络
I am currently facing an error of BadPaddingException. I am sending the encrypted data from client to server. The server will do the decryption upon received data.

I am currently facing an error of BadPaddingException. I am sending the encrypted data from client to server. The server will do the decryption upon received data.

Could anyone help me take a look at the codes and point the error, please.

client side

try{
    Cipher c = Cipher.getInstance("RSA");
    c.init(Cipher.ENCRYPT_MODE, servPubKey);
    String myMessage = "this i开发者_高级运维s 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();
}

server side

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!");
}

it said that the error occoured in the following line.

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

thanks in advance for your help and guidance.


I assume you are missing this line from the client code:

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

Except for that, the most probable error is that servPubKey and serverPrivateKey does not match (i.e. they are not the two halves of the same RSA keypair).

A quick way to check that they match is to print servPubKey.getModulus() and serverPrivateKey.getModulus() and check that they are identical.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号