ConFoo: Call for paper is now Open

hash_pbkdf2

(PHP 5 >= 5.5.0)

hash_pbkdf2Generate a PBKDF2 key derivation of a supplied password

Açıklama

string hash_pbkdf2 ( string $algo , string $password , string $salt , int $iterations [, int $length = 0 [, bool $raw_output = false ]] )

Değiştirgeler

algo

Name of selected hashing algorithm (i.e. md5, sha256, haval160,4, etc..) See hash_algos() for a list of supported algorithms.

password

The password to use for the derivation.

salt

The salt to use for the derivation. This value should be generated randomly.

iterations

The number of internal iterations to perform for the derivation.

length

The length of the output string. If raw_output is TRUE this corresponds to the byte-length of the derived key, if raw_output is FALSE this corresponds to twice the byte-length of the derived key (as every byte of the key is returned as two hexits).

If 0 is passed, the entire output of the supplied algorithm is used.

raw_output

When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.

Dönen Değerler

Returns a string containing the derived key as lowercase hexits unless raw_output is set to TRUE in which case the raw binary representation of the derived key is returned.

Hatalar/İstisnalar

An E_WARNING will be raised if the algorithm is unknown, the iterations parameter is less than or equal to 0, the length is less than 0 or the salt is too long (greater than INT_MAX - 4).

Örnekler

Örnek 1 hash_pbkdf2() example, basic usage

<?php
$password 
"password";
$iterations 1000;

// Generate a random IV using mcrypt_create_iv(),
// openssl_random_pseudo_bytes() or another suitable source of randomness
$salt mcrypt_create_iv(16MCRYPT_DEV_URANDOM);

$hash hash_pbkdf2("sha256"$password$salt$iterations20);
echo 
$hash;
?>

Yukarıdaki örnek şuna benzer bir çıktı üretir:

120fb6cffcf8b32c43e7

Notlar

Dikkat

The PBKDF2 method can be used for hashing passwords for storage. However, it should be noted that password_hash() or crypt() with CRYPT_BLOWFISH are better suited for password storage.

Ayrıca Bakınız

  • crypt() - Tek yönlü dizge şifrelemesi yapar
  • password_hash() - Creates a password hash
  • hash() - Bir ileti özeti üretir
  • hash_algos() - Kayıtlı özetleme algoritmalarının bir listesini döndürür
  • hash_init() - Ardışık özetleme bağlamını ilklendirir
  • hash_hmac() - HMAC yöntemini kullanarak bir anahtarlı ileti özeti üretir
  • hash_hmac_file() - Bir dosyanın içeriğinden HMAC yöntemini kullanarak bir anahtarlı ileti özeti üretir

add a note add a note

User Contributed Notes 4 notes

