Search code examples
javaopenssldes

How do I decrypt a Java-DES-encrypted message using openssl?


Since the question title is self-explaining, please consider the following code:

private static final String ALGORITHM = "DES";
private static final String MESSAGE = "This is an extremely secret message";
private static final byte[] key = { 0, 1, 2, 3, 4, 5, 6, 7 };

...

// Do encryption
final Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(ENCRYPT_MODE, new SecretKeySpec(key, ALGORITHM));
final byte[] encrypted = cipher.doFinal(MESSAGE.getBytes());

// Copy the encrypted message to a file
final InputStream inputStream = new ByteArrayInputStream(encrypted);
final OutputStream outputStream = new FileOutputStream("___SECRET");
copy(inputStream, outputStream);

Now I'm trying to decrypt the ___SECRET file with the following command:

openssl enc -d -des -K 0001020304050607 -iv 0 -in ___SECRET -out ___OPEN

which results in:

bad decrypt
3073636028:error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt:evp_enc.c:539:

just decrypting the very first block (8 bytes) leaving the rest in trash state (OEM encoding):

This is MЕ$S6%@╢Т√°ў╝°╢]∙iь

What am I doing wrong and how do I decrypt the encrypted message using openssl?


Solution

  • On Java you use DES in ECB mode and on OpenSSL you use DES in CBC mode (IV is present).

    This is a significant difference as in CBC the blocks are chained - therefore the first block is decrypted correctly but all following blocks are scrambled.

    You can change the Java part to use "DES/CBC" mode instead and provide an IV or change the openssl part and use -des-ecb instead of -des.