-
Notifications
You must be signed in to change notification settings - Fork 0
/
encryptFile
executable file
·85 lines (71 loc) · 1.87 KB
/
encryptFile
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/bin/bash
# See also decryptFile
# SETUP --------------------------------------------------------------
ENCKEY=''
KDF='pbkdf2'
ITER='5555555' # iterations for key derivation # ~6 seconds @ Intel(R) Xeon(R) CPU E3-1230 v3 @ 3.30GHz
CIPHER='aes-256-cbc'
DIGEST='sha256'
# --------------------------------------------------------------------
set -ueo pipefail
SUFFIX=".$KDF.$ITER.$CIPHER.$DIGEST.enc"
# pv
BLOCKSIZE=16
if [ $# -lt 1 ]; then
APP=${0##*/}
echo "Encrypt a file."
echo
echo "KDF: $KDF"
echo "Iterations: $ITER"
echo "Cipher: $CIPHER"
echo "Digest: $DIGEST"
echo
echo "Usage: $APP <input> [<output>]"
echo
echo "If <output> is - then output is redirected to STDOUT"
echo "If <output> is empty '$SUFFIX' is appended to input file name"
echo
exit 1
fi >&2
if [ ! -e "$1" ]; then # -f does not catch FIFOs
echo -e "Error: File '$1' not found.\n" >&2
exit 1
fi
checkBinarys() {
#http://stackoverflow.com/a/677212/568737
BINS=("$@")
for BIN in "${BINS[@]}"; do
hash "$BIN" 2>/dev/null || {
echo -e "Error: Binary '$BIN' is missing.\n" >&2
exit 1
}
done
}
# Check if all needed binarys are present
checkBinarys "openssl" "pv" "stat"
if [ -z "${ENCKEY:-}" ]; then
read -r -s -p "Enter password: " ENCKEY
echo
[ -z "$ENCKEY" ] && echo && exit 1
read -r -s -p "Repeat password: " ENCKEY2
echo
if [ "$ENCKEY" != "$ENCKEY2" ]; then
echo
echo "Error: Passwords not matching."
echo
exit 1
fi >&2
fi
CMD=("openssl" "$CIPHER" "-salt" "-$KDF" "-iter" "$ITER" "-md" "$DIGEST" "-k" "$ENCKEY" "-in" "$1")
if [ "${2:-}" == "-" ]; then
# STDOUT
echo "Encrypting: $1" >&2
"${CMD[@]}"
else
# OUTPUT to FILE
[ -z "${2:-}" ] && set "$1" "$1$SUFFIX"
# TODO Check if destination file already exist
echo "Encrypting: $1 --> $2"
"${CMD[@]}" | pv -bper -s $(( ($(stat -c%s "$1") + BLOCKSIZE) / BLOCKSIZE * BLOCKSIZE + BLOCKSIZE)) > "$2"
echo
fi