1

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?

Lyubomyr Shaydariv
  • 20,327
  • 12
  • 64
  • 105
  • 1
    @jww: Aside from the minor difference in algorithm, 11783062 is about encrypting with openssl's default PBE which is indeed EVP_BytesToKey; this is about encrypting with key **NOT PBE**, which is a MAJOR difference. The PBE solution there is completely wrong here. A **better dupe** is http://stackoverflow.com/questions/37354200/blowfish-encrypt-in-java-scala-and-decrypt-in-bash although the earlier answer by Robert is already correct. – dave_thompson_085 Aug 24 '16 at 19:40
  • 1
    OP: do be aware that hardware improvements made **DES insecure** more than 20 years ago and it should not be used for any security purpose. _Triple_ DES, designated DESede in Java for historical reasons, is still aceeptably secure but other algorithms especially AES afe better. – dave_thompson_085 Aug 24 '16 at 19:45
  • @dave_thompson_085 yes, I'm aware of DES weakness. My question was a sort of a result of some reverse engineering, so `openssl` use is supposed for scripting only. Thank you for the comments! – Lyubomyr Shaydariv Aug 24 '16 at 21:24

1 Answers1

3

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.

Robert
  • 39,162
  • 17
  • 99
  • 152