Skip to content

Instantly share code, notes, and snippets.

@toddlers
Created January 8, 2018 04:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toddlers/fa25e5a731703aa96bca0be848d9ba68 to your computer and use it in GitHub Desktop.
Save toddlers/fa25e5a731703aa96bca0be848d9ba68 to your computer and use it in GitHub Desktop.
SSH Encrypt/Decrypt

ENCRYPT A FILE USING A PUBLIC SSH KEY

Generate the symmetric key (32 bytes gives us the 256 bit key):

$ openssl rand 32 -out secret.key

You should only use this key this one time, by the way. If you send something to the recipient at another time, don’t reuse it.

Encrypt the file you’re sending, using the generated symmetric key:

$ openssl aes-256-cbc -in secretfile.txt -out secretfile.txt.enc -pass file:secret.key

In this example secretfile.txt is the unencrypted secret file, and secretfile.txt.enc is the encrypted file. The encrypted file can be named whatever you like.

Encrypt the symmetric key, using the recipient’s public SSH key:

$ openssl rsautl -encrypt -oaep -pubin -inkey <(ssh-keygen -e -f recipients-key.pub -m PKCS8) -in secret.key -out secret.key.enc

Replace recipients-key.pub with the recipient’s public SSH key.

Delete the unencrypted symmetric key, so you don’t leave it around:

$ rm secret.key

Now you can send the encrypted secret file (secretfile.txt.enc) and the encrypted symmetric key (secret.key.enc) to the recipient. It is even safe to upload the files to a public file sharing service and tell the recipient to download them from there.

DECRYPT A FILE ENCRYPTED WITH A PUBLIC SSH KEY First decrypt the symmetric.key:

$ openssl rsautl -decrypt -oaep -inkey ~/.ssh/id_rsa -in secret.key.enc -out secret.key

The recipient should replace ~/.ssh/id_rsa with the path to their secret key if needed. But this is the path to where it usually is located.

Now the secret file can be decrypted, using the symmetric key:

$ openssl aes-256-cbc -d -in secretfile.txt.enc -out secretfile.txt -pass file:secret.key

Again, here the encrypted file is secretfile.txt.enc and the unencrypted file will be named secretfile.txt

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