Skip to content

Instantly share code, notes, and snippets.

@Lajule
Created January 14, 2025 09:08
Show Gist options
  • Save Lajule/fa8e8fa1edcead0b0286dbfea11e8bc1 to your computer and use it in GitHub Desktop.
Save Lajule/fa8e8fa1edcead0b0286dbfea11e8bc1 to your computer and use it in GitHub Desktop.
Copy a file to a crypted version.
#######################################
# Copy a file to a crypted version.
# Globals:
# CRPT_PASSWORD
# Arguments:
# Decrypt file ? (optional).
# Remove file ? (optional).
# Given source file.
# Given destination file.
# Returns:
# 0 if file is copied, non-zero on error.
#######################################
crpt() {
local rm
declare -a options
options+=('aes-256-cbc')
while [[ "$1" = -* ]]; do
case "$1" in
-r | --rm) rm='yes' ;;
-d | --decrypt) options+=('-d') ;;
*) echo 'Unknown option' >&2; return 1 ;;
esac
shift
done
if (( $# < 2 )); then
echo 'Missing arguments' >&2
return 1
fi
if [[ "$1" == "$2" ]]; then
echo 'Source and destination file names are the same' >&2
return 1
fi
options+=('-salt')
options+=('-pbkdf2')
options+=('-in')
options+=("$1")
options+=('-out')
options+=("$2")
if [[ -n "${CRPT_PASSWORD}" ]]; then
options+=('-pass')
options+=('env:CRPT_PASSWORD')
fi
if openssl "${options[@]}" && [[ -n "${rm}" ]]; then
rm -f "$1"
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment