I finally found how to convert an OpenSSH public key to PEM format on a blog and was able to successfully encrypt and decrypt a string using my private/public key.
I've outlined the steps I used to perform the encryption and decryption.
To encrypt a string:
# convert public key to PEM format
ssh-keygen -f ~/.ssh/id_rsa.pub -e -m PKCS8 > ~/.ssh/id_rsa.pub.pem
# encrypt string using public key
echo "String to Encrypt" \
| openssl rsautl -pubin -inkey ~/.ssh/id_rsa.pub.pem -encrypt -pkcs \
| openssl enc -base64 \
> string.txt
To decrypt a string (from file):
openssl enc -base64 -d -in string.txt \
| openssl rsautl -inkey ~/.ssh/id_rsa -decrypt
Since my goal is to e-mail the password, I've written an extremely basic script to automate things a bit:
#!/bin/sh
if test "x${1}" == "x";then
echo "Usage: ${0} <username>"
exit 1
fi
SSHUSER=${1}
printf "Enter Password: "
read PASS1
echo ""
echo ""
ssh-keygen -f /home/${SSHUSER}/.ssh/id_rsa.pub -e -m PKCS8 \
> /tmp/ssh-pubkey-${SSHUSER}.pem
echo 'cat << EOF |openssl enc -base64 -d |openssl rsautl -inkey ~/.ssh/id_rsa -decrypt'
echo "New Password: ${PASS1}" \
| openssl rsautl -pubin -inkey /tmp/ssh-pubkey-${SSHUSER}.pem -encrypt -pkcs \
| openssl enc -base64
echo "EOF"
echo ""
rm -f /tmp/ssh-pubkey-${SSHUSER}.pem
I can then send the output of the script in an e-mail for the user to decrypt.
The complete script is available on Github: https://gist.github.com/3078682