#!/bin/sh # (de)crypt using ssh rsa key. ed25519 not supported. tmp="/tmp/enc-$$" mkdir -p "$tmp" trap 'rm -rf $tmp' INT TERM EXIT # Encrypt stdin to stdout. encrypt() { # Generate a random 256 bits one-time key, for symmetric aes encryption. openssl rand 32 >"$tmp/key" # 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" # Now encrypt stdin to stdout, using the clear otk. openssl aes-256-cbc -pbkdf2 -pass "file:$tmp/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" # The remaining input is the payload decrypted with the aes key. openssl aes-256-cbc -d -pbkdf2 -pass "file:$tmp/key" } cmd=encrypt [ "$1" = "-d" ] && cmd=decrypt && shift [ "$1" ] && exec 0<"$1" "$cmd"