summaryrefslogtreecommitdiff
path: root/bin
diff options
context:
space:
mode:
authorMarc Vertes <mvertes@free.fr>2025-04-16 17:42:53 +0200
committerMarc Vertes <mvertes@free.fr>2025-04-16 17:42:53 +0200
commit0616e0cc96c141a686a4a4a3c1d1391e8b43b356 (patch)
treec614d4f18bd071d0279f95e67635a5eee87511c0 /bin
parent197f065a22a712d20d91862cbfb6ef4615774b4d (diff)
improve crypt
Diffstat (limited to 'bin')
-rwxr-xr-xbin/crypt60
1 files changed, 27 insertions, 33 deletions
diff --git a/bin/crypt b/bin/crypt
index c63d60a..64afc42 100755
--- a/bin/crypt
+++ b/bin/crypt
@@ -1,51 +1,45 @@
#!/bin/sh
-usage='Usage: crypt [-d] [-o output] [input]
+crypt_usage='Usage: crypt [-d] [-o output] [input]
-Encrypt or decrypt input (default: stdin) to ouput (default: stdout),
-using ssh rsa key.
+Encrypt or decrypt input (stdin) to ouput (stdout), using ssh rsa key.
Options:
-d action is decrypt (default: encrypt)
-o output set ouput (default: stdout)'
-key="$(mktemp)"
-trap 'rm -f $key' EXIT
-
# Encrypt stdin to stdout.
encrypt() {
- # Generate a random 256 bits one-time key, for symmetric aes encryption.
- openssl rand 32 >"$key"
-
- # Convert (only once) the ssh RSA public to PKCS8, for openssl.
- [ -f ~/.ssh/id_rsa.pub.pkcs8 ] ||
- ssh-keygen -e -f ~/.ssh/id_rsa.pub -m PKCS8 >~/.ssh/id_rsa.pub.pkcs8
+ set -- "$(openssl rand -hex 32)"
- # Output the one-time key asymmetrically encrypted with the rsa pubkey.
- openssl pkeyutl -encrypt -pubin -inkey ~/.ssh/id_rsa.pub.pkcs8 <"$key"
+ echo "$1" | openssl pkeyutl -encrypt -pubin -inkey /dev/fd/3 3<<- EOF
+ $(ssh-keygen -e -f ~/.ssh/id_rsa.pub -m PKCS8)
+ EOF
- # Now encrypt stdin to stdout, using the clear otk.
- openssl aes-256-cbc -pbkdf2 -pass "file:$key"
+ openssl aes-256-cbc -pbkdf2 -pass file:/dev/fd/3 3<<- EOF
+ $1
+ EOF
}
# Decrypt stdin to stdout.
decrypt() {
- # Recover the aes key from the first 256 input bytes.
- dd ibs=256 count=1 iflag=direct status=none |
- openssl pkeyutl -decrypt -inkey ~/.ssh/id_rsa -out "$key"
-
- # The remaining input is the payload, decrypt it with the aes key.
- openssl aes-256-cbc -d -pbkdf2 -pass "file:$key"
+ openssl aes-256-cbc -d -pbkdf2 -pass file:/dev/fd/3 3<<- EOF
+ $(dd ibs=256 count=1 iflag=direct status=none |
+ openssl pkeyutl -decrypt -inkey ~/.ssh/id_rsa)
+ EOF
}
-cmd=encrypt
-while getopts :do: opt; do
- case $opt in
- d) cmd=decrypt ;;
- o) exec 1>"$OPTARG" ;;
- *) echo "$usage" >&2; exit 1 ;;
- esac
-done
-shift $((OPTIND - 1))
-[ "$1" ] && exec 0<"$1"
-"$cmd"
+# Execute main only if not sourced.
+if [ "${0##*/}" = "crypt" ]; then
+ cmd=encrypt
+ while getopts :do: opt; do
+ case $opt in
+ d) cmd=decrypt ;;
+ o) exec 1>"$OPTARG" ;;
+ *) echo "$crypt_usage" >&2; exit 1 ;;
+ esac
+ done
+ shift $((OPTIND - 1))
+ [ "$1" ] && exec 0<"$1"
+ "$cmd"
+fi