Skip to content

Instantly share code, notes, and snippets.

@markuskreitzer
Last active August 29, 2015 14:00
Show Gist options
  • Save markuskreitzer/d4026777db4fc743e7ea to your computer and use it in GitHub Desktop.
Save markuskreitzer/d4026777db4fc743e7ea to your computer and use it in GitHub Desktop.
Decypt and Encrypt using OpenSSH pivate and public keys

How to encrypt a file using a OpenSSH public key.

Requirements:

  • openssl
  • ssh-keygen
  • sshpub-to-rsa
    • Python with the following libs:
      • pyasn1

Directions

If you haven't already, generate an SSH key using ssh-keygen. Not that you encrypt with the public key (that everyone has) and decrypt with the private key (the secret key only you have).

# ssh-keygen -b 2048 
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/username/.ssh/id_rsa): booger_rsa
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in booger_rsa.
Your public key has been saved in booger_rsa.pub.
The key fingerprint is:
69:1d:8c:9e:24:14:c7:80:4a:a7:83:a1:77:43:23:a5 [email protected]
The key's randomart image is:
+--[ RSA 2048]----+
|   ...++.        |
|. o.=. ..o       |
|.+E* .. o o      |
|o = o  + + .     |
| . o .  S .      |
|       .         |
|                 |
|                 |
|                 |
+-----------------+

To encrypt:

  • sh encrypt_with_pub.sh id_rsa.pub cleartext_file.txt

To decrypt:

  • sh decrypt_with_priv.sh id_rsa base64_encrypted_file.txt
#!/usr/bin/env bash
base64 --decode $2 > ./.encrypted.tmp
openssl rsautl -decrypt -inkey $1 -in ./.encrypted.tmp -out decrypted.txt
rm -f ./.encrypted.tmp
cat decrypted.txt
rm decrypted.txt
#!/usr/bin/env bash
# Convert public key from OpenSSH to OpenSSL format
public_key="$1.pem"
if sshpub-to-rsa $1 |grep -v -i comment > $public_key;
then
echo "Converted to PEM"
else
echo "failed to convert to pem"
exit -1
fi
# Get the above script at https://gist.github.com/1024558
# Encrypt message using public key
if openssl rsautl -encrypt -inkey $public_key -pubin -in $2 -out $2.secret
then
echo Encrypted
else
echo Failed to encrypt message
exit -1
fi
# Convert to base64 for easier copy/pasta (optional)
base64 $2.secret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment