1
public static String decrypt(byte[] text, PrivateKey key) {
    byte[] decryptedText = null;
    try {
        final Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, key);
        decryptedText = cipher.doFinal(text);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return new String(decryptedText);
}

There is my code, for some reason I get this error and I think it is something to do with using the default constructor of the Cipher class.

Why am I getting this error?

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Archie
  • 13
  • 1
  • 5
  • BadPaddingException usually indicates a wrong password. – dpr May 29 '17 at 09:39
  • @dpr what do you mean by a "wrong password"? I'm trying some socket, server -> client messaging encryption for a school project. – Archie May 29 '17 at 09:40
  • *"I think it is something to do with using the default constructor of the Cipher class."* ___You___ don't use any constructor, especially not a default constructor (that class doesn't have one anyway). – Tom May 29 '17 at 09:42
  • Oh, of course, silly me. – Archie May 29 '17 at 09:44
  • Not sure how your setup looks like. But as it seems you try to decrypt something with a private key. In order to decrypt something it needs to be encrypted before with the same key (or the matching public key). It looks as if this is not the case in your setup. – dpr May 29 '17 at 10:58
  • @dpr ah, I see, I serialize the PublicKey via an ObjectOutputStream to the client side, and it must change the key as it works perfectly otherwise. – Archie May 29 '17 at 12:04
  • 1
    There is a great deal of missing information from this question that could be relevant. How are you encrypting it, how are you encoding and transmitting the encrypted result, how are you receiving and decoding prior to attempting decryption? `Cipher.getInstance("RSA");` uses platform defaults, a frequent source of bugs. So that immediately begs the question of whether the encryption platform is different than the decryption platform. Same with `new String(decryptedText);` – President James K. Polk May 29 '17 at 12:39
  • 1
    Welcome to Stack Overflow! A padding error can mean any number of things: wrong key, wrong encoding, incomplete/overfull ciphertext. You should show the encryption code and give the example values that you've used. Otherwise, it would be plain guessing what might be wrong with this code (or the encryption code). In short, please create a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – Artjom B. May 29 '17 at 19:03

1 Answers1

0

In order to lead to reasonable results, you often don't want to encrypt an arbitrary number of bytes.

Instead: you enlarge the number of bytes to encrypt using padding.

See here on the "why to pad?"

GhostCat
  • 137,827
  • 25
  • 176
  • 248