我有一个JavaScript函数可以创建基于时间的一次性密码(TOTP)。 现在我必须使用PHP在服务器上创建相同的TOTP。 我在PHP中编写了与我的javascript函数相同的逻辑。 为了方便起见,我创建了一个JavaScript小提琴和一个PHP小提琴。所以你可以比较代码并查看输出。HMAC Javascript函数的结果不如PHP
的JavaScript版本:(小提琴:https://jsfiddle.net/rrfk4ey9/1/)
var TOTP = function() {
var dec2hex = function(s) {
return (s < 15.5 ? "0" : "") + Math.round(s).toString(16);
};
var hex2dec = function(s) {
return parseInt(s, 16);
};
var leftpad = function(s, l, p) {
if(l + 1 >= s.length) {
s = Array(l + 1 - s.length).join(p) + s;
}
return s;
};
this.getOTP = function(secret) {
try {
var epoch = Math.round(new Date().getTime()/1000.0);
// For testing, we take a fixed time. (same as in PHP version).
var time = "0000000002f3e3c9";//leftpad(dec2hex(Math.floor(epoch/30)), 16, "0");
document.getElementById("key").innerHTML = secret;
document.getElementById("time").innerHTML = time;
var hmacObj = new jsSHA(time, "HEX");
var hmac = hmacObj.getHMAC(secret, "TEXT", "SHA-1", "HEX");
document.getElementById("hmac-out").innerHTML = hmac;
var offset = hex2dec(hmac.substring(hmac.length - 1));
var otp = (hex2dec(hmac.substr(offset * 2, 8)) & hex2dec("7fffffff")) + "";
otp = (otp).substr(otp.length - 6, 6);
} catch (error) {
\t alert("Error: " + error);
throw error;
}
return otp;
};
};
var totpObj = new TOTP();
document.getElementById("result").innerHTML = totpObj.getOTP("someSecret");
output {
font-family: monospace;
white-space: pre;
}
#result {
color: orange;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsSHA/1.6.0/sha.js"></script>
<body>
<aside>This snippet uses external library <b>jsSHA</b> version <b>1.6.0</b></aside>
<hr />
<output>
<div>Key: <b id="key"></b></div>
<div>Time: <b id="time"></b></div>
<div>HMAC: <b id="hmac-out"></b></div>
<div>code: <b id="result"></b></div>
</output>
</body>
PHP版本:(http://ideone.com/s0Bwqu)
<?php
function leftPad($in, $len, $str) {
return str_pad($in, $len, $str, STR_PAD_LEFT);
}
$key = "someSecret";
$epoch = time();
// For testing, we take a fixed time. (same as in JS version).
$time = "0000000002f3e3c9";//leftPad(dechex(floor($epoch/30)), 16, "0");
echo "Key: " . $key . "\n";
echo "Time: " . $time . "\n";
$hmac = hash_hmac("sha1", $time, $key, false);
echo "HMAC: " . $hmac . "\n";
$offset = hexdec(substr($hmac, strlen($hmac) - 1));
$otp = (hexdec(substr($hmac, $offset * 2, 8)) & hexdec("7fffffff")) . "";
$otp = substr($otp, strlen($otp) - 6, 6);
echo "Code: " . $otp . "\n";
?>
这产生了:
Key: someSecret
Time: 0000000002f3e3c9
HMAC: 5dcab54740bdca71e706c7e38a5c59fec3cb9c1a
Code: 094428
注意,在两个版本(JS和PHP)的time
和key
是相同的。 HMAC
不同,所以在我的理解这里开始的问题。 JavaScript版本是我首先创建的版本,并且经过验证可以正常工作。
我很确定这个问题是由jsSHA库的行为引起的。 所以我把一些事情的角度:
- jsSHA图书馆HEX格式需要
time
。同样在PHP中,当放入hash_hmac
函数时,时间是十六进制格式。 secret
(key
)以TEXT格式放入jsSHA。也在PHP中。
实际上,重点是在PHP中获得与javascript中的jsSHA库相同的结果。 我确定我错过了一些东西。我一直在尝试,甚至谷歌也不知道答案。
请直接在您的问题中发布代码,而不是通过第三方服务。 – Narf