在PHP中为URL生成随机字符

时间:2014-07-01 17:13:50

标签: php security passwords cryptography

我已经回答了我自己的实现(如下),如果你能检查数学和逻辑,我会很感激,但我也意识到还有其他的可能性。


我试图在注册网址中生成32个随机字符。

新帐户部分由员工创建(设置名称/电子邮件),并向新用户发送纯文本电子邮件,以便他们确认自己的电子邮件地址并设置密码。

尝试保留[A-Za-z0-9]字符,我相信这会创建一个基本的62系统,只需要不到6位来存储...这只是超过190位的熵?还是190.53428193238?

由于这是一项安全功能,我不相信uniqid()单独是一个好主意,因为这是基于当前的微缩时间。

我不相信使用加密或散列用户ID或电子邮件地址也是一个很好的解决方案(碰撞,低熵,并且可能由一个密钥保护)。

1 个答案:

答案 0 :(得分:1)

这适用于PHP 7.0 random_bytes()函数:

<?php

function random_key($length, $safe = false) {

    if ($safe !== false) {
        $bad_words = array_map('trim', file('/path/to/bad-words.txt', FILE_IGNORE_NEW_LINES));
    } else {
        $bad_words = NULL;
    }

    $j = 0;

    do {

        $bytes = (ceil($length / 4) * 3); // Must be divisible by 3, otherwise base64 encoding introduces padding characters, and the last character biases towards "0 4 8 A E I M Q U Y c g k o s w".
        $bytes = ($bytes * 2); // Get even more, because some characters will be dropped.

        $key = random_bytes($bytes);
        $key = base64_encode($key);
        $key = str_replace(array('0', 'O', 'I', 'l', '/', '+'), '', $key); // Make URL safe (base58), and drop similar looking characters (no substitutions, as we don't want to bias certain characters)
        $key = substr($key, 0, $length);

        if (preg_match('/[^a-zA-Z0-9]/', $key)) {
            exit_with_error('Invalid characters detected in key "' . $key . '"');
        }

        $valid = (strlen($key) == $length);

        if ($bad_words) {
            foreach ($bad_words as $bad_word) {
                if (stripos($key, $bad_word) !== false) {
                    $valid = false;
                    break;
                }
            }
        }

        if ($valid) {
            return $key;
        }

    } while ($j++ < 10);

    exit_with_error('Cannot generate a safe key after 10 attempts.');

}

?>

此代码显示base64_encode()函数如何偏向某些字符:

<?php

$characters = [];

for ($k = 0; $k < 500000; $k++) {

    $key = base64_encode(random_bytes(32)); // 32 bytes results in "=" padding; try changing to 30 to fix.

    foreach (str_split($key) as $c) {
        if (!isset($characters[$c])) {
            $characters[$c] = 0;
        }
        $characters[$c]++;
    }

}

$characters = array_filter($characters, function($value) {
        return ($value > 343750); // ((((33/3)*4)*500000)/64) = 343750, everything else is about ~327000
    });

ksort($characters, SORT_STRING);

print_r($characters);

?>