lock

Image by Alexlion on Pixabay

Reminder to myself how to encrypt and decrypt data on the shell:

prepare

$ # generate RSA key in PEM format
$ ssh-keygen -f ~/.ssh/dummy_key -t rsa -b 4096 -m PEM
Generating public/private RSA key pair.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/username/.ssh/dummy_key
Your public key has been saved in /home/username/.ssh/dummy_key.pub
The key fingerprint is: <here is some fingerprint>
The key's randomart image is:
+---[RSA 3072]----+
|                 |
|      here       |
|       is        |
|      some       |
|    randomart    |
|                 |
|                 |
|.                |
|                 |
+----[SHA256]-----+
$ # convert public key of dummy key to PEM
$ ssh-keygen -f ~/.ssh/dummy_key -e -m pem > ~/.ssh/dummy_pub.pem

encrypt, then decrypt

$ # encrypt
$ echo "mytest" | openssl pkeyutl -encrypt -pubin -inkey ~/.ssh/dummy_pub.pem  > encrypted.dat
$ # decrypt
$ cat encrypted.dat | openssl pkeyutl -decrypt -inkey ~/.ssh/dummy_key | cat 
mytest

encrypt and encode in base64, then decode base64 and decrypt:

$ # encrypt and encode
$ echo "mytest" | openssl pkeyutl -encrypt -pubin -inkey ~/.ssh/dummy_pub.pem | base64 > encrypted.b64
$ # decode and decrypt
$ cat encrypted.b64 | base64 --decode | openssl pkeyutl -decrypt -inkey ~/.ssh/dummy_key | cat
mytest

Why is it so complicated? Because of differences between OpenSSL and OpenSSH, different algorithms etc.