I'm currently working through a series of exercises in an attempt to improve my bash scripting knowledge.
The exercise I am working on is as follows: Write a script called encrypt.sh that's used to encrypt files. Here are the requirements for the script:
- It must use openssl to encrypt files.
- It must take the name of a file to encrypt as a parameter
- When it encrypts a file it must put the encrypted version in a file with the same name but ".enc" appended.
- It must be safe to run on a system with other users. That is, it must not pass any passwords as command line arguments.
- It must read the password to use from an environment variable called ENCRYPTION_KEY.
- If that environment variable is not set, it should prompt the user to enter a password and use that instead.
- It should display an error if no parameter is provided and exit with exit code 2.
- It should display a message if the user calls the script with a --help switch.
- It should work with files with spaces in the name.
I feel as if my current script has satisfied requirements 1-5,7-8. However I am somewhat floundered as to 6 and 9.
Any feedback on my current workings, or solutions to my missing requirements would be greatly appreciated.
Thank you in advance.
usage="Usage: Enter the name of the file you would like to encrypt as a parameter, eg. $0 words"
ENCRYPTION_KEY="1234"
export ENCRYPTION_KEY
openssl enc -e -aes256 -in "$1" -out "$1".enc -pass env:ENCRYPTION_KEY
if [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
echo $usage
fi
if test -z ${1}
then
echo "${0} :ERROR: No parameters provided. Please see -h or --help for usage." 1>&2
exit 1
fi
#DECODE (script is not required to decode, just here for testing purposes)
#openssl enc -d -aes256 -in words.enc -out words.enc.dec -pass env:ENCRYPTION_KEY
--helpswitch and for no arguments before, not after theopenssl enccommand. You should also changeif test -z ${1}toif test -z "$1"in order to satisfy point 9.ENCRYPTION_KEYif you want to be able to pass it to the script via the environment; btw, though that's a requirement, it's usually a stupid idea to pass password via the environment.