php hash pbkdf2,PHP: hash_pbkdf2 - Manual

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;

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值