up
7
Anonymous
1 year ago
Sadly this function was added in PHP 5.5 but many webservers just provide PHP 5.3. But there exists a pure PHP implementation (found here: https://defuse.ca/php-pbkdf2.htm).
I took this implementation, put it into a class with comments for PHPDoc and added a switch so that the native PHP function is used if available.

Feel free to use it!
http://pastebin.com/f5PDq735
(Posted on pastebin.com since the text would have been too long)
up
3
does dot not at matter dot org
10 months ago
this snippet was posted over a year ago on a dutch PHP community: (reference/source: http://www.phphulp.nl/php/script/beveiliging/pbkdf2-een-veilige-manier-om-wachtwoorden-op-te-slaan/1956/pbkdf2php/1757/)

<?php

/**
* @author Chris Horeweg
* @package Security_Tools
*/

function pbkdf2($password, $salt, $algorithm = 'sha512', $count = 20000, $key_length = 128, $raw_output = false)
{
    if(!
in_array($algorithm, hash_algos(), true)) {
        exit(
'pbkdf2: Hash algoritme is niet geinstalleerd op het systeem.');
    }
   
    if(
$count <= 0 || $key_length <= 0) {
       
$count = 20000;
       
$key_length = 128;
    }

   
$hash_length = strlen(hash($algorithm, "", true));
   
$block_count = ceil($key_length / $hash_length);

   
$output = "";
    for(
$i = 1; $i <= $block_count; $i++) {
       
$last = $salt . pack("N", $i);
       
$last = $xorsum = hash_hmac($algorithm, $last, $password, true);
        for (
$j = 1; $j < $count; $j++) {
           
$xorsum ^= ($last = hash_hmac($algorithm, $last, $password, true));
        }
       
$output .= $xorsum;
    }

    if(
$raw_output) {
        return
substr($output, 0, $key_length);
    }
    else {
        return
base64_encode(substr($output, 0, $key_length));
    }
}
up
1
Binod Kumar Luitel
10 months ago
People who wants pure PHP implementation of the function, i.e. who don't have PHP 5.5 installed within their server, can use the following implementation. Nothing has been modified so far as from reference https://defuse.ca/php-pbkdf2.htm but the OOP lovers might like this.
For more information about PBKDF2 see: http://en.wikipedia.org/wiki/PBKDF2

<?php
/**
* PBKDF2 key derivation function as defined by RSA's PKCS #5: https://www.ietf.org/rfc/rfc2898.txt
* $algorithm - The hash algorithm to use. Recommended: SHA256
* $password - The password.
* $salt - A salt that is unique to the password.
* $count - Iteration count. Higher is better, but slower. Recommended: At least 1000.
* $key_length - The length of the derived key in bytes.
* $raw_output - If true, the key is returned in raw binary format. Hex encoded otherwise.
* Returns: A $key_length-byte key derived from the password and salt.
*/
if (!function_exists("hash_pbkdf2")) {
    function
hash_pbkdf2($algorithm, $password, $salt, $count, $key_length, $raw_output = false) {

        class
pbkdf2 {
            public
$algorithm;
            public
$password;
            public
$salt;
            public
$count;
            public
$key_length;
            public
$raw_output;

            private
$hash_length;
            private
$output         = "";

            public function
__construct($data = null)
            {
                if (
$data != null) {
                   
$this->init($data);
                }
            }

            public function
init($data)
            {
               
$this->algorithm  = $data["algorithm"];
               
$this->password   = $data["password"];
               
$this->salt       = $data["salt"];
               
$this->count      = $data["count"];
               
$this->key_length = $data["key_length"];
               
$this->raw_output = $data["raw_output"];
            }

            public function
hash()
            {
               
$this->algorithm = strtolower($this->algorithm);
                if(!
in_array($this->algorithm, hash_algos(), true))
                    throw new
Exception('PBKDF2 ERROR: Invalid hash algorithm.');

                if(
$this->count <= 0 || $this->key_length <= 0)
                    throw new
Exception('PBKDF2 ERROR: Invalid parameters.');

               
$this->hash_length = strlen(hash($this->algorithm, "", true));
               
$block_count = ceil($this->key_length / $this->hash_length);
                for (
$i = 1; $i <= $block_count; $i++) {
                   
// $i encoded as 4 bytes, big endian.
                   
$last = $this->salt . pack("N", $i);
                   
// first iteration
                   
$last = $xorsum = hash_hmac($this->algorithm, $last, $this->password, true);
                   
// perform the other $this->count - 1 iterations
                   
for ($j = 1; $j < $this->count; $j++) {
                       
$xorsum ^= ($last = hash_hmac($this->algorithm, $last, $this->password, true));
                    }
                   
$this->output .= $xorsum;
                    if(
$this->raw_output)
                        return
substr($this->output, 0, $this->key_length);
                    else
                        return
bin2hex(substr($this->output, 0, $this->key_length));
                }
            }
        }

       
$data = array('algorithm' => $algorithm, 'password' => $password, 'salt' => $salt, 'count' => $count, 'key_length' => $key_length, 'raw_output' => $raw_output);
        try {
           
$pbkdf2 = new pbkdf2($data);
            return
$pbkdf2->hash();
        } catch (
Exception $e) {
            throw
$e;
        }
    }
}
up
-1
Peter
9 months ago
See also https://github.com/rchouinard/hash_pbkdf2-compat for a compatibility function
To Top