In JavaScript side I use:
CryptoJS.DES.encrypt('Content', 'password').toString()
The result:
U2FsdGVkX1/25rW2q0X7/pOtExFyP7MD
In Java side I try to decrypt it:
public static void main(String[] args) throws Exception {
String password = "password";
String encryptedString = "U2FsdGVkX1/25rW2q0X7/pOtExFyP7MD";
DESKeySpec key = new DESKeySpec(password.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
SecureRandom secureRandom = new SecureRandom();
byte[] ivspec = new byte[cipher.getBlockSize()];
secureRandom.nextBytes(ivspec);
IvParameterSpec iv = new IvParameterSpec(ivspec);
cipher.init(Cipher.DECRYPT_MODE, keyFactory.generateSecret(key), iv);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedString.getBytes()));
System.out.println(new String(Base64.getEncoder().encode(decryptedBytes)));
}
But I'm getting the bad padding error:
Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
Can anyone tell me what went wrong and what is the proper way to decrypt it? Assuming that the JavaScript side code cannot be changed (i.e the way to encrypt the string using DES). Thank you very much.