Skip to content

Instantly share code, notes, and snippets.

@SansGuidon
Forked from mingfang/convert id_rsa to pem
Last active June 9, 2017 17:33
Show Gist options
  • Save SansGuidon/78f90e742dc3a993d17573be5ceadabd to your computer and use it in GitHub Desktop.
Save SansGuidon/78f90e742dc3a993d17573be5ceadabd to your computer and use it in GitHub Desktop.
OpenSSL for files encryption
# create a PEM pub key (will be useful later)
openssl rsa -in .ssh/id_rsa -pubout -out id_rsa.pub.pem
# check it
chmod 700 id_rsa.pub.pem
openssl rsa -in id_rsa.pub.pem -pubin -text -noout
# 1) encrypt small file, using only RSA private and pub key
# create a secret
echo "my secret" > secret.txt
# encrypt the file using your public key
openssl rsautl -encrypt -inkey id_rsa.pub.pem -pubin -in secret.txt -out secret.enc
# decrypt the file using your private key
openssl rsautl -decrypt -inkey .ssh/id_rsa -in secret.enc
# 2) encrypt large files using RSA
# generate a random key / password file
openssl rand -base64 128 -out key.bin
# encrypt the large file with the random key
openssl enc -aes-256-cbc -salt -in secret.txt -out secret.enc -pass file:key.bin
# encrypt the random key with public key file
openssl rsautl -encrypt -inkey id_rsa.pub.pem -pubin -in key.bin -out key.bin.enc
# decrypt the random key with the private key file
openssl rsautl -decrypt -inkey id_rsa -in key.bin.enc -out key.bin
# decrypt the large file with the random key
openssl enc -d -aes-256-cbc -in secret.enc -out secret.txt -pass file:key.bin
# source https://raymii.org/s/tutorials/Encrypt_and_decrypt_files_to_public_keys_via_the_OpenSSL_Command_Line.html
# 3) encrypt large files without using priv/pub key at all but only OpenSSL and a password (you will be prompted)
openssl aes-256-cbc -salt -in secret.txt -out secret.txt.enc
openssl aes-256-cbc -d -in secret.txt -out secret.txt.enc
# source http://tombuntu.com/index.php/2007/12/12/simple-file-encryption-with-openssl/
@SansGuidon
Copy link
Author

SansGuidon commented Jun 8, 2017

Remarks :
RSA is not suited for encrypting 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)
GPG should be prefered to OpenSSL (more info https://stackoverflow.com/a/31552829/2309958)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment