Last active
March 11, 2023 20:35
-
-
Save rlcamp/dc2308aeb323cee4cbeda0c68d147040 to your computer and use it in GitHub Desktop.
encryption and decryption using an openssh-formatted rsa public-private key pair
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# TODO: this leaks the session key to arguments visible to ps while decrypting | |
set -euo pipefail | |
# if an argument was provided, use it as the path to the rsa private key, otherwise assume openssh | |
keypath=${1:-"$HOME/.ssh/id_rsa"} | |
# deal with converting openssh special file format to something openssl understands | |
TMPFILE=$(mktemp) | |
cp -p "$keypath" $TMPFILE | |
# if the rsa key was passphrase protected, you will be prompted for it during the below command | |
ssh-keygen -q -p -m pkcs8 -f $TMPFILE -N '' 1>/dev/null | |
exec 9<$TMPFILE | |
exec 8<$TMPFILE | |
rm $TMPFILE | |
# extract first 384 bytes from stdin, decrypt them with the RSA private key, and hex encode them | |
KEYPLUSIV=$(dd status=none bs=$( openssl pkey -in /dev/fd/8 -text | awk '/Private-Key/ { print substr($3, 2) / 8 }') count=1 | openssl rsautl -decrypt -inkey /dev/fd/9 | xxd -p -c0) | |
# don't need private key anymore | |
exec 8<&- | |
exec 9<&- | |
# run openssl AES decryption on the rest of stdin, using the resulting session key and iv | |
exec openssl enc -d -aes-256-cbc -K "${KEYPLUSIV:0:64}" -iv "${KEYPLUSIV:64:}" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# TODO: this leaks the session key to arguments visible to ps while encrypting | |
set -euo pipefail | |
if (( $# < 1 )); then | |
printf "error: must provide path to recipient's id_rsa.pub\n" >&2 | |
exit 1; | |
fi | |
# generate 32+16 bytes of random key and iv, hex encoded | |
KEYPLUSIV=$(openssl rand -hex 48) | |
# public-key encrypt the binary representation of key and iv, converting from openssh .pub format | |
xxd -r -p <<< "$KEYPLUSIV" | openssl pkeyutl -encrypt -pubin -inkey <( ssh-keygen -f $1 -e -m pkcs8 ) | |
# run openssl AES on stdin, using the hex version of the session key and iv | |
exec openssl enc -aes-256-cbc -K "${KEYPLUSIV:0:64}" -iv "${KEYPLUSIV:64:}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment