0

I am using the following algo to encrypt/decrypt in Java -

cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

Encrypt/Decrypt methods are as follows -

    public String encryptString(String originalString) {
        String encryptedString = null;
        try {
            cipher.init(Cipher.ENCRYPT_MODE, secKey);
            byte[] encryptedBytes = cipher.doFinal(originalString.getBytes("UTF8"));
            encryptedString = new String(encryptedBytes,"UTF8");
        } catch (Exception ex) {
            LOGGER.error("Could not encrypt String {}", originalString, ex);
            ex.printStackTrace();
        }
        return encryptedString;
    }

    public String decryptString(String encryptedString) {
        String decryptedString = null;
        try {
            cipher.init(Cipher.DECRYPT_MODE, secKey);
            byte[] encryptedBytes = cipher.doFinal(encryptedString.getBytes("UTF8"));
            decryptedString = new String(encryptedBytes,"UTF8");
        } catch (Exception ex) {
            LOGGER.error("Could not decrypt String {}", encryptedString, ex);
            ex.printStackTrace();
        }
        return decryptedString;
    }

But it gives me following error

javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher
    at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)

If I remove all UTF-8 in String and getBytes() in works fine in on my local windows 7 machine but does not work on the my linux box (where tomcat is deployed) with same error as above. Any help or suggestion is appreciated.

It may not be relevant but I am saving and retrieving values from DB2 database.


I cannot use to store String in DB2 after base64 encoding due to existing data setups. I need to decrypt existing data with above alogo. It works on windows machine but not on Linux (all without utf-formats).


After some debugging it looks like new String() and getBytes() are using default platform specific locales. Also UTF-8 in new String() changes encoded bytes (which are multiple of 8 bytes as per DES) to non multiple of 8 due to which decryption fails. Using base64 is not an option.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
  • It is not duplicate. I don't want to use Base64 to after encode/decode. It works on my local windows box. Same code gives error on decrypting on Linux. – Aniket Thakur Dec 23 '15 at 11:32
  • 1
    Encryption produces 8-bit data bytes, not all 8-bit bytes sequences are valid UTF-8 characters strings. In general it is not possible for encrypted data to be directly expressed or converted to UTF-8 strings or any character encoding. The answer, like it or not, is to convert to a character encoding such as base64 or hexadecimal if you need the encrypted data as a character string. – zaph Dec 23 '15 at 14:36

0 Answers0