Using hash algorithms in PHPPosted in PHP -
PHP has a number of hashing algorithms available for creating hash values of files and strings. A hash is a non-reversible fixed length string which has a number of applications, such as storing a password in a database in a way that can not be read (in this example when someone logs in the hash is applied to their submitted plain text password and compared with the hashed value in the database). This post looks at how to show the available hashes in PHP and how to use the hash() function to generate a hash value.
To get the list of all the available hash algorithms in PHP use the hash_algos() function, for example:
This will give you a zero based index array containing all the hash algorithms available. The output from the command above is shown below:
Array (  => md4  => md5  => sha1  => sha256  => sha384  => sha512  => ripemd128  => ripemd160  => whirlpool  => tiger128,3  => tiger160,3  => tiger192,3  => tiger128,4  => tiger160,4  => tiger192,4  => snefru  => gost  => adler32  => crc32  => crc32b  => haval128,3  => haval160,3  => haval192,3  => haval224,3  => haval256,3  => haval128,4  => haval160,4  => haval192,4  => haval224,4  => haval256,4  => haval128,5  => haval160,5  => haval192,5  => haval224,5  => haval256,5 )
As you can see there are a lot. The most commonly used ones are MD5 and SHA1 and these have their own functions as well as the generic hash and hash_file functions.
To calculate the hash on a string using md5, for example, you can do this:
echo hash("md5", "this is my string to be hashed"); OR echo md5("this is my string to be hashed");
Both of the above examples will output the same hash which is as follows:
Picking one of the other hash algorithms at random, we could use e.g. haval256,3 like so:
echo hash("haval256,3", "this is my string to be hashed"); // outputs 2e5b5a9abc71b4ef8f24bba766b0de18e7799380349909cc34f74570b45fce76
You can also create a hash of a file using the hash_file, md5_file and sha1_file functions, e.g.:
$hash = hash_file("md5", "/path/to/file"); $hash = md5_file("/path/to/file"); $hash = sha1_file("/path/to/file");