简体   繁体   中英

Proper way to decrypt CryptoJS DES encoded string using Java?

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 (ie the way to encrypt the string using DES). Thank you very much.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM