概述 快速入门 教程 手册 最佳实践 组件 参考 贡献

发布于 2015-08-27 16:55:46 | 111 次阅读 | 评论: 0 | 来源: 网络整理

The Symfony Security component comes with a collection of nice utilities related to security. These utilities are used by Symfony, but you should also use them if you want to solve the problem they address.

Comparing Strings

The time it takes to compare two strings depends on their differences. This can be used by an attacker when the two strings represent a password for instance; it is known as a Timing attack.

Internally, when comparing two passwords, Symfony uses a constant-time algorithm; you can use the same strategy in your own code thanks to the StringUtils class:

use SymfonyComponentSecurityCoreUtilStringUtils;

// is some known string (e.g. password) equal to some user input?
$bool = StringUtils::equals($knownString, $userInput);

警告

To avoid timing attacks, the known string must be the first argument and the user-entered string the second.

Generating a Secure random Number

Whenever you need to generate a secure random number, you are highly encouraged to use the Symfony SecureRandom class:

use SymfonyComponentSecurityCoreUtilSecureRandom;

$generator = new SecureRandom();
$random = $generator->nextBytes(10);

The nextBytes() method returns a random string composed of the number of characters passed as an argument (10 in the above example).

The SecureRandom class works better when OpenSSL is installed. But when it’s not available, it falls back to an internal algorithm, which needs a seed file to work correctly. Just pass a file name to enable it:

use SymfonyComponentSecurityCoreUtilSecureRandom;

$generator = new SecureRandom('/some/path/to/store/the/seed.txt');
$random = $generator->nextBytes(10);

注解

If you’re using the Symfony Framework, you can access a secure random instance directly from the container: its name is security.secure_random.

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务