php hash pbkdf2,hash_pbkdf2

[#4]

Binod Kumar Luitel [2013-10-17 22:25:03]

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

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 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;

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值