Skip to content

Instantly share code, notes, and snippets.

@jmhobbs
Created November 7, 2011 22:37
Show Gist options
  • Save jmhobbs/1346439 to your computer and use it in GitHub Desktop.
Save jmhobbs/1346439 to your computer and use it in GitHub Desktop.
Using PBKDF2 with Kohana 3 Auth Module
<?php
abstract class Auth extends Kohana_Auth {
public function hash ( $str ) {
if ( ! $this->_config['hash_key'] )
throw new Kohana_Exception( 'A valid hash key must be set in your auth config.' );
if ( 'pbkdf2' == $this->_config['hash_method'] ) {
return base64_encode( self::pbkdf2(
$str,
$this->_config['hash_key'],
Arr::get( $this->_config['pbkdf2'], 'rounds', 1000 ),
Arr::get( $this->_config['pbkdf2'], 'length', 45 ),
Arr::get( $this->_config['pbkdf2'], 'method', 'sha256' )
) );
}
else {
return parent::hash( $str );
}
}
/** PBKDF2 Implementation (described in RFC 2898)
*
* @param string p password
* @param string s salt
* @param int c iteration count (use 1000 or higher)
* @param int kl derived key length
* @param string a hash algorithm
*
* @return string derived key
*
* @url http://www.itnewb.com/tutorial/Encrypting-Passwords-with-PHP-for-Storage-Using-the-RSA-PBKDF2-StandardL
*/
public static function pbkdf2 ( $p, $s, $c, $kl, $a = 'sha256' ) {
$hl = strlen(hash($a, null, true)); # Hash length
$kb = ceil($kl / $hl); # Key blocks to compute
$dk = ''; # Derived key
# Create key
for ( $block = 1; $block <= $kb; $block ++ ) {
# Initial hash for this block
$ib = $b = hash_hmac($a, $s . pack('N', $block), $p, true);
# Perform block iterations
for ( $i = 1; $i < $c; $i ++ )
# XOR each iterate
$ib ^= ($b = hash_hmac($a, $b, $p, true));
$dk .= $ib; # Append iterated block
}
# Return derived key of correct length
return substr($dk, 0, $kl);
}
}
<?php defined('SYSPATH') or die('No direct access allowed.');
return array(
'driver' => 'orm',
'hash_method' => 'pbkdf2',
'hash_key' => 'zomg',
'lifetime' => 1209600,
'session_key' => 'auth_user',
'pbkdf2' => array(
'method' => 'sha256',
'rounds' => 1000,
'length' => 45,
)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment