簡體   English   中英

php的hmac sha256實現與Java的不匹配

[英]php's hmac sha256 implementation mismatches java's one

我正在嘗試在php中重現用Java編寫的totp計算參考( http://tools.ietf.org/html/rfc6238附錄A)中提到的測試用例。 該參考提供了sha1,sha256和sha512算法的示例。

我發現這個由羅布天鵝(見8位例)再現精細一個測試用例(與SHA1)很好的例子。 但是,如果我將算法更改為sha256或sha512(並根據參考輸入數據也更改了種子),則得到的結果與參考的結果不同。

php的hmac哈希函數可能不同於Java的hmac哈希函數嗎?

謝謝!

*解決方案

這是我提到的Rob Swan的php實現的副本:

<?php

// Define your secret seed
// NB: this is a hexadecimal representation of the example
// ASCII string which is: 12345678901234567890
$secret_seed = "3132333435363738393031323334353637383930";

// Determine the time window as 30 seconds
$time_window = 30;

// Set the timestamp manually
$exact_time = 1111111109;

// Round the time down to the time window
$rounded_time = floor($exact_time/$time_window);

// Pack the counter into binary
$packed_time = pack("N", $rounded_time);

// Make sure the packed time is 8 characters long
$padded_packed_time = str_pad($packed_time,8, chr(0), STR_PAD_LEFT);

// Pack the secret seed into a binary string
$packed_secret_seed = pack("H*", $secret_seed);

// Generate the hash using the SHA1 algorithm
$hash = hash_hmac ('sha1', $padded_packed_time, $packed_secret_seed, true);

// NB: Note we have change the exponent in the pow function 
// from 6 to 8 to generate an 8 digit OTP not a 6 digit one 

// Extract the 8 digit number fromt the hash as per RFC 6238
$offset = ord($hash[19]) & 0xf;
$otp = (
    ((ord($hash[$offset+0]) & 0x7f) << 24 ) |
    ((ord($hash[$offset+1]) & 0xff) << 16 ) |
    ((ord($hash[$offset+2]) & 0xff) << 8 ) |
    (ord($hash[$offset+3]) & 0xff)
) % pow(10, 8);

// NB: Note that we are padding to 8 characters not 6 for this example

// Add any missing zeros to the left of the numerical output
$otp = str_pad($otp, 8, "0", STR_PAD_LEFT);

// Display the output, which should be 
echo "This should display 07081804: " . $otp;

?>

關鍵是這一行:

$offset = ord($hash[19]) & 0xf;

在使用sha1算法的假設下,此方法可以正常工作,該算法返回20個字符的字符串。

要抽象化該行並使其與任何其他算法兼容,請將此行更改為:

$offset = ord($hash[strlen($hash)-1]) & 0xf;

現在,您有了RFC 6238 totp計算的通用且有效的php版本!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM