Saturday, June 30, 2012

Difference Between the Hash() and Hash_File() Functions in PHP

The Hash_File() function returns the same value as if the function Hash() had been performed on the same exact piece of data.  At first, I was uncertain if Hash_File() used the filename, or even the permission settings, when defining the data to be hashed for the given algorithm.  If it did work that way, then that means the same exact files would have different HASH values when you moved or renamed them on your system.  Anyway, fortunately, it does not work that way.  Hash() and Hash_File() produce identical results for the same pieces of data.  This is also true for the relationship between the Hash_HMAC() and Hash_HMAC_File() functions: the same pieces of data, the same keys, produce identical results.  It was a wise, design principle.

Some sample code to demonstrate this principle :

<?php

            // Author: holdoffhunger@gmail.com

        // Preset Data
        // ------------------------------------------------
       
    $test_data = "php-hashing";
    $test_file = "test.txt";
    $test_file_read = file_get_contents($test_file);
   
        // Hash Data
        // ------------------------------------------------
   
    $test_data_hash = hash("md2", $test_data, FALSE);
    $test_file_hash = hash_file("md2", $test_file, FALSE);
   
        // Print Hash Results
        // ------------------------------------------------
   
    print("Data Hash ($test_data): $test_data_hash<br><br>");
    print("File Hash ($test_file_read): $test_file_hash");
   
?>

    Expected Results
    ..................................
   
Data Hash (php-hashing): 457d84e1d69e519a7b73348db21477d3

File Hash (php-hashing): 457d84e1d69e519a7b73348db21477d3

Official Function Page: http://www.php.net/manual/en/function.hash-file.php

// Note: All code appearing on the PHP Revolution blog by the blog owner is released under the Hacktivismo Enhanced-Source Software License Agreement (HESSLA), unless otherwise noted.  http://www.hacktivismo.com/about/hessla.php

No comments:

Post a Comment