#!/bin/bash set -euo pipefail SCRIPT_PATH=$(dirname "$(readlink -f "$0")") function help { echo " gpg-tool.sh [args] file Commands: -d, --decrypt decrypt file -e, --encrypt encrypt file -r, --reencrypt decrypt and encrypt all .asc files in directory -v, --view view encrypted file -i, --import_keys import keys -h, --help display help Example: ./gpg-tool.sh --import_keys ./gpg-tool.sh --view secrets.txt.asc ./gpg-tool.sh --decrypt secrets.txt.asc ./gpg-tool.sh --encrypt secrets.txt ./gpg-tool.sh --reencrypt . " } function decrypt { local FILE="$1" gpg --decrypt-files "${SCRIPT_PATH:?}/${FILE}" rm -r "${SCRIPT_PATH:?}/${FILE}" } function view { local FILE="$1" gpg --decrypt "${SCRIPT_PATH:?}/${FILE}" 2> /dev/null } function import_keys { for i in ls "${SCRIPT_PATH:?}"/keys/*.pub; do gpg --import "$i" 2>&1 | head -1 | awk '{print $3}' | sed 's/.$//' > /dev/null done echo 'All keys have been imported' } function get_recipients { local ALL_KEYS for i in "${SCRIPT_PATH:?}"/keys/*.pub; do ALL_KEYS+="--recipient $(gpg --import "$i" 2>&1 | head -1 | awk '{print $3}' | sed 's/.$//') " done echo "${ALL_KEYS}" } function encrypt { local PUBLIC_KEYS PUBLIC_KEYS=$(get_recipients) local FILE="$1" # shellcheck disable=SC2086 gpg --encrypt-files --trust-model always ${PUBLIC_KEYS} --armor "${FILE}" } function reencrypt { local PUBLIC_KEYS PUBLIC_KEYS=$(get_recipients) local CHECK_REMOVE local DIR="$1" local LIST_FILES_ASC local LIST_FILES LIST_FILES_ASC=$(find "$SCRIPT_PATH/${DIR}/" -type f -name "*.asc") LIST_FILES=$(echo "${LIST_FILES_ASC}" | awk '{gsub(/\.asc$/,""); print}') echo -e "List files for decrypt:\n${LIST_FILES_ASC}\n" read -r -p 'Decrypt files for future reencrypt. Are you sure (y/N): ' CHECK_DECRYPT if ! [ "${CHECK_DECRYPT}" == "y" ] || [ "${CHECK_DECRYPT}" == "Y" ]; then exit 1 fi echo "${LIST_FILES_ASC}" | gpg --decrypt-files echo -e "\n" read -r -p 'Reencrypt decrypted files. Are you sure (y/N): ' CHECK_REENCRYPT if [ "${CHECK_REENCRYPT}" == "y" ] || [ "${CHECK_REENCRYPT}" == "Y" ]; then # shellcheck disable=SC2086 echo "${LIST_FILES}" | gpg --encrypt-files --trust-model always ${PUBLIC_KEYS} --armor --yes fi echo -e "\nList decrypted files for remove:\n${LIST_FILES}\n" read -r -p 'Remove decrypted files. Are you sure (y/N): ' CHECK_REMOVE if [ "${CHECK_REMOVE}" == "y" ] || [ "${CHECK_REMOVE}" == "Y" ]; then echo "${LIST_FILES}" | xargs rm -f fi } if [ $# = 0 ]; then help exit fi case $1 in -i | --import_keys) import_keys && exit 0 ;; -d | --decrypt) decrypt "$2" ;; -e | --encrypt) encrypt "$2" ;; -r | --reencrypt) reencrypt "$2" ;; -v | --view) view "$2" ;; -h | --help) help exit ;; *) help exit 0 ;; esac