Skip to content

Instantly share code, notes, and snippets.

@jobwat
Created January 5, 2022 23:18
Show Gist options
  • Save jobwat/0cb95f902acfacc6dc276e080581ad11 to your computer and use it in GitHub Desktop.
Save jobwat/0cb95f902acfacc6dc276e080581ad11 to your computer and use it in GitHub Desktop.
encrypt text with ssh key pair
## encrypt text with SSH key
# Notes:
# It's not as straightforward as someone would think!
# Need to convert the keys to an openssl known format (PEM) first.
# Also, SSH keys aren't meant to encrypt content larger than 200bytes
# Sources:
# https://superuser.com/questions/576506/how-to-use-ssh-rsa-public-key-to-encrypt-a-text
# https://serverfault.com/questions/706336/how-to-get-a-pem-file-from-ssh-key-pair
# https://superuser.com/questions/1679344/for-valid-pem-i-get-unable-to-load-private-key-by-openssh
# backup your original private key (just in case you need that original OPENSSH format in the future)
cp ~/.ssh/id_rsa ~/.ssh/id_rsa.original
# ensure your private key is in PEM format (RSA PRIVATE KEY (pem), not OPENSSH PRIVATE KEY (RFC4716))
ssh-keygen -p -N "" -m pem -f ~/.ssh/id_rsa
# get the public key to PEM format as well
ssh-keygen -f ~/.ssh/id_rsa.pub -m PKCS8 -e > ~/.ssh/id_rsa.pem.pub
# encrypt text
echo 'Hi' | openssl rsautl -encrypt -pubin -inkey ~/.ssh/id_rsa.pem.pub > /tmp/message.encrypted
# decrypt
cat /tmp/message.encrypted | openssl rsautl -decrypt -inkey ~/.ssh/id_rsa
# encrypt text
echo 'Hi' | openssl rsautl -encrypt -pubin -inkey ~/.ssh/id_rsa_asx_aws.pem.pub > /tmp/message.encrypted
# decrypt
cat /tmp/message.encrypted | openssl rsautl -decrypt -inkey ~/.ssh/id_rsa_asx_aws
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment