summaryrefslogtreecommitdiff
path: root/bin
diff options
context:
space:
mode:
authorMarc Vertes <mvertes@free.fr>2025-04-11 13:33:08 +0200
committerMarc Vertes <mvertes@free.fr>2025-04-11 13:33:08 +0200
commitb7927432c7574abb47425fd1af5e7d8ab8fc936c (patch)
tree4e3d1d8a96f584fc3801ca189e5217ae515c0b21 /bin
parentdc8fe54203e7353c5f873ef20a1b85c4c7a00b17 (diff)
improve crypt
Diffstat (limited to 'bin')
-rwxr-xr-xbin/crypt49
1 files changed, 33 insertions, 16 deletions
diff --git a/bin/crypt b/bin/crypt
index 01e7a31..939f3f5 100755
--- a/bin/crypt
+++ b/bin/crypt
@@ -1,36 +1,53 @@
#!/bin/sh
-# (de)crypt using ssh rsa key. ed25519 not supported.
+usage='Usage: crypt [-de] [-o output] [input]
-tmp="/tmp/enc-$$"
-mkdir -p "$tmp"
-trap 'rm -rf $tmp' INT TERM EXIT
+Encrypt or decrypt input (default: stdin) to ouput (default: stdout),
+using ssh rsa key.
+
+Options:
+ -d action is decrypt (default: encrypt)
+ -e action is 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 >"$tmp/key"
+ 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
# Output the one-time key asymmetrically encrypted with the rsa pubkey.
- ssh-keygen -e -f ~/.ssh/id_rsa.pub -m PKCS8 >"$tmp/pk"
- openssl pkeyutl -encrypt -pubin -inkey "$tmp/pk" <"$tmp/key"
+ openssl pkeyutl -encrypt -pubin -inkey ~/.ssh/id_rsa.pub.pkcs8 <"$key"
# Now encrypt stdin to stdout, using the clear otk.
- openssl aes-256-cbc -pbkdf2 -pass "file:$tmp/key"
+ openssl aes-256-cbc -pbkdf2 -pass "file:$key"
}
# Decrypt stdin to stdout.
decrypt() {
- # The first 256 input bytes contains the one time key to be decrypted
- # with the private rsa key.
- dd ibs=256 count=1 iflag=direct |
- openssl pkeyutl -decrypt -inkey ~/.ssh/id_rsa -out "$tmp/key"
+ # 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 decrypted with the aes key.
- openssl aes-256-cbc -d -pbkdf2 -pass "file:$tmp/key"
+ # The remaining input is the payload, decrypt it with the aes key.
+ openssl aes-256-cbc -d -pbkdf2 -pass "file:$key"
}
cmd=encrypt
-[ "$1" = "-d" ] && cmd=decrypt && shift
-[ "$1" ] && exec 0<"$1"
+while getopts :deo: opt; do
+ case $opt in
+ d) cmd=decrypt ;;
+ e) cmd=encrypt ;;
+ o) exec 1>"$OPTARG" ;;
+ *) echo "$usage" >&2; exit 1 ;;
+ esac
+done
+shift $((OPTIND - 1))
+[ "$1" ] && [ "$1" != "-" ] && exec 0<"$1"
"$cmd"