SSH encrypt and decrypt

From ATI public wiki
Jump to: navigation, search

Tutorial on how to encrypt and decrypt small messages using Secure Shell keys

Why?

For example,
when You have to send someone a password and sending it over internet in plaintext is out of the question.

How to send Yourself a secret message (tutorial)

The keys

Everyone who uses Secure Shell (SSH) has an easy access to accompanying Secure Shell keys. When You do not have them, then You generate them.

All it takes is Linux, MacOS command line or Cygwin shell in Windows. A minute or two of Your time and few sips of tea. Done.


One can make simple passwordless RSA key-pair with ssh-keygen utility like this:

linux:/home/user> ssh-keygen -t rsa -b 4096
Generating public/private rsa key pair.
Enter file in which to save the key (/home/user/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/user/.ssh/id_rsa.
Your public key has been saved in /home/user/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:seDs6vDo55WegAZnG/mr8S+sgz2kvJFCc1wAGsHyB2c user@linux
The key's randomart image is:
+---[RSA 4096]----+
|+o..             |
|oo. E            |
|o. + .. .        |
|  o.oo . o       |
|.o=+  o S        |
|.+== . .         |
|oB*.o +          |
|+o=*+* .         |
| o*OBo+          |
+----[SHA256]-----+

The process above creates 2 files id_rsa id_rsa.pub and places them into subfolder .ssh relative to Your home directory.

The contents of the public key id_rsa.pub should be like this:

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC0slKFeI2QKDbele2YNbbsQnIuIr070sAAcK3lazDRNEfSAVqcevAoUoTFRe7BRKjeTzj74q8XGfH6/OciiVGpvF9La/a8apXB0x4qYdCA+S/pZJGbl8MLRMMuaU+7sUSd0wEhru5H8LXilpRjNBht+In4+CJKEOWb3TJ2gAPHp8hACdCpyKUNz6g+hcE8Vkx/JoMXDqhyGGr2qVcVTDxZ/Y506LyOMwarnzdz7JYLBq8LPOiHI6BNIUSnC8HixQ9DnJev44ZVJcoKLLM/kn7GNVczZ+L8xKC5i5GB+rAWPy4unQqqB9pAwKUjZ3WRRPFH8TcRprjiHlsZjeW27nAPeIu+jE0fQWKSWMdGt1CTYJuOGf7zOFCHupHC6S6EKqVUtni3GuiM+NQHukGAk95DWGydVY6OSTJP0a5/4akS/KmpOZ20WTer1BV171DZI3X8P35vwJIaP9Aamg4pDhQUSXSn1f9YD5lgXmhhgFVcyjo+ox6Q2VuVNX/eLW7WxtfmDBYCHbJEzIb3nHH2CWb47YyA+pYbku4WjFDTRc7blgsnCjCMGHPHXyP8TLLWB6ZiLYwAvucK78rljkTXwPALllktMG9YN215CRJGqZcWaCiVspWJvSwpMF8nJR842IpgkGFtlcMoPFoPwuv8yMUa+3bu2T3nwULOmZCsEBJiXQ== user@linux

And the contents of the private key id_rsa should be like this:

SSH private key, file id_rsa contents
click to expand
-----BEGIN RSA PRIVATE KEY-----
MIIJKQIBAAKCAgEAu5Z/XRKcm5pxUMTcAHM643DqdvheWVDTwsG5R3RAF18HN7kt
P/WLgk3bJy3gMTEetczE5uEV6ukY2ZgrPyOqAfORjB5cRfzy4TsRCqJ0eljY4PEo
A54gJFCzlOBiQwL8pL1KHwMQGyer54++VTVay8+te9AXWkX6K9aRWM+FVuUPAjnX
RZ6OpDmcJ+AXn2e3LEIENgs4gTnHGxwCYYuHkRivWFj2C8fIOgMoYjX7eUO68151
jgLlsRQEvpedYA2xTSQ9gP/UTTSbxJWrUjkDHr7Qyq3JKudU/cjeYDN9ZXgxwuJz
777jMgfnoAQgAdywtLKEqY8Be5z9zYmfU7C4AgXBbacDDmcRfjgHHIbIwYTo411A
22HvMzl+af0NTb1ALk5vCpb8hVdWozNb0eAnPa3L9UGvcu/rko59E0UA0pJ3CtNA
Xo/ZX7OLucrdehAmUQtD97bMrEFr+pP21t8r2XqvNfH6EparArL9cVXbGuVvkpRz
xnXhJmHFogOlHLPXOnF9pkFj7HL0ScYqkhll8niDLG3+AyjCcEQ0vmIuRpMONfa5
K8sH9XQLY4yKFbZzWcpIUUeSkSWkAfo7os7e+D4+xUcTLAUXaZsvs9QaNnMKZU+A
5FSd5uv8H/Ku+ejX03G1CGDV9nJYzA0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c9XRoxAoIBAQCjE2+VQOtWWV+6ab3TlsZ0nWM7
kKTcWlz0WixKAfGzkYtypW3qlli3M8JqDGPw4M5o4VR1c5gjj0hIr37ywBi9PtrM
nkz3iRI8sTyTWqfns/NfQiJrSCWMvTOChxDskm7gxn6cz2/OcmsqUINjQdm+mqiE
cd/4Awso2itT0NUkhoZSRon5cwOCqJg8DukLBdXrmWDmDqJDulzAZTZlbAMxeSn4
M1Vrc7QD6jtNBxlJsvDolatOccZv9dVCLUIUUkkTN41uIq96F+4mxW63SqTW0MaT
PGN9FPjRVXSuyyDrVyua7Z3R4wqy1RFc7XMaXxg5qaqhiZbXkBU444NkU0jg
-----END RSA PRIVATE KEY-----

To encrypt

Now You have Your pair of keys, the public one id_rsa.pub is used to encrypt and the private one id_rsa to decrypt a message.

Create the message

Take Your favorite text editor and create short text file message.txt with some content like:

This is very serious short message.
That will be encrypted.
And decrypted.

Prepare Your public key for encryption

One drawback or discouraging step for encryption is that Your public key is not usable as is.

To be usable with openssl utility it has to be in PKCS8 format.

Public key can be converted to PKCS8 format with ssh-keygen utility like this:

linux:/home/user> ssh-keygen -f ~/.ssh/id_rsa.pub -e -m pkcs8 > id_rsa_pub.pkcs8

The contents of such converted key should be like this:

-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAtLJShXiNkCg23pXtmDW2
7EJyLiK9O9LAAHCt5Wsw0TRH0gFanHrwKFKExUXuwUSo3k84++KvFxnx+vznIolR
qbxfS2v2vGqVwdMeKmHQgPkv6WSRm5fDC0TDLmlPu7FEndMBIa7uR/C14paUYzQY
bfiJ+PgiShDlm90ydoADx6fIQAnQqcilDc+oPoXBPFZMfyaDFw6ochhq9qlXFUw8
Wf2OdOi8jjMGq583c+yWCwavCzzohyOgTSFEpwvB4sUPQ5yXr+OGVSXKCiyzP5J+
xjVXM2fi/MSguYuRgfqwFj8uLp0KqgfaQMClI2d1kUTxR/E3Eaa44h5bGY3ltu5w
D3iLvoxNH0FikljHRrdQk2Cbjhn+8zhQh7qRwukuhCqlVLZ4txrojPjUB7pBgJPe
Q1hsnVWOjkkyT9Guf+GpEvypqTmdtFk3q9QVde9Q2SN1/D9+b8CSGj/QGpoOKQ4U
FEl0p9X/WA+ZYF5oYYBVXMo6PqMekNlblTV/3i1u1sbX5gwWAh2yRMyG95xx9glm
+O2MgPqWG5LuFoxQ00XO25YLJwowjBhzx18j/Eyy1gemYi2MAL7nCu/K5Y5E18Dw
C5ZZLTBvWDdteQkSRqmXFmgolbKVib0sKTBfJyUfONiKYJBhbZXDKDxaD8Lr/MjF
Gvt27tk958FCzpmQrBASYl0CAwEAAQ==
-----END PUBLIC KEY-----

Encrypt the message

Now You can encrypt Your super secret message with converted public key like this:

linux:/home/user> cat message.txt | openssl rsautl -encrypt -pubin -inkey id_rsa_pub.pkcs8 > message.enc

In above example we pipe the contents of message.txt file to openssl utility that uses converted public key id_rsa_pub.pkcs8 and then we store the output in file message.enc

To decrypt

To decrypt the encrypted message file message.enc we use openssl utility like this:

linux:/home/user> cat message.enc | openssl rsautl -decrypt -inkey ~/.ssh/id_rsa
This is very serious short message.
That will be encrypted.
And decrypted.

In above example the contents of decrypted message are show in startard output.

To save decrypted contents one can modify the command like this:

linux:/home/user> cat message.enc | openssl rsautl -decrypt -inkey ~/.ssh/id_rsa > message.txt

Real world

In real world, when You have to pass someone sensitive small message, like a password

  1. You ask that someone to send You their public key
    • If that public key is not already in PKCS8 format then You convert it
  2. You encrypt Your message with that someone's public key that is in PKCS8 format
  3. You send the encrypted message to that someone
  4. That someone decrypts Your message with their private key

Contrary to tutorial above Your SSH keys are not needed when You are sending an encrypted message. You only need the other persons public key.



When someone sends You their public key, save it to a file someone.pub. Create Your secret message message.txt. Then do following, firstly to convert the key and secondly to encrypt Your message:

linux:/home/user> ssh-keygen -f someone.pub -e -m pkcs8 > someone_pub.pkcs8
linux:/home/user> cat message.txt | openssl rsautl -encrypt -pubin -inkey someone_pub.pkcs8 > message.enc

And send the output message.enc as a file to that someone.

That person then does following and reads the message content from standard output:

linux:/home/someone> cat message.enc | openssl rsautl -decrypt -inkey ~/.ssh/id_rsa
This is very serious short message.
That will be encrypted.
And decrypted.

Notes

Message size

This encryption / decryption method is suitable for small messages, messages whose bitlength is smaller than used RSA key length.

If You want to encrypt longer messages or some big file(s) then the above method can be used for passing on encrypted passwords that are used for file encryption/decryption.

One should use CBC (Cipher Block Chaining) continuous block cipher like AES256 for big file encryption / decryption. openssl utility is able to do that too.

openssl enc -aes256 -kfile message.txt -in file -out file.enc

What the path?

~ denotes users home directory, in essence its a shortcut for /home/user

Then ~/.ssh means subfolder .ssh that resides in users home directory /home/user

When using full path the above would be /home/user/.ssh

Decryption fail

In reference to: https://medium.com/@6et/convert-openssh-rsa-key-to-a-pem-file-80753fdbac00

When You see following error unable to load Private Key...Expecting: ANY PRIVATE KEY.

This means that Your private key is not in PEM format. To check if that is the case, You can view the contents of your ~/.ssh/id_rsa file and see if it starts with line

-----BEGIN OPENSSH PRIVATE KEY-----

Different versions of Secure Shell than You are currently using may have generated such keys. Secure Shell itself is able to handle different versions of private key formats as it converts/reads in them into suitable format for itself. Trouble lies with other utilities like openssl that can handle only specific/specified formats.


To convert Your private key into usable form, issue command

ssh-keygen -p -m PEM -f ~/.ssh/id_rsa

After that Your private key should start with line

-----BEGIN RSA PRIVATE KEY-----

And now You can decrypt the message using openssl utility.

Private stuff

Your key pair that You generated is Your sensitive security information.

Your public key can be passed on to persons/organizations You know, to authenticate You as a sign-on method (go see Gitlab), or it can be used as in above tutorial to encrypt messages. Being "public" does not mean You should openly advertise the contents of that key. It is theoretically possible to re-create private key based on public key, that process takes massive amounts of supercomputer time and is exponentially difficult based on key length. The longer the key the better. There is a tradeoff - longer keys work slower. In above tutorial we used 4096 bit keys that are quite okay by todays (2019) standards.

Your private key should never be shown or given out to anyone. The best practice is to encrypt Your private key with a password.

ssh-keygen utility is able to do that like this:
linux:/home/user> ssh-keygen -p -f ~/.ssh/id_rsa
Enter new passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved with the new passphrase.

When You lose your private key, then all is lost. Unless You work for NSA and have supercomputer farm at hand. So keep it safe and secure.

Martian messages

Obviously encrypted messages are not human readable. If You made a mistake of looking the contents and Your command line went gibberish, issue following command by blindly typing: reset. This resets the terminal and You should see normal command line again.