Skip to content

Instantly share code, notes, and snippets.

@unrelentingfox
Last active April 22, 2021 01:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unrelentingfox/56d7322c43c59475c8f99b20899c837f to your computer and use it in GitHub Desktop.
Save unrelentingfox/56d7322c43c59475c8f99b20899c837f to your computer and use it in GitHub Desktop.
Quick 7z based directory locking script. I created this because I want an easy way to quickly encrypt and decrypt a directory.
#!/bin/bash
USAGE_TEXT="Usage: locker.sh <command> target
Commands:
lock Expects target to be a directory. This directory will be compressed
with a password using 7z removing the original directory afterwards.
unlock Expects target to be a 7z compressed file. Unlocks the given
directory using 7z removing the original compressed file afterwards.
help Display this help text.
"
COMMAND=$1
TARGET=${2%/} # Remove trailing /
throw_error () {
echo "ERROR: $1" > /dev/stderr
exit 1
}
throw_user_error () {
echo "ERROR: $1" > /dev/stderr
echo "$USAGE_TEXT"
exit 1
}
check_target_type () {
if [[ -z "$2" ]]; then
throw_user_error "Missing target as second parameter."
elif [[ "$1" = "lock" && ! -d "$2" ]]; then
throw_user_error "Target must be a directory."
elif [[ "$1" = "unlock" && ! -f "$2" ]]; then
throw_user_error "Target must be a file."
fi
}
shred_files () {
if [[ -d "$1" ]]; then
echo "Shredding old directory after encryption.."
find "$1" -type f -exec shred -uz {} +
rm -r "$1"
elif [[ -f "$1" ]]; then
echo "Shredding old file after decryption.."
shred -uz "$1"
fi
}
if [[ "$COMMAND" = "lock" ]]; then
check_target_type "$COMMAND" "$TARGET"
if 7z a -p -mhe -t7z "$TARGET" "$TARGET"; then
shred_files "$TARGET"
else
throw_error "Lock failed!"
fi
elif [[ "$COMMAND" = "unlock" ]]; then
check_target_type "$COMMAND" "$TARGET"
if 7z x "$TARGET"; then
shred_files "$TARGET"
else
throw_error "Unlock failed!"
fi
elif [[ "$COMMAND" = "-h" || "$COMMAND" = "--help" || "$COMMAND" = "help" ]]; then
echo "$USAGE_TEXT"
else
throw_user_error "Missing or invalid command."
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment