summaryrefslogtreecommitdiff
path: root/bin/crypt
blob: fcc84aa8ed6e12810c17279203e8be91d2fad500 (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
37
38
39
40
41
42
43
44
#!/bin/sh

crypt_usage='Usage: crypt [-d] [-o output] [input]

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)'

# Encrypt stdin to stdout.
encrypt() {
	set --  "$(openssl rand -hex 32)"

	echo "$1" | openssl pkeyutl -encrypt -pubin -inkey /dev/fd/3 3<<- EOF
		$(ssh-keygen -e -f ~/.ssh/id_rsa.pub -m PKCS8)
	EOF

	openssl aes-256-cbc -pbkdf2 -iter 10000 -saltlen 8 -pass file:/dev/fd/3 3<<- EOF
		$1
	EOF
}

# Decrypt stdin to stdout.
decrypt() {
	openssl aes-256-cbc -d -pbkdf2 -iter 10000 -saltlen 8 -pass file:/dev/fd/3 3<<- EOF
		$(dd ibs=256 count=1 iflag=direct status=none |
			openssl pkeyutl -decrypt -inkey ~/.ssh/id_rsa)
	EOF
}

# 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))
	cat "${1:-/dev/stdin}" | "$cmd"  # XXX: despite being redundant, cat is required on some systems.
fi