Encrypting Files with openssl
Here is how to encrypt and decrypt files using public-key encryption and openssl.
I prefer this over GPG because openssl is installed everywhere (including OS X by default) and it requires no specialized subsystem (keyrings, etc.). Just two key files and the document to be encrypted.
Private Key EncryptionI use RSA encryption. There are three commands in openssl relevant to RSA:
- genrsa - Generates an RSA private key.
- rsa - Manages RSA private keys (includes generating the public key from it).
- rsautl - Encrypt and decrypt files using RSA keys.
Symmetric Key EncryptionSymmetric key encryption is an encryption algorithm that encrypts and decrypts a file using a single key or password.
In openssl, the enc command performs symmetric key encryption (among other things). To use it, you must choose (1) an algorithm, or “cipher,” and (2) a password.
The cipher I use is aes-256-cbc. The “aes” stands for Advanced Encryption Standard, which seems pretty well respected. The 256 is the key size, and the cbc stands for Cipher Block Chaining, which is less vulnerable to standard cryptanalysis than the other option, ebc.
The key is just a string of random bytes. I use a base64 encoded string of 30 bytes, which comes out to 41 characters. Since 41 characters is 328 bits, even a small RSA key will be able to encrypt it.
Procedures for Encryption and DecryptionThe following steps encrypt a file:
- Choose a random key.
- Encrypt the random key using the RSA public key to produce the encrypted key.
- Use the (unencrypted) random key as a symmetric key encryption password, to encrypt the data, producing the encrypted data.
- Return the encrypted key and the encrypted data to the user.
The steps for decryption are:
- Decrypt the encrypted key using the RSA private key, to retrieve the random key.
- Decrypt the encrypted data using the random key and symmetric key decryption.