2013-09-30 44 views
0

我一直在努力學習如何HOTP(基於計數器的HOTP代碼Android Google Authenication)。 我發現了這個代碼,它有能力在服務器和客戶端(手機APP)之間共享密鑰。PHP一次性密碼?

<?php 
function oath_hotp($key,$counter) { 

    // Convert to padded binary string 
    $data = pack ('C*', $counter); 
    $data = str_pad($data,8,chr(0),STR_PAD_LEFT); 

    // HMAC 
    return hash_hmac('sha1',$data,$key); 
} 

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<10;$i++){ 
    print $i."\t".($a=oath_hotp("mysecretvalue",$i)); 
    print "\t".oath_truncate($a)."\n"; 
} 
?> 

這個輸出如下 -

Compare results with: http://tools.ietf.org/html/draft-mraihi-oath-hmac-otp-04 
Count     Hash      Pin 
0 f25e6c58cc7a2dfedae7eb48a1bff891aa0c0189 472801 
1 b52adf13022511f08740566fb44c0b267d7c2604 983856 
2 3c693c66f6e04178943dc9badc0dd41318dbc7f7 981065 
3 1225cf508043a59fe2e39e335ff5f3e5795131ba 683381 
4 21a9756e8de58df5e10c9292e0147823ba03539b 675192 
5 7339c3496cebdaf3a035eaba888f61d8c19d8cf9 575624 
6 c7c03ce2174f144a329664d35cc90e70a3686596 406934 
7 431a75f26b9950f0206911667f3a2ed7fdfc43c7 172241 
8 81e05a2d9e060a25f515b1e53170dce4daad5cc7 818865 
9 ff2068918dc53db45a0c338d8de99419cf3cb571 723917 

現在我的問題是,我不能管理上面的代碼在客戶端和服務器端正常工作。我使用了相同的密鑰print $i."\t".($a=oath_hotp("**mysecretvalue**",$i));輸出完全不同。請注意,這是基於計數器,這意味着沒有時間同步,如TOTP

我已經加倍檢查我的android手機和服務器端的密碼。什麼可能是錯的?請注意,我並不熟悉PHP安全性。因此,如果上述內容不適用於Google身份驗證,請爲我提供一個開始的地方。

謝謝

回答

1

谷歌身份驗證需要輸入密如RFC 3548 base32(https://code.google.com/p/google-authenticator/),並且您正在使用一個祕密,是ASCII。

你所擁有的php代碼是可以的(你可以通過在「123456789」的ASCII碼中傳遞一個祕密,並根據http://www.ietf.org/rfc/rfc4226.txt的附錄D檢查它)來看到。

您需要做的是將您輸入到Google身份驗證器的密鑰從base32轉換爲ASCII。

您可以使用從GitHub https://github.com/devicenull/PHP-Google-Authenticator/blob/master/base32.php這個工具類base32爲你做轉換,那麼就加入:

include_once "base32.php"; 
$keyToTest = "mysecretvalue"; 

$b = new Base32(Base32::csRFC3548); 
$keyToTest = $b->toString($keyToTest); 

for($i=0;$i<10;$i++){ 
    print $i."\t".($a=oath_hotp($keyToTest,$i)); 
    print "\t".oath_truncate($a)."\n"; 
}