1. Overview

The SHA-256 standard is used in document integrity checks. It’s preferred over the SHA-1 standard, since the latter has been shown to produce the same hash for different documents.

In this tutorial, we’ll look at SHA-256 hash generation using the sha256sum command.

2. Generate SHA-256 Hashes for Files

We can use the sha256sum command in two modes; binary and text (the default). On Linux, both modes generate the same SHA-256 hash, and so the default mode is used throughout this tutorial. 

Let’s create a text file with some simple text in it, and use that to demonstrate how the command works:

echo "https://baeldung.com" > data.txt

Let’s now create the sha-256 hash of the above file:

sha256sum data.txt 
86c5ceb27e1bf441130299c0209e5f35b88089f62c06b2b09d65772274f12057 data.txt

This generated output consists of:

  • the hash sum – the first 65 characters
  • space(s)
  • an asterisk (only in binary mode)
  • the path to the file or just the name of the file

We can also generate the hash for a file in a directory:

sha256sum /path/to/data.txt > checksum
cat checksum 
86c5ceb27e1bf441130299c0209e5f35b88089f62c06b2b09d65772274f12057 /path/to/data.txt​

3. Verify File Integrity

Let’s use the hash stored in the checksum file to verify the integrity of the data.txt file that we’ve hashed:

sha256sum --check checksum
data.txt: OK

Next, let’s modify the information contained in data.txt to simulate a failed test. We’ll use the sed command to replace “https” with “http”:

sed -i 's/https/http/' data.txt

Lastly, we check the file’s integrity again:

sha256sum --check checksum 
data.txt: FAILED
sha256sum: WARNING: 1 computed checksum did NOT match

3.1. Dealing With Multiple Files

Let’s add another entry in the checksum file for another file. We’ll do this by adding a simple text to a new file, generating the digest for that new file, and appending it to the checksum file:

echo "https://google.com" > data2.txt 
sha256sum data2.txt >> checksum

If now we do integrity tests for all the entries in the checksum file, it processes each one of the entries, telling us which files fail the test, and which pass:

sha256sum --check checksum 
data.txt: FAILED 
data2.txt: OK 
sha256sum: WARNING: 1 computed checksum did NOT match

4. Conclusion

In this article, we saw how to use the sha256sum command to check the integrity of files by generating an SHA-256 hash digest. After that, we stored the output in a file and used it to check for file integrity.

Finally, we saw how to test the integrity of multiple files.

Authors Bottom

If you have a few years of experience in the Linux ecosystem, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

Comments are closed on this article!