note 91031 added to function.hash-hmac
| From: | brent at thebrent dot net | Date: | Thu, 21 May 2009 15:17:56 +0000 |
| Subject: | note 91031 added to function.hash-hmac | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-155850@lists.php.net to get a copy of this message | ||
The hotp algorithms above work with counter values less than 256, but since the counter can be
larger, it's necessary to iterate through all the bytes of the counter:
<?php
function oath_hotp ($key, $counter)
{
// Counter
//the counter value can be more than one byte long, so we need to go multiple times
$cur_counter = array(0,0,0,0,0,0,0,0);
for($i=7;$i>=0;$i--)
{
$cur_counter[$i] = pack ('C*', $counter);
$counter = $counter >> 8;
}
$bin_counter = implode($cur_counter);
// Pad to 8 chars
if (strlen ($bin_counter) < 8)
{
$bin_counter = str_repeat (chr(0), 8 - strlen ($bin_counter)) . $bin_counter;
}
// HMAC
$hash = hash_hmac ('sha1', $bin_counter, $key);
return $hash;
}
function oath_truncate($hash, $length = 6)
{
// Convert to dec
foreach(str_split($hash,2) as $hex)
{
$hmac_result[]=hexdec($hex);
}
// Find offset
$offset = $hmac_result[19] & 0xf;
// Algorithm from RFC
return
(
(($hmac_result[$offset+0] & 0x7f) << 24 ) |
(($hmac_result[$offset+1] & 0xff) << 16 ) |
(($hmac_result[$offset+2] & 0xff) << 8 ) |
($hmac_result[$offset+3] & 0xff)
) % pow(10,$length);
}
print "<pre>";
print "Compare results with:";
print " http://tools.ietf.org/html/draft-mraihi-oath-hmac-otp-04\n";
print "Count\tHash\t\t\t\t\t\tPin\n";
for($i=0;$i<=1024;$i=$i+128)
{
print $i."\t".($a=oath_hotp("12345678901234567890",$i));
print "\t".oath_truncate($a)."\n";
}
?>
----
Server IP: 208.69.120.35
Probable Submitter: 67.151.136.161
----
Manual Page -- http://www.php.net/manual/en/function.hash-hmac.php
Edit -- https://master.php.net/note/edit/91031
Del: integrated -- https://master.php.net/note/delete/91031/integrated
Del: useless -- https://master.php.net/note/delete/91031/useless
Del: bad code -- https://master.php.net/note/delete/91031/bad+code
Del: spam -- https://master.php.net/note/delete/91031/spam
Del: non-english -- https://master.php.net/note/delete/91031/non-english
Del: in docs -- https://master.php.net/note/delete/91031/in+docs
Del: other reasons-- https://master.php.net/note/delete/91031
Reject -- https://master.php.net/note/reject/91031
Search -- https://master.php.net/manage/user-notes.php