Skip to content

Instantly share code, notes, and snippets.

@rickowski
Created October 27, 2015 12:48
Show Gist options
  • Save rickowski/6e73d51cfbcb9e36627b to your computer and use it in GitHub Desktop.
Save rickowski/6e73d51cfbcb9e36627b to your computer and use it in GitHub Desktop.
Encrypt files easy and basic with gpg
#!/bin/bash
# Copyright © 2015 Ole Rickowski
# This work is free. You can redistribute it and/or modify it under the
# terms of the Do What The Fuck You Want To Public License, Version 2,
# as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
main(){
# Check if target file exists
checkfile
# Perform operation
if [ $OPERATION == "e" ]; then
doencrypt
else
dodecrypt
fi
}
usage(){
echo "Usage: $0 <Operation> <File>"
echo "Options:"
echo -e "\t-e\tEncrypt file"
echo -e "\t-d\tDecrypt file"
echo -e "\t-f\tFile to En-/Decrypt"
exit 1
}
# Write in variable, which operation to be performed
setoperation(){
# If already set -> usage
if [ $OPERATION ]; then
echo "Only one operation can be performed!"
usage
fi
OPERATION=$1
}
# Check if the file to be operated exists
checkfile(){
# Check if given file exists
if [ ! -f $ENCFILE ]; then
prnt_red -e "\"$ENCFILE\" not found!\n"
usage
fi
}
# Encrypt the file with AES256
doencrypt(){
#Encrypt
gpg -q --cipher-algo AES256 --no-use-agent -c "$ENCFILE"
#Abort if error
if [ ! $? -eq 0 ]; then
prnt_red "Error!"
exit 1
fi
#Integrity check, if wanted
read -p "Check integrity of encryption? [y/n]" -n 1 -r
echo ""
if [[ $REPLY =~ ^[YyJj]$ ]]; then
#Decrypt again and check with original file
gpg -q --no-use-agent -d "$ENCFILE.gpg" | cmp - "$ENCFILE" > /dev/null 2>&1
if [ ! $? -eq 0 ]; then
prnt_red "Integrity failed!"
else
prnt_green "File seems to be alright!"
fi
fi
#Delete the original file if wanted
read -p "Do you want the non encrypted file deleted? [y/n]" -n 1 -r
echo ""
if [[ $REPLY =~ ^[YyJj]$ ]]; then
rm $ENCFILE
fi
}
#Decrypt the file
dodecrypt(){
gpg -q --no-use-agent "$ENCFILE"
#Abort if error
if [ ! $? -eq 0 ]; then
prnt_red "Error!"
exit 1
fi
#Delete encrypted file if wanted
read -p "Do you want the encrypted file deleted? [y/n]" -n 1 -r
echo ""
if [[ $REPLY =~ ^[YyJj]$ ]]; then
rm $ENCFILE
fi
}
#Functions to print in color
function prnt_green(){
echo -e "\e[1;32m$1\e[0m"
}
function prnt_red(){
echo -e "\e[1;31m$1\e[0m"
}
# ###############################################
# Start
# Parse Arguments
# Are Arguments given?
if [ $# -eq 0 ]; then
usage
fi
while getopts ":edf:" opt; do
case $opt in
e)
setoperation e
;;
d)
setoperation d
;;
f)
ENCFILE=$OPTARG
;;
\?)
echo "Wrong option: -$OPTARG"
usage
;;
:)
echo "Missing argument for option: -$OPTARG"
usage
;;
esac
done
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment