Categories
PHP

Checksum Strings and Files with MD5 and SHA1

How to generate a checksum (hash signature) to encrypt or verify if two copies of a string or file are identical in all respects.

Using md5() or sha1() with strings (or files) generates a checksum. It can be easily determined whether a string (or file) matches the checksum; however, it is not (easily) possible to re-create the original string from the checksum.

Encrypting String

The md5() and sha1() functions accept a string input and produce a fixed-length signature called checksum that can be used for comparison or encryption.

Example: md5()

The MD5 (message-digest 5) is a mathematical algorithm, which takes a string (or file), and performs a one-way operation on it to come up with a 32-digit hexadecimal number, which is called the MD5 hash:

<?php
 $str = 'BrainBell.com';
 echo md5( $str );
 //Prints: 63b5b2fc999abfeb28ca02df96449737

Example: sha1()

The SHA1 (Secure Hash Algorithm 1) also creates a checksum or hash. The main difference between md5() and sha1() is:

  • md5() function produces a 128-bit hash
  • while the sha1() function produces a 160-bit hash
<?php
 $str = 'BrainBell.com';
 echo sha1( $str );
 //Prints: 96467b5b84be4047460cf2a7ce0b634811845f6a

Example: Checking login using md5()

<?php
 $user = $_POST['username'] ?? '';
 $pass = $_POST['password'] ?? '';
 
 //fetch username and password from database
 $md5pass = '63b5b2fc999abfeb28ca02df96449737';
 if (md5($pass) === $md5pass) 
  echo 'Login successful.';
 else
  echo 'Login failed.';

Example: Checking username and password using sha1()

<?php
 $user = $_POST['username'] ?? '';
 $pass = $_POST['password'] ?? '';
 
 //fetch username and password from database
 $sha1pass = '96467b5b84be4047460cf2a7ce0b634811845f6a';
 if (sha1($pass) === $sha1pass) 
  echo 'Login successful.';
 else
  echo 'Login failed.';

Note: Visit the following URL for secure password hashing: https://php.net/manual/faq.passwords.php.

Encrypting files

When calculating the MD5 or SHA1 hash of a file, do not call the file_get_contents() or other file functions, PHP offers md5_file() and sha1_file() functions that calculate the hashes of a file (and take care of opening and reading the file data):

Example: md5_file()

<?php
 $file = 'images/logo.png';
 echo md5_file( $file );
 //f3bdbf0e7274b5b6b19b9c2fca1796b2

Example: sha1_file()

<?php
 $file = 'images/logo.png';
 echo sha1_file( $file );
 //a964c50eaa057722fc444d59fb24f34fff9ce8bf

Working with Strings: