hash entire directory and/or list of files

This commit is contained in:
Asif Bacchus 2020-06-20 03:09:11 -06:00
parent 594c1eb0ad
commit ffa5602dff

62
sri
View File

@ -52,6 +52,8 @@ trapExit (){
### default variables ### default variables
scriptName="$( basename "$0" )" scriptName="$( basename "$0" )"
doDir=0
doFiles=0
algo='sha384' algo='sha384'
unset filename unset filename
@ -81,18 +83,25 @@ while [ $# -gt 0 ]; do
# generate SRI using sha512 # generate SRI using sha512
algo='sha512' algo='sha512'
;; ;;
-f|--file) -d|--dir|--directory)
# file for which to generate SRI hash # verify directory exists
if [ -n "$2" ]; then if [ -d "$2" ]; then
if [ -f "$2" ]; then doDir=1
filename="$2" hashDir="${2%/}"
else
displayError 1 "Directory '$2' does not exist."
fi
shift shift
;;
-f|--file)
# has supplied list of files
if [ -z "$2" ]; then
displayError 1 'No filename(s) specified.'
else else
displayError 3 "Cannot find file '${2}'." doFiles=1
fi hashFiles="$2"
else
displayError 3 'No filename specified.'
fi fi
shift
;; ;;
*) *)
# unknown option # unknown option
@ -103,18 +112,37 @@ while [ $# -gt 0 ]; do
esac esac
shift shift
done done
printf "\n"
printf "\n%sselected algo: %s%s\n" "$magenta" "$norm" "$algo"
printf "%sselected file: %s%s%s\n\n" "$magenta" "$norm" "$filename" "$norm"
### do SRI generation ### do SRI generation
hash=$( openssl dgst -${algo} -binary "${filename}" | openssl base64 -A) > /dev/null 2>&1 if [ "$doDir" -eq 1 ]; then
if [ -z "$hash" ]; then for file in "$hashDir"/*; do
displayError 4 'An error occurred while generating SRI hash.' hash=$( openssl dgst -${algo} -binary "$file" | openssl base64 -A) > /dev/null 2>&1
else if [ -z "$hash" ]; then
printf "%sSRI hash: %s%s-%s%s\n\n" "$magenta" "$ok" "$algo" "$hash" "$norm" printf "%s --> unable to generate SRI hash\n" "$file"
else
printf "%s%s --> %s%s-%s%s\n" "$magenta" "$file" "$ok" "$algo" "$hash" "$norm"
fi
done
fi fi
if [ "$doFiles" -eq 1 ]; then
for file in $hashFiles; do
# verify file exists, then hash it
if [ -f "$file" ]; then
hash=$( openssl dgst -${algo} -binary "$file" | openssl base64 -A) > /dev/null 2>&1
if [ -z "$hash" ]; then
printf "%s --> unable to generate SRI hash\n" "$file"
else
printf "%s%s --> %s%s-%s%s\n" "$magenta" "$file" "$ok" "$algo" "$hash" "$norm"
fi
else
printf "%s%s --> does not exist\n" "$err" "$file"
fi
done
fi
printf "\n"
exit 0 exit 0