Oscar K.
Oscar K.

Reputation: 71

How to fix javax.crypto.BadPaddingException: Decryption error in Java

I am trying to make a Server/Client Echo program with encryption.

By looking for a bit I found this post which had an answer with simple step by step guide on what needs to be done to encrypt communication between the server and client. I am now on the last step of decrypting the key. My problem is that when the server tries decrypt the key it fails and spits out this error:

Exception in thread "main" javax.crypto.BadPaddingException: Decryption error
        at java.base/sun.security.rsa.RSAPadding.unpadOAEP(RSAPadding.java:497)
        at java.base/sun.security.rsa.RSAPadding.unpad(RSAPadding.java:292)
        at java.base/com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:366)
        at java.base/com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:392)
        at java.base/javax.crypto.Cipher.doFinal(Cipher.java:2202)
        at EnServer.main(EnServer.java:58)

I have tried changing the padding multiple times, but to be honest I don't know what else to do.

This is what the client does when encrypting the key:

Cipher c = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
c.init(Cipher.ENCRYPT_MODE, publicKey);

byte[] encodedKey = key.getEncoded();
String b64Key = Base64.getEncoder().encodeToString(ek);
String eek = c.doFinal(b64Key.getBytes()).toString();
out.println(encryptedEncodedKey);

This is what the Server does when trying to decrypt the key:

String encryptedEncodedKey = in.readLine();
Cipher c = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
c.init(Cipher.DECRYPT_MODE, kp.getPrivate());
//below is the line of code that the error points to
byte[] encodedKey = c.doFinal(encryptedEncodedKey.getBytes());
Key key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "DES");
System.out.println(key);

Anyway, thanks in advance.

Upvotes: 2

Views: 10438

Answers (0)

Related Questions