Public-key cryptography is not suitable for encrypting large files. A naive approach to encrypting a large file will return an error if the file is larger than the RSA key:
[smoonen@smoonen encryption]$ dd if=/dev/zero bs=1024 count=1024 | openssl pkeyutl -encrypt -pubin -inkey pubkey.pem Public Key operation error 140544802154400:error:0406D06E:rsa routines:RSA_padding_add_PKCS1_type_2:data too large for key size:rsa_pk1.c:151:
The general approach is to encrypt the file using symmetric cryptography, and encrypt the symmetric key using public-key cryptography. The OpenSSL smime command uses this approach, but it does not support extremely large files.
To support this case, I’ve written some simple file encryption shell scripts which I’ve posted on GitHub. These scripts are as follows:
- genkeypair generates a private and public key pair
- encrfile encrypts one or more files using AES-256 encryption, encrypts the AES-256 keys using public-key encryption, and saves the encrypted key as part of the encrypted file
- decrfile decrypts a single file previously encrypted by encrfile, by extracting the encrypted AES-256 key, decrypting it using public-key encryption, and then decrypting the file itself. The decrypted data is sent to stdout.