Skip to content

Instantly share code, notes, and snippets.

@Techcable
Created April 26, 2016 22:37
Show Gist options
  • Select an option

  • Save Techcable/1ca0785d46fcb03f8351ce85cfe62223 to your computer and use it in GitHub Desktop.

Select an option

Save Techcable/1ca0785d46fcb03f8351ce85cfe62223 to your computer and use it in GitHub Desktop.
A script to verify files match cryptographic hashses
#!/bin/bash
usage() {
echo "Usage: assert-hash [type] file hash"
echo "[type] is the type of hash to use, it is optional, and defaults to sha256"
echo "file is the file to hash"
echo "hash is the hash you want to assert the file has"
}
if [[ $# == 2 ]]; then
TYPE="sha256"
FILE="$1";
DESIRED_HASH="$2";
elif [[ $# == 3 ]]; then
TYPE="$1";
FILE="$2";
DESIRED_HASH="$3";
else
echo "Invalid number of arguments $#"
usage
exit 1;
fi;
DESIRED_HASH=$(echo "$DESIRED_HASH" | awk '{print(tolower($1))}')
if [ ! -f "$FILE" ]; then
echo "File '$FILE' not found"
exit 1;
fi;
case "$TYPE" in
"md5" )
echo "MD5 is insecure"
echo "A bad person can fake the hash if they want too"
echo "Do *NOT* rely on the validity of this hash for security"
;&
"sha256" | "sha512" | "sha1" )
HASH=$(openssl dgst -r -$TYPE $FILE | sed -r 's/(\w+).*/\1/')
if [[ "$HASH" == "$DESIRED_HASH" ]]; then
echo "OK $HASH";
exit 0;
else
echo "INVALID $HASH";
exit 2;
fi;
;;
"*" )
echo "Unknown hash $TYPE"
;;
esac;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment