0

I have to encode a string using AES/ECB/PKCS5Padding. The encrypted result ( new String(encryptedResult) as they don't want bytes) is then sent to a partner. My partner then decrypt the string using getBytes().

Here is the decrypting method :

    public static String decrypter(final String donnees) throws NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, key);

    return new String(cipher.doFinal(donnees.getBytes()));
}

My problem is that I get this error when I try to decrypt : Input Length must be multiple of 16 when decrypting with padded cipher.

When I decode bytes directly it works just fine. How can I make the string.getBytes() not loose padding ? Or any other solutions ?

I cannot change the crypting algorythm, and the same can be said about the string and not bytes beeing sent to the partner.

Martin Remy
  • 83
  • 10
  • 3
    You can't just turn bytes into a String like that. At the least you'd need to use an 8-bit encoding, or preferably use something like Base64. – Kayaman Nov 29 '17 at 12:41
  • 1
    See https://stackoverflow.com/questions/1536054/how-to-convert-byte-array-to-string-and-vice-versa – Oleg Nov 29 '17 at 12:50
  • Thanks to both of you, the problem is solved. I had a quite wrong understanding of how bytes work. – Martin Remy Nov 29 '17 at 13:45
  • **Do not use ECB** mode in new work and update legacy work ASAP, it is not secure, see [ECB mode](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Electronic_Codebook_.28ECB.29), scroll down to the Penguin. Instead use CBC mode with a random IV, just prefix the encrypted data with the IV for use in decryption, it does not need to be secret. – zaph Nov 29 '17 at 15:10

1 Answers1

1

A padding error generally means the decryption failed and failures can include a incorrect key, data and encodings. Incorrect decryption has a side-effect of also producing incorrect padding.

In this case it is an incorrect encoding of the encrypted data. If you need the encrypted data as a string the general method is to use Base64 or hexadecimal encoding.

This code is incorrect: new String(cipher.doFinal(donnees.getBytes()));

zaph
  • 111,848
  • 21
  • 189
  • 228