Tonight, I tried to write a Bash OpenSSL file decryption script. Encryption script will follow in highly similar manner, so I think it's not necessary now.
Let's suppose we have an encrypted large file using:
openssl enc -aes-256-cbc -salt -in somefile -out somefile.enc
You correctly noticed I always add .enc
to the file name.
The meaning of the script is:
take one, and only one, argument as a file
ask user for password
decrypt that file with
openssl
with a shown progresssave it without the
.enc
extension, or if it didn't have that extension, give it.dec
extensionnot to overwrite existing files
Though I wrote it with maximum effort, a review is more than welcome.
The script follows:
#!/bin/bash
if [ "$#" -ne 1 ] || [ ! -f "$1" ]
then
echo "A single existing file needs to be given as an argument. Exiting."
else
input_filename="$1"
filepath=$(dirname "$1")
filename_extracted_from_path=$(basename "$1")
filename_without_enc_extension="${filename_extracted_from_path%.enc}"
if [[ "$filename_extracted_from_path" == "$filename_without_enc_extension" ]]
then
output_filename="$filepath/$filename_extracted_from_path".dec
else
output_filename="$filepath/$filename_without_enc_extension"
fi
if [ -f "$output_filename" ]
then
echo "Destination file exists. Exiting."
else
pv "$input_filename" | openssl enc -aes-256-cbc -d -salt -out "$output_filename"
fi
fi
EDIT1:
I decided to put the script on GitHub (when done), therefore it must be POSIX compliant, so I have made minor changes.
I found out, the script lacks destination directory writable check, so I integrated it.
Also, it now checks if it is run as
root
(or withsudo
).
But the structure remains and new version of the script follows:
#!/bin/sh
if [ "$#" -ne 1 ] || [ ! -f "$1" ]
then
echo "A single existing file needs to be given as an argument. Exiting."
else
input_filename="$1"
filepath=$(dirname "$1")
filename_extracted_from_path=$(basename "$1")
filename_without_enc_extension="${filename_extracted_from_path%.enc}"
if [ "$filename_extracted_from_path" = "$filename_without_enc_extension" ]
then
output_filename="$filepath/$filename_extracted_from_path".dec
else
output_filename="$filepath/$filename_without_enc_extension"
fi
if [ -f "$output_filename" ]
then
echo "Destination file exists. Exiting."
else
if [ ! -w "$filepath" ] && [ "$(id -u)" -ne 0 ]
then
echo "Destination directory is not writable. Exiting."
else
pv --wait "$input_filename" | openssl enc -aes-256-cbc -d -salt -out "$output_filename"
fi
fi
fi
Uploaded on GitHub: https://git.io/fxslm