Often when seeting-up a VPN or other similar mechanism we need to transfer securely a private key or a list of passwords or anything very private to another party via email without running the risks of the man-in-the-middle snoopin on it. Here is a method using OpenSSL which is available in Linux.
Sending a one line key:
Example: A wants to send an encrypted PEM formatted key(/tmp/PSK.txt) to B:
Note: This work only for a single line formatted in PEM and NOT for a file.
For a file you need to use the second method shown below.
B creates a public key(/tmp/public.pem) in PEM format using his own ssh private-key(~/.ssh/id_rsa) and send it to A via email for example.:
openssl rsa -in ~/.ssh/id_rsa -out /tmp/public.pem -outform PEM -pubout
It would look like this for example:
-----BEGIN PUBLIC KEY-----
MIGdMA0GCSqGSIb3DQEBAQUAA4GLADCBhwKBgQDHxee5n1Na06RdBUjIYMRH5aC5
zo4XvgxC8NED0yUzjfX+adFgQbTRVuNOBtnSVm83XT1Bp/BKQqqx0hcMlazVRjrH
x2jUr4nCczSvVnq4cKzDyvO7tj5kOg1m6fliXcKv4cqjftQpOnz4RTmieyjb3+aN
1/JynAFpnLxKrF8bZQIBIw==
-----END PUBLIC KEY-----
A uses this public key(public.pem) to encrypt the PSK file(/tmp/PSK.txt) and send it to B via email:
openssl rsautl -encrypt -inkey /tmp/public.pem -pubin -in /tmp/PSK.txt -out /tmp/PSK.ssl
B decrypt the ecnryped file using his own ssh private-key(~/.ssh/id_rsa) to a file(/tmp/PSK.txt):
openssl rsautl -decrypt -inkey ~/.ssh/id_rsa -in /tmp/PSK.ssl -out /tmp/PSK.txt
Sending a FILE securely
A wants to encrypt a file(/tmp/file.txt) and send it to B:
B creates a self signed certificate using his own ssh private-key(~/.ssh/id_rsa) and sends it to A via email:
openssl req -x509 -new -key ~/.ssh/id_rsa > /tmp/rsa.crt
Country Name (2 letter code) [AU]:DE
State or Province Name (full name) [Some-State]:Berlin
Locality Name (eg, city) []:Berlin
Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Company Ltd
Organizational Unit Name (eg, section) []:Sysadmin
Common Name (e.g. server FQDN or YOUR name) []: MyCompany
Email Address []:myname@myserver.com
A encrypt the file(/tmp/file.txt) with the Certificate(/tmp/rsa.crt) and send it to B via email:
openssl smime -encrypt -binary -aes-256-cbc -in /tmp/file.txt -out /tmp/file.enc -outform DER /tmp/rsa.crt
B decrypt the file using his own ssh private-key(~/.ssh/id_rsa):
openssl smime -decrypt -binary -in /tmp/file.enc -inform DER -out /tmp/file.txt -inkey ~/.ssh/id_rsa
The file(/tmp/file.txt) is then been transfered securely from A(/tmp/file.txt) to B.