Community Documentation

Use of hash functions

Last updated February 22, 2011. Created by pwolanin on July 5, 2010.
Log in to edit this page.

Drupal 5 and Drupal 6 core use the md5() for many purposes. While a collision or attack on this hash function is still unlikely, when writing a contributed module for Drupal 5 or 6, it is still preferable to use the sha1() hash function in place of md5().

Any time you need to authenticate the content of a string or file by combining a secret key (E.g. a session ID) with the string, you should avoid using a single hash function which may be vulnerable to string-extension attacks. The preferred approach is to calculate a Hash-based Message Authentication Code (HMAC) using hash functions or relying on PHP's hash extension for PHP 5. An acceptable (but less preferred) alternative is to apply the hash function twice.

An example using PHP's hash library

  $hmac = hash_hmac('sha256', $data, $secret_key);

An example using Drupal 7's hmac function:

  $hmac = drupal_hmac_base64($data, $secret_key);

An example of double hashing is:

  $hash = sha1(sha1($secret_key . $data));

For Drupal 7 modules, md5() and sha1() should never be used, since they are considered obsolete and potentially insecure for some applications. For a normal hash function use sha-256 by calling hash('sha256', $data). Drupal 7 also presents wrapper functions to get shorter, base-64 encoded hashes to use in URLs, etc. See:

http://api.drupal.org/api/function/drupal_hash_base64/7
http://api.drupal.org/api/function/drupal_hmac_base64/7

for a full discussion of the motivation for the change for Drupal 7 see: http://drupal.org/node/723802

nobody click here