Encrypt and decrypt files to public keys via the OpenSSL Command Line

Table of Contents

This small tutorial will show you how to use the openssl command line to encrypt and decrypt a file using a public key. We will first generate a random key, encrypt that random key against the public key of the other person and use that random key to encrypt the actual file with using symmetric encryption.

Because of how the RSA algorithm works it is not possible to encrypt large files. If you create a key of n bits, then the file you want to encrypt must not larger than (n minus 11) bits. The most effective use of RSA crypto is to encrypt a random generated password, then encrypt the file with the password using symmetric crypto. If the file is larger then the key size the encryption command will fail:

We generate a random file and use that as the key to encrypt the large file with symmetric crypto. That random file acts as the password so to say. We encrypt the large file with the small password file as password. Then we send the encrypted file and the encrypted key to the other party and then can decrypt the key with their public key, the use that key to decrypt the large file.

Generate the random password file

Use the following command to generate the random key:

openssl rand -hex 64 -out key.bin

Do this every time you encrypt a file. Use a new key every time!

Update 25-10-2018

The key format is HEX because the base64 format adds newlines. The -pass argument later on only takes the first line of the file, so the full key is not used. (Thanks Ken Larson for pointing this to me)

Encrypt the file with the random key

Use the following command to encrypt the large file with the random key: