📅  最后修改于: 2023-12-03 14:47:25.960000             🧑  作者: Mango
SHA-256 is a Secure Hash Algorithm used for encryption and cryptographic applications. It generates a fixed-length hash value known as a message digest.
In PHP, the SHA-256 algorithm is available through the hash()
function. Here is an example of how to use it:
$string = "Hello World";
$hash = hash('sha256', $string);
echo $hash;
This will output the SHA-256 hash value for the Hello World
string.
To verify if two SHA-256 values match, you can compare them using the hash_equals()
function:
$string = "Hello World";
$hash1 = hash('sha256', $string);
$hash2 = hash('sha256', $string);
if (hash_equals($hash1, $hash2)) {
echo "The hashes match";
} else {
echo "The hashes do not match";
}
It is important to note that SHA-256 is a one-way hash function - meaning it cannot be reversed to retrieve the original data. It is used primarily for verifying data integrity and password encryption.
In addition to the hash()
function, PHP also provides access to the HMAC-SHA256 message authentication code (MAC) through the hash_hmac()
function. This allows you to generate a MAC value using a secret key along with the message data.
$message = "Hello World";
$secret_key = "my_secret_key";
$mac = hash_hmac('sha256', $message, $secret_key);
echo $mac;
This will output the HMAC-SHA256 value for the Hello World
message using the my_secret_key
secret key.
Overall, SHA-256 in PHP is a powerful tool for securing data and ensuring its integrity. By understanding how to use it properly, developers can help make their applications more secure.