Created
October 16, 2023 01:11
-
-
Save TurnerSoftwareDev/8ec63c58ab10802a64d3d48c94096d9a to your computer and use it in GitHub Desktop.
Symmetrically encrypt or decrypt a file with GnuPG using a password
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# | |
# Shell script that encrypts or decrypts a file with a password using GnuPG. | |
# The encrypted file is named with a .scramble extension. | |
# Input file is deleted unless the --keep flag is specified. | |
# | |
# Usage: | |
# | |
# scramble [--keep] <file> | |
# | |
cipher="AES256" | |
# Check that a command is installed | |
installed () { command -v "${1}" >/dev/null 2>&1 || { >&2 echo "Cannot execute the ${1} command"; exit 1; } } | |
installed chmod | |
installed file | |
installed gpg | |
installed grep | |
# Whether or not to keep the original file after encrypting or decrypting it. | |
keep=false | |
scramble_params=( ) | |
while [[ $# != 0 ]]; do | |
case "${1}" in | |
-k|--keep) | |
keep=true | |
shift | |
;; | |
*) | |
scramble_params+=("${1}") | |
shift | |
;; | |
esac | |
done | |
if [[ ${#scramble_params[@]} = 0 ]]; then | |
>&2 echo "Missing the file argument." | |
exit 1 | |
fi | |
# TODO: encrypt/decrypt multiple files rather than just the first one provided on the command line. | |
input_file="${scramble_params[@]}" | |
if [[ ! -r ${input_file} ]]; then | |
>&2 echo "${input_file} cannot be read." | |
exit 1 | |
fi | |
output_file= | |
if grep --quiet "encrypted" <(file "${input_file}"); then | |
# TODO: Use the cipher from the output of the file command | |
output_file=$(echo "${input_file}" | sed s/\.scramble$//) | |
gpg --cipher-algo "${cipher}" --quiet --output "${output_file}" --decrypt "${input_file}" >/dev/null | |
else | |
output_file="${input_file}.scramble" | |
gpg --cipher-algo "${cipher}" --quiet --output "${output_file}" --symmetric "${input_file}" > /dev/null | |
# Don't allow modification of the encrypted file. | |
chmod -f a-w "${output_file}" | |
fi | |
# Make sure the output file was created before deleting the input file | |
if [[ -s ${output_file} ]]; then | |
# Only delete the input file if we aren't keeping it | |
if [[ ${keep} = false ]]; then | |
rm -f "${input_file}" | |
fi | |
else | |
>&2 echo "${output_file} was not created." | |
exit 1 | |
fi | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment