Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
SSH Encrypt/Decrypt


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 -m PKCS8) -in secret.key -out secret.key.enc

Replace 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
You can’t perform that action at this time.