Skip to content

Instantly share code, notes, and snippets.

@kbagher
Created December 13, 2023 04:30
Show Gist options
  • Save kbagher/b4336d338b5138626434389f29a01c17 to your computer and use it in GitHub Desktop.
Save kbagher/b4336d338b5138626434389f29a01c17 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Function to list all files except .txt files and allow user selection by number
select_file() {
echo "Available files:"
local i=1
for file in *; do
if [[ $file != *.txt ]]; then
echo "$i) $file"
files[i++]="$file"
fi
done
read -p "Select a file by number: " file_number
filename="${files[file_number]}"
if [ -z "$filename" ] || [ ! -f "$filename" ]; then
echo "Invalid selection or file does not exist."
exit 1
fi
}
# Function to format the output filename
format_output_filename() {
local base_name="${1%.*}"
local extension="${1##*.}"
base_name=$(echo "$base_name" | sed -e 's/_encrypted$//' -e 's/_decrypted$//')
echo "${base_name}_${2}.${extension}"
}
# Function to ask for encryption/decryption
select_operation() {
echo "Select operation:"
echo "1) Encrypt"
echo "2) Decrypt"
read -p "Enter your choice (1 or 2): " operation_choice
case $operation_choice in
1) operation="encrypt" ;;
2) operation="decrypt" ;;
*) echo "Invalid operation."
exit 1 ;;
esac
}
# Function to get passphrase from user
get_user_input() {
read -p "Enter passphrase: " passphrase
}
# Function to perform the encryption or decryption
perform_operation() {
local iter=10000
local output_filename
if [ "$operation" == "encrypt" ]; then
local iv=$(openssl rand -hex 16)
output_filename=$(format_output_filename "$filename" "encrypted")
openssl enc -aes-256-cbc -e -in "$filename" -pass "pass:$passphrase" -pbkdf2 -iter $iter -iv "$iv" | xxd -p -c 256 | cat <(echo -n "$iv") - > "$output_filename"
echo "Encryption complete. Output: $output_filename"
elif [ "$operation" == "decrypt" ]; then
local iv=$(head -c 32 "$filename")
output_filename=$(format_output_filename "$filename" "decrypted")
xxd -r -p <(tail -c +33 "$filename") > temp_decrypted
openssl enc -aes-256-cbc -d -in temp_decrypted -out "$output_filename" -pass "pass:$passphrase" -pbkdf2 -iter $iter -iv "$iv"
rm temp_decrypted
echo "Decryption complete. Output: $output_filename"
fi
}
# Main script logic
select_file
select_operation
get_user_input
perform_operation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment