【发布时间】:2009-11-25 10:20:51
【问题描述】:
来自http://fullthrottledevelopment.com/php-nonce-library#download,有一个PHP nonce 库,但是有一些我不知道了解的东西。第一个是它提醒我们为FT_NONCE_UNIQUE_KEY 设置一个值,但它从未在其任何函数中使用它。
第二件事是,当我调用ft_nonce_create_query_string 函数时,等待几秒钟然后用相同的参数再次调用它,两次调用都返回相同的值。这很奇怪,我真的不明白它如何确保它生成的每个随机数,随机数将在FT_NONCE_DURATION 中指定的持续时间内有效。
但是如果我在第二次调用之前等待更长的时间,它们将返回不同的值。我已经粘贴了代码here,你可以尝试直接运行。
为什么会这样?它应该如何工作?
<?php
/*
* Name: FT-NONCE-LIB
* Created By: Full Throttle Development, LLC (http://fullthrottledevelopment.com)
* Created On: July 2009
* Last Modified On: August 12, 2009
* Last Modified By: Glenn Ansley (glenn@fullthrottledevelopment.com)
* Version: 0.2
*/
/*
Copyright 2009 Full Throttle Development, LLC
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
define( 'FT_NONCE_UNIQUE_KEY' , '' );
define( 'FT_NONCE_DURATION' , 300 ); // 300 makes link or form good for 5 minutes from time of generation
define( 'FT_NONCE_KEY' , '_nonce' );
// This method creates a key / value pair for a url string
function ft_nonce_create_query_string( $action = '' , $user = '' ){
return FT_NONCE_KEY."=".ft_nonce_create( $action , $user );
}
// This method creates an nonce for a form field
function ft_nonce_create_form_input( $action = '' , $user='' ){
echo "<input type='hidden' name='".FT_NONCE_KEY."' value='".ft_nonce_create( $action . $user )."' />";
}
// This method creates an nonce. It should be called by one of the previous two functions.
function ft_nonce_create( $action = '' , $user='' ){
return substr( ft_nonce_generate_hash( $action . $user ), -12, 10);
}
// This method validates an nonce
function ft_nonce_is_valid( $nonce , $action = '' , $user='' ){
// Nonce generated 0-12 hours ago
if ( substr(ft_nonce_generate_hash( $action . $user ), -12, 10) == $nonce ){
return true;
}
return false;
}
// This method generates the nonce timestamp
function ft_nonce_generate_hash( $action='' , $user='' ){
$i = ceil( time() / ( FT_NONCE_DURATION / 2 ) );
return md5( $i . $action . $user . $action );
}
if ( FT_NONCE_UNIQUE_KEY == '' ){ die( 'You must enter a unique key on line 2 of ft_nonce_lib.php to use this library.'); }
?>
【问题讨论】:
-
我想我现在明白为什么它返回相同的值了,因为它必须这样做,这是为了让我们进行验证。但另一方面,这种行为会使每个函数调用返回的 nonce 值具有可变的持续时间?
-
虽然它的持续时间现在设置为 5 分钟,但从 ft_nonce_create_query_string() 函数返回的 nonce 值可能在 5 分钟内真的无效。如果在下一个间隔前 1 分钟调用,那么它只在 1 分钟内有效?我的想法正确吗?
标签: php hash cryptography