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
* 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")) {
functionhash_pbkdf2($algorithm,$password,$salt,$count,$key_length,$raw_output=false) {
classpbkdf2{
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 functioninit($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 functionhash()
{$this->algorithm=strtolower($this->algorithm);
if(!in_array($this->algorithm,hash_algos(),true))
throw newException('PBKDF2 ERROR: Invalid hash algorithm.');
if($this->count<=0||$this->key_length<=0)
throw newException('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 iterationsfor ($j=1;$jcount;$j++) {$xorsum^= ($last=hash_hmac($this->algorithm,$last,$this->password,true));
}$this->output.=$xorsum;
if($this->raw_output)
returnsubstr($this->output,0,$this->key_length);
else
returnbin2hex(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= newpbkdf2($data);
return$pbkdf2->hash();
} catch (Exception $e) {
throw$e;
}
}
}