Sha256 Hashes in PHP
Here’s the translation of the SHA256 Hashes example from Go to PHP:
SHA256 hashes are frequently used to compute short identities for binary or text blobs. For example, TLS/SSL certificates use SHA256 to compute a certificate’s signature. Here’s how to compute SHA256 hashes in PHP.
<?php
// PHP has built-in functions for various hash algorithms
$s = "sha256 this string";
// Here we compute the SHA256 hash
$hash = hash('sha256', $s);
echo $s . "\n";
echo $hash . "\n";
In this PHP code:
We start by defining the string we want to hash.
We use the
hash()
function, which is part of PHP’s built-in hashing library. The first argument specifies the algorithm (in this case, ‘sha256’), and the second argument is the string to be hashed.The
hash()
function returns the hash as a lowercase hexadecimal number.
Running the program computes the hash and prints it in a human-readable hex format.
$ php sha256_hashes.php
sha256 this string
1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a0678b2144d53bff
You can compute other hashes using a similar pattern. For example, to compute SHA512 hashes, you would use hash('sha512', $s)
.
Note that if you need cryptographically secure hashes, you should carefully research hash strength!
PHP also provides more advanced hashing capabilities through the hash_*
family of functions, which allow for incremental hashing of larger data sets or streams. Here’s an example:
<?php
$s = "sha256 this string";
$context = hash_init('sha256');
hash_update($context, $s);
$hash = hash_final($context);
echo $s . "\n";
echo $hash . "\n";
This approach is particularly useful when you need to hash large amounts of data or when the data is coming from a stream.