gpt4 book ai didi

PHP - 为电子邮件闭环验证创建随机哈希字符串

转载 作者:太空狗 更新时间:2023-10-29 12:05:43 26 4
gpt4 key购买 nike

我目前正在从事一个需要闭环电子邮件验证的项目。作为该过程的一部分,我需要生成一个随机哈希字符串,该字符串可以附加到发送给用户的链接中。当他们单击链接时,他们将被定向到我的网站,届时应用程序将确认哈希并完成注册过程。对于我一直在使用的所有哈希:

hash('sha256', $string);

但是对于这个过程,我需要为 $string 设置一个随机值。我有可用的 Zend Framework 并希望做这样的事情:

$crypt = new Zend_Filter_Encrypt_Mcrypt(array());

$hash = hash('sha256', $crypt->getVector());

我的问题是,这是生成随机哈希码的可行算法吗?

这里是 Zend_Filter_Encrypt_Mcrypt::setVector() 方法(生成通过 getVector() 返回的值):

public function setVector($vector = null)
{
$cipher = $this->_openCipher();
$size = mcrypt_enc_get_iv_size($cipher);
if (empty($vector)) {
$this->_srand();
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' && version_compare(PHP_VERSION, '5.3.0', '<')) {
$method = MCRYPT_RAND;
} else {
if (file_exists('/dev/urandom') || (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')) {
$method = MCRYPT_DEV_URANDOM;
} elseif (file_exists('/dev/random')) {
$method = MCRYPT_DEV_RANDOM;
} else {
$method = MCRYPT_RAND;
}
}
$vector = mcrypt_create_iv($size, $method);
} else if (strlen($vector) != $size) {
require_once 'Zend/Filter/Exception.php';
throw new Zend_Filter_Exception('The given vector has a wrong size for the set algorithm');
}

$this->_encryption['vector'] = $vector;
$this->_closeCipher($cipher);

return $this;
}

最佳答案

我对 ZF 不是很熟悉,但是其中包含 Encrypt 一词的东西听起来像是错误的方法。

->getVector() 听起来与 Initialization Vector 在对称加密中的作用相似;问题是这样的向量不需要密码安全,只是随机的。例如,它很可能只是实现为 uniqid(mt_rand()) 或其他东西。

->getVector() 使用mcrypt 首先初始化加密密码,知道IV应该有多大;这通常是 8 个字节,但它在很大程度上取决于所用密码的 block 大小。问题是,您没有加密任何内容;你只需要一个随机序列。

获得随机序列的更好方法是使用大小为 8 字节的 openssl_random_pseudo_bytes()

如果没有,您还可以从熵文件中读取,例如 /dev/random/dev/urandom。之后您可以通过 binh2hex() 运行它以生成一个十六进制字符串。

像这样的东西很初级,但应该可以在 Linux'y 系统上运行:

$rnd = bin2hex(file_get_contents('/dev/urandom', false, null, 0, 8));

作为 Windows 的后备方案,您仍然可以使用类似的东西:

$rnd = hash('sha256', uniqid(mt_rand(), true));

关于PHP - 为电子邮件闭环验证创建随机哈希字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13754342/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com