Open In App

PHP md5(), sha1(), hash() Functions

PHP is a server-side scripting language which implies that PHP is responsible for all the back-end functionalities required by the website. The authentication system is one of the most important parts of a website and it is one of the most commonplace where developers commit mistakes leaving out vulnerabilities for others to exploit. One example could be storing and using user passwords in its true form, which may lead to a situation where an unauthorized person gets the access to the database and the whole system is compromised.

This situation can be easily prevented using password hashing. Password Hashing is a method which takes the user password( a variable-length sequence of characters) and encrypts it to a fixed-length password containing random characters from a larger set. PHP has a few functions that can be used to achieve the same.



md5() Function

Syntax:



string md5 ($string, $getRawOutput)

Parameters: The function an take up to a maximum of two parameters as follows:

Return Type: This function returns the hashed string (either in lowercase hex character sequence of length 32 or raw binary form of length 16).

sha1() Function

Syntax:

string sha1($string, $getRawOutput)

Parameters: The function an take up to a maximum of two parameters as follows:

Return Type: This function returns the hashed string (either in lowercase hex character sequence of length 40 or raw binary form of length 20).

hash() Function

Syntax:

string hash($algo, $string, $getRawOutput)

Parameters: The function an take up to a maximum of three parameters as follows:

Return Type: This function returns the hashed string (either in lowercase hex character sequence or raw binary form).

Below program illustrates the working of md5(), sha1() and hash() in PHP:




<?php
  
// PHP code to illustrate the working 
// of md5(), sha1() and hash()
  
$str = 'Password';
$salt = 'Username20Jun96';
echo sprintf("The md5 hashed password of %s is: %s\n"
                                $str, md5($str.$salt));
echo sprintf("The sha1 hashed password of %s is: %s\n",
                                $str, sha1($str.$salt));
echo sprintf("The gost hashed password of %s is: %s\n"
                        $str, hash('gost', $str.$salt));
                          
?>

Output:

The md5  hashed password of Password is: 
a59a0e0fcfab450008571e94a5549225
The sha1 hashed password of Password is: 
a69652ddbc8401ae93b5d2f0390d98abd94fc2f4
The gost hashed password of Password is:
5376160a0d848c327949364b96fb9fd6e13a9b20c58fbab50f418ea9eea3b67f

Important points to note:

Reference:


Article Tags :