blob: 01e7a31cb71cc6d1ee6031e34fb41190b6c1e2cf (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
#!/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"
|