2

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.

Oscar K.
  • 71
  • 3
  • 9
  • Did you try ```Base64``` encode/decode with the flag ```Base64.NO_PADDING?``` – Jarvis Oct 31 '19 at 00:53
  • 2
    `c.doFinal(b64Key.getBytes()).toString();` doesn't do anything useful, but it does throw away all the data. `c.update(encryptedEncodedKey);` doesn't make sense given the code you've provided. Unfortunately there are some fundamental java mistakes that you should work through before trying to implement a crypto scheme. – President James K. Polk Oct 31 '19 at 01:30
  • @Jarvis: That only makes sense for Android's base64 class. Java's is different and doesn't have any flags. – President James K. Polk Oct 31 '19 at 01:35
  • You are base64-encoding at the sender but not base64-decoding at the receiver. – user207421 Oct 31 '19 at 06:45

0 Answers0