Encrypting/decrypting a file can be done easily with OpenSSL. First, you need to generate an RSA key pair; the public key will be used for encryption and the private one will be used to decrypt.

  • Generate the keypair (2048 will be the size used in this example):
openssl genrsa -out private.key 2048
openssl rsa -pubout -in private.key -out public.key
  • Encrypt the file (test.txt):
openssl rsautl -encrypt -inkey public.key -pubin -in test.txt -out test.encrypted
  • Decrypt the file:
openssl rsautl -decrypt -inkey private.key -in test.encrypted -out test.decrypted

Notes:

  • the size of the encrypted file will grow by a few bytes; an RSA buffer has a size of (S/8), where S is the bit size of the key. The size of an encrypted file will therefore be aligned on buffers of (S/8) bytes (e.g. 256 bytes for a 2048-bit key)
  • given the pseudorandom nature of encrypted contents, an encrypted file cannot be compressed. If you wish to compress the file, do it before you encrypt it.