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.