Search code examples
linuxmacosterminalopenssl

Decryption of file in Linux, originally encrypted in Mac terminal using OpenSSL, does not decrypt correct in Linux (Ubuntu terminal)


I´m not a professional technician, I just try to understand how I can safely encrypt secret files using OpenSSL in the Mac terminal. Searching some websites I have successfully used some commands to encrypt and decrypt files in the mac terminal. I use the following commands in mac terminal to encrypt:

openssl enc -aes-256-cbc -salt -in Image.jpg -out Image.enc

The following command to decrypt (still on Mac):

openssl enc -d -aes-256-cbc -in Image.enc -out Image.jpg

This works, and the Image.jpg file is just fine after decrypting. When I however try to decrypt the same Image.enc file on a Linux machine (Ubuntu) using the same command, the file Image.jpg is created/decrypted, but is broken and cannot be opened. In the terminal i get the following message:

***** WARNING : deprecated key derivation used. Using -iter or -pbkdf2 would be better. bad decrypt 4017207B5A7F0000:error:1C80006B:Provider routines:ossl_cipher_generic_block_final:wrong final block length:../providers/implementations/ciphers/ciphercommon.c:429:**

I have searched the web, but cannot find any answer to this. As I said, I am not an IT-professional, so there are some expressions and terminology I don´t understand to well


Solution

  • The macOS and Linux versions of openssl enc use different default key derivation functions. That is, the way they turn a password into an encryption key is different, so even if you use the same password between them, the encryption key will be different, and the result is similar to if you'd used the wrong password.

    More specifically, older versions of openssl defaulted to using PBKDF1 ("Password-Based Key Derivation Function #1") with the MD5 hash, and a single iteration. This is... a pretty bad choice. In openssl version 1.1.0, the default was switched from MD5 to SHA256 (still with PBKDF1 and a single iteration), which is only slightly better. Your Linux system has a newer version of openssl, but macOS actually ships with LibreSSL instead of OpenSSL, which emulates an old version of openssl.

    You can force the macOS version to use the newer SHA256 key derivation by adding the -md sha256 option to the command, which'll make the encrypted file Linux-compatible. Alternately, you could add the -md md5 options on the Linux side to make it use the mac-default derivation function.

    Starting in version 1.1.1, openssl supports -iter and -pbkdf2, which'll let you choose a better key derivation function and/or more iterations (hence the message you got). This is great for security, but (at least as far as I know) not at all compatible with the macOS version of openssl (although you can install a newer version there with homebrew or something similar).

    For more details, see this answer on crypto.SE.