Last Updated : 29 Jan, 2024
Summarize
Comments
Improve
Hashing Functions play a crucial role in securing sensitive data by converting it into a fixed-size string of characters, often a hash value or checksum. PHP provides several built-in hashing functions for various purposes, such as password hashing, data integrity verification, and more.
The Hashing technique implements the hash Function to transform the data into a fixed-length string of characters, which represents the hash value. The hash function ensures the data will be encrypted in its true form, without manipulating its original form. Thus, it helps in authenticating and authorizing while the transformation of data takes place. It is a single-way transformation technique, which signifies that it is computationally infeasible to reverse the process & retrieve the original data from the hash.
There are several in-built hash algorithms, such as md5 (), sha1 (), etc, which are most commonly used for the encryption of information, are described below.
Table of Content
- Hashing with md5() Function
- Hashing with sha1() Function
- Password Hashing with password_hash() Function
- Hashing Data with hash() Function
Hashing with md5() Function
The md5() function generates a 32-character hexadecimal number representing the hash value of a given string.
Example:
PHP
<?php
$data
=
"Hello, World!"
;
$hash
= md5(
$data
);
echo
"Original Data: $data\n"
;
echo
"MD5 Hash: $hash\n"
;
?>
Output
Original Data: Hello, World!MD5 Hash: 65a8e27d8879283831b664bd8b7f0ad4
Hashing with sha1() Function
The sha1() function produces a 40-character hexadecimal number representing the SHA-1 hash value of a string.
Example:
PHP
<?php
$data
=
"Hello, World!"
;
$hash
= sha1(
$data
);
echo
"Original Data: $data\n"
;
echo
"SHA-1 Hash: $hash\n"
;
?>
Output
Original Data: Hello, World!SHA-1 Hash: 0a0a9f2a6772942557ab5355d76af442f8f65e01
Password Hashing with password_hash() Function
The password_hash() function is specifically designed for secure password hashing using bcrypt, which is a strong, adaptive hashing algorithm.
Example:
PHP
<?php
$password
=
"mySecurePassword"
;
$hashedPassword
= password_hash(
$password
, PASSWORD_BCRYPT);
echo
"Original Password: $password\n"
;
echo
"Hashed Password: $hashedPassword\n"
;
?>
Output
Original Password: mySecurePasswordHashed Password: $2y$10$fMakDUqb6p7sEGzYRXaS0ecO73SB3/GTR.r7QJjMbbdtQBVvt.HQm
Hashing Data with hash() Function
The hash() function supports a variety of algorithms, including SHA-256 and SHA-512. It provides more flexibility but requires manual management of salt and options.
Example:
PHP
<?php
$data
=
"Hello, World!"
;
$hashedData
= hash(
'sha256'
,
$data
);
echo
"Original Data: $data\n"
;
echo
"SHA-256 Hash: $hashedData\n"
;
?>
Output
Original Data: Hello, World!SHA-256 Hash: dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f