-1

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.

Antony Ng
  • 767
  • 8
  • 16
  • In general a padding error is an indication that the decryption failed. – zaph Mar 02 '18 at 11:42
  • **Do not use DES for new work**, it is no longer considered secure and has been superceeded by AES (Advanced Encryption Standard) DES only has key size is only 56 bits which is not considered to be secure, AES supports key sizes of 128,192 and 256 bits. See [Security comparison of DES and AES](https://security.stackexchange.com/a/26181/5121). – zaph Mar 02 '18 at 11:43
  • The data always begins with 53616c7465645f5f. This is from the OpenSSL formatter, so you need to decode using this format to get the IV and data bytes. – fgb Mar 02 '18 at 12:35
  • This is for AES but should be similar: https://stackoverflow.com/questions/29151211/how-to-decrypt-an-encrypted-aes-256-string-from-cryptojs-using-java – fgb Mar 02 '18 at 12:36
  • Thanks fgb, I finally solved the problem using the example in your link. If you post an answer I'll just mark it as accepted. – Antony Ng Mar 03 '18 at 08:13

1 Answers1

1

The IV must be the same for both encryption and decryption. in the example a new random IV is being created for decryption: secureRandom.nextBytes(ivspec);.

You need to carefully and fully review the CryptoJS documentation to determine how the IV is being handled. Often the IV is prepended to the encrypted data for use during decryption.

The encryptedString seems to be Base64 encoded and the decoded length is 32-bytes, just right for a 16-byte IV and 16-byte encrypted data+padding.

zaph
  • 111,848
  • 21
  • 189
  • 228