我编写了一个脚本,可以让我在 vim 中编辑 gpg 加密文件:
#!/bin/sh
read_password() {
printf "Enter passphrase: "
stty -echo
read password
stty echo
echo
}
usage() {
echo "Usage:"
echo "gpg-edit [-s/-a] [FILE]"
echo "-a asymmetric encryption"
echo "-s symmetric encryption"
}
if [ $# -ne 2 ]; then
usage
exit
else
file="$2"
if [ ! -f $file ]; then
echo "No such file, exiting"
exit
fi
if [ "$1" != "-s" ] && [ "$1" != "-a" ]; then
usage
exit
fi
fi
if [ -z "$EDITOR" ]; then
editor="vim"
else
editor=$EDITOR
fi
tmp_file="$(mktemp)"
if [ "$1" = "-a" ]; then
gpg -d --yes -o "$tmp_file" "$file"
elif [ "$1" = "-s" ]; then
read_password
echo "$password" | gpg -d --yes --passphrase-fd 0 --batch -o "$tmp_file" "$file"
fi
gpg_exit=$?
if [ $gpg_exit -ne 0 ]; then
echo "Decryption failed, exiting"
rm $tmp_file
exit
fi
original_mod_time=$(stat -c %Y "$tmp_file")
$editor "$tmp_file"
new_mod_time=$(stat -c %Y "$tmp_file")
if [ "$original_mod_time" -ne "$new_mod_time" ]; then
if [ "$1" = "-a" ]; then
gpg -o "$file" -e --yes -r recipient "$tmp_file"
elif [ "$1" = "-s" ]; then
echo "$password" | gpg -c --cipher-algo AES256 --yes --passphrase-fd 0 --batch -o "$file" "$tmp_file"
fi
gpg_exit=$?
if [ $gpg_exit -ne 0 ]; then
echo "Encryption failed, exiting"
fi
fi
shred -u "$tmp_file"
但是,它不安全,因为echo "$password"
它会在进程列表中显示密码(例如,当您运行 htop 时)。我该如何防止这种情况?我更希望它能在 POSIX 兼容的 shell 中运行dash
。我知道如果我不将密码存储在变量中,而是直接将其提供给 gpg,就不会出现此问题,但在对称加密的情况下,用户总共必须输入三次密码。