Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to check a file's shasum

How to check file integrity with shasum


For verifying the integrity (but not authenticity of data, i.e., who authored it or the origin of the file) of a file, it is necessary to run a checksum function on the file which will output a value and compare it to a previously stored checksum value; if both values match, we can be relatively confident that the file hasn't been tampered with or altered.

You might be asked to verify a file's sha1sum or sha2sum–-all this means is calculating and verifying the cryptographic sha1 or sha2 hash value or digest included in the file.

Various commands and methods for verifying shasum 1 or 2:


Organic:
In terminal run:

For sha2:
shasum -a 256 filename/path

For sha1:
shasum -a 1 filename/path

Use your eyeballs and compare by sight the expected hash and the computed hash in the terminal. Eye strain might ensue.

Artisanal & organic:
Run the above commands. Copy the resulting shasum with Ctrl + C. In browser or file use Ctrl + F with your copied shasum; if you find a match, congrats your file is fine! If no match, your file might have been altered or tampered with.

Inorganic, man-made:
Use shasum check command. Runs diff and prints results in terminal.

In terminal run:
echo 'your_expected_shasum_here_followed_by_a_space *name_of_file_to_check_after_asterisk' | shasum -c

References:


notepad2 blog

Raspberry Pi Forums

@Onyishi
Copy link

Onyishi commented May 13, 2019

gud

@ashafq
Copy link

ashafq commented Jun 3, 2020

+1 for inorganic method.

@gregalia
Copy link

After reading your example I can see that this is technically in the man page but I definitely didn't see it beforehand. Much appreciated!

@the-vampiire
Copy link

couldnt get this to work unless the target file was in the CWD. wrote this function instead. just add to your .[zsh|bash]rc file

usage

# no args prints usage format
checksum
# checksum <target file path> <target sum> [bit length, default 256]

checksum ~/Downloads/file-to-check[.tar.gz] <checksum to check against>
# checksum match, 0 return code (for scripting)
# checksum mismatch, 1 return code (for scripting)

function

checksum () {
  if [[ -z "$1" ]]
  then
    echo "checksum <target file path> <target sum> [bit length, default 256]"
    return 1
  fi
	
  target_file="$1"
  target_sum="$2"
  bit_length="${3:-256}"
	
  computed_sum=`openssl "sha$bit_length" "$target_file" | cut -d' ' -f2`
	
  if [[ "$computed_sum" == "$target_sum" ]]
  then
    echo "checksum match"
    return 0
  else
    echo "checksum mismatch"
    return 1
  fi
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment