Akamai Haole

Aloha!      Welcome!      Howdy!

Verifying a file’s SHA1 hash on OS X

I frequently have to verify a file’s SHA1 hash, to ensure that the file downloaded correctly and has not been tampered with.  While you can visually inspect the hash result to compare it to a known value, I find it very handy to have a script that does this for me, given a filename and a known valid hash.

#!/bin/bash

#
# Script to validate a SHA1 hash on a file
# Copyright (c)2011, Akamai Haole, LLC
#
# Usage: verifySHA1
#

# Executable paths
AWK=/usr/bin/awk
OPENSSL=/opt/local/bin/openssl

# Parameter sanity check
if [ "${1}x" == "x" -o "${2}x" == "x" ]; then
   echo ""
   echo "Usage: ${0} "
   echo ""
   exit
fi

# File existence sanity check
if [ ! -f "${2}" ]; then
   echo ""
   echo "ERROR: File (${2}) does not exist!"
   echo ""
   exit
fi

# Calculate SHA1 hash value and trim it
SHA1_HASH_VALUE=`${OPENSSL} sha1 ${2} | ${AWK} 'BEGIN {FS="="}; {gsub(/ /,"",$2); print $2}'`

# File information
echo ""
echo "File path: ${2}"
echo "Calculated SHA1 hash: ${SHA1_HASH_VALUE}"
echo ""

# Test with the SHA1 hash that was passed in
if [ "${SHA1_HASH_VALUE}x" != "${1}x" ]; then
   echo "Hash comparison fails!"
else
   echo "Hash comparison matches."
fi

echo ""

# End of script