How to Encrypt and Decrypt Files and Data With SSH - Part III
In the previous posts Part 1, Part 2 we saw how to encrypt and decrypt files directories, messages with GPG. In this article we’ll see how to encrypt and decrypt them with ssh keys.
Let’s start with creating a temporary directory called
ssh-enc in the root
/tmp directory and then enter in it.
$ mkdir -p /tmp/ssh-enc $ cd /tmp/ssh-enc
In order to encrypt files, directories and messages, you’ll need the
format of your public shh key. To convert the public key into PEM
format run below command:
$ ssh-keygen -f path/to/id_rsa.pub -e -m PKCS8 > /tpm/ssh-enc/id_rsa.pem # Example $ ssh-keygen -f ~/.ssh/id_rsa.pub -e -m PKCS8 > /tpm/ssh-enc/id_rsa.pem
Let’s see how to encrypt stin, file and directories.
1.0. Stdin Encryption
Using the public pem file to encrypt a
$ echo "some plain text" | openssl rsautl -encrypt -pubin -inkey /tmp/ssh-enc/id_rsa.pem > /tmp/ssh-enc/encrypted.txt
1.1. File Encryption
To encrypt a file:
$ openssl rsautl -encrypt -pubin -inkey /tmp/ssh-enc/id_rsa.pem < /tmp/ssh-enc/plain.txt > /tmp/ssh-enc/encrypted.txt # with cat $ cat /tmp/ssh-enc/plain.txt | openssl rsautl -encrypt -pubin -inkey /tmp/ssh-enc/id_rsa.pem > /tmp/ssh-enc/encrypted.txt
1.2. Directory Encryption
There is no recursive option for
ssh. Therefore you should turn your
directory into a file via
$ tar -czf /tmp/ssh-enc/my-directory.tar.gz /some/path/to/my-plain-directory/ $ zip -r /tmp/ssh-enc/my-directory.zip /some/path/to/my-plain-directory/
After that you can encrypt your compressed directory with your ssh keys:
$ openssl rsautl -encrypt -pubin -inkey /tmp/ssh-enc/id_rsa.pem < /tmp/ssh-enc/my-directory.tar > /tmp/ssh-enc/encrypted.txt
In order decrypt, you’ll need the related private key:
$ openssl rsautl -decrypt -inkey ~/.ssh/id_rsa < /tmp/ssh-enc/encrypted.txt > /tmp/ssh-enc/decrypted.txt # with cat $ cat /tmp/ssh-enc/encrypted.txt | openssl rsautl -decrypt -inkey ~/.ssh/id_rsa > /tmp/ssh-enc/decrypted.txt
If you are on a MacOS, you may have a
OPENSSH format instead of
for your private key.
You can convert it by running one of the below 2 commands:
To use with a passphrase:
$ ssh-keygen -p -P "old passphrase" -N "new passphrase" -m pem -f path/to/key
If you don’t want to use a passphrase at all:
$ ssh-keygen -p -N "" -m pem -f /path/to/key
This all for this post of the series.