How do I perform SHA-2 family hashing in my PHP application?
Posted by admin at February 7th, 2007
How do I perform SHA-2 family hashing in my PHP application?
Answer
Option 1: Upgrade to PHP >= 5.1.2. You can use hash() to generate a hash value, hash_algos() will return an array of supported hashing algorithms. See:Upgrade to PHP >= 5.1.2. You can use hash() to generate a hash value, hash_algos() will return an array of supported hashing algorithms. See:
Example PHP5 Code
$phrase = “Hello World”; $sha1a = base64_encode(sha1($phrase)); $sha1b = hash(’sha1′,$phrase); $sha256= hash(’sha256′,$phrase);$sha384= hash(’sha384′,$phrase);$sha512= hash(’sha512′,$phrase); echo (“SHA1..:” . $sha1a . “\n”); echo (“SHA1..:” . $sha1b . “\n”); echo (“SHA256:” . $sha256 . “\n”);echo (“SHA384:” . $sha384 . “\n”);echo (“SHA512:” . $sha512 . “\n”);
Option 1: Download and install the mhash and php-mhash RPMs on your Fedora, RedHat Enterprise Linux, or Centos machine. You can visit http://phprpms.sourceforge.net/mhash to determine the correct RPMs to grab and install.
rpm -ivh http://…/mhash-x.x.x-x.rpm
rpm -ivh http://…/php-mhash-x.x.x-x.rpm
…or grab and install the source code from http://mhash.sourceforge.net/.
Example PHP4 Code
$phrase = “Hello World”; $sha1a = base64_encode(sha1($phrase)); $sha1b = base64_encode(bin2hex(mhash(MHASH_SHA1,$phrase))); $sha256= base64_encode(bin2hex(mhash(MHASH_SHA256,$phrase)));$sha384= base64_encode(bin2hex(mhash(MHASH_SHA384,$phrase)));$sha512= base64_encode(bin2hex(mhash(MHASH_SHA512,$phrase)));echo (“SHA1..:” . $sha1a . “\n”); echo (“SHA1..:” . $sha1b . “\n”); echo (“SHA256:” . $sha256 . “\n“);echo (“SHA384:” . $sha384 . “\n“);echo (“SHA512:” . $sha512 . “\n”);
Code sample originally post on the PHP sha1 Manual page by Dan Casey
Background
SHA-1 was compromised by a research team in China and it’s use has been discontinued by the U.S Government in favor of the SHA-2 family of hashing algorithms.
http://www.schneier.com/blog/archives/2005/02/sha1_broken.html
Mhash is a free library which provides a uniform interface to a large number of hash algorithms including, SHA224, SHA384, and SHA512.
Links
- mhash Homepage
- mhash library man page - This page includes an example c program that demonstrates the use of the library
- PHP RPMs: php-mhash
- PHP sha1 Manual Page -
- PHP5 hash functions -
- CSRC Cryptographic Toolkit - Information about the discontinued use of SHA-1.