Skip to content

Instantly share code, notes, and snippets.

@icasdri
Created July 2, 2016 19:41
Show Gist options
  • Save icasdri/04185fe00c9fc67176de3e652563dd58 to your computer and use it in GitHub Desktop.
Save icasdri/04185fe00c9fc67176de3e652563dd58 to your computer and use it in GitHub Desktop.
Wrapper around ssh-keygen, openssl, and base64 to exchange small asymmetric encrypted messages
#!/bin/bash
# Copyright 2016 icasdri
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
improper_usage() {
echo 'Usage: enc_wrapper.sh (encrypt|decrypt) KEY'
echo ' where KEY is an OpenSSH RSA key (public/private as appropriate)'
echo
echo 'Example: '
echo ' To encrypt: enc_wrapper.sh enc ~/.ssh/id_rsa.pub'
echo ' To decrypt: enc_wrapper.sh dec ~/.ssh/id_rsa'
exit 2
}
if [ "$#" -ne 2 ]; then
improper_usage
fi
KEY_TARGET='/tmp/enc_wrapper.pub'
umask 077
case "$1" in
e*)
if [ -f "$2" ]; then
echo "Reading ssh-rsa public key from $2..."
echo "Converting to PKCS8 format..."
ssh-keygen -e -f "$2" -m PKCS8 > "$KEY_TARGET"
echo "Enter message then press Return followed by Ctrl-D to end stream: "
openssl rsautl -encrypt -inkey "$KEY_TARGET" -pubin -pkcs | base64 -w0
echo
echo "The last printed line is your encrypted message."
else
echo "Failed to read key: no such file $2"
fi
;;
d*)
if [ -f "$2" ]; then
echo "Reading PEM private key from $2"
echo "Enter encrypted message then press Return followed by Ctrl-D to end stream: "
base64 -dw0 | openssl rsautl -decrypt -inkey "$2" -pkcs
else
echo "Failed to read key: no such file $2"
fi
;;
*)
improper_usage
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment