Skip to content

Instantly share code, notes, and snippets.

@TechNickAI
Created March 24, 2023 18:01
Show Gist options
  • Save TechNickAI/2fc9e490f772562ba2204f47e22b693f to your computer and use it in GitHub Desktop.
Save TechNickAI/2fc9e490f772562ba2204f47e22b693f to your computer and use it in GitHub Desktop.
encrypt/decrypt text
#!/bin/bash
OPTIONS="-aes-256-cbc -base64 -pbkdf2 -iter 4200000 -salt"
function encrypt {
local input_file="$1"
local output_file="$2"
openssl enc $OPTIONS \
-in "$input_file" \
-out "$output_file" \
-k "$(read -s -p 'Enter your password: ' password; echo $password)"
if [ $? -eq 0 ]; then
echo
echo "✅ Encrypted text saved to $output_file"
else
echo
echo "❌ Encryption failed"
exit 1
fi
}
function decrypt {
local input_file="$1"
local output_file="$2"
openssl enc $OPTIONS \
-d \
-in "$input_file" \
-k "$(read -s -p 'Enter your password: ' password; echo $password)" \
> "$output_file"
if [ $? -eq 0 ]; then
echo
echo "✅ Decrypted text saved to $output_file"
else
echo
echo "❌ Decryption failed"
exit 1
fi
}
function test_decrypt {
local encrypted_file="$1"
local decrypted_file="$2"
echo "Testing decryption to verify the password..."
decrypt "$encrypted_file" "$decrypted_file"
if [ $? -eq 0 ]; then
echo "Test decryption succeeded, password is correct"
rm "$decrypted_file"
else
echo "Test decryption failed, password is incorrect"
exit 1
fi
}
if [[ "$#" -lt 3 ]]; then
echo "Usage: $0 encrypt|decrypt input_file output_file"
exit 1
fi
command="$1"
input_file="$2"
output_file="$3"
case "$command" in
encrypt)
encrypt "$input_file" "$output_file"
test_decrypt "$output_file" "test_decrypted_file.txt"
;;
decrypt)
decrypt "$input_file" "$output_file"
;;
*)
echo "Invalid command. Use 'encrypt' or 'decrypt'."
exit 1
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment