生成 7 个字符长的唯一随机字母数字字符

2022-01-22 00:00:00 unique passwords php mysql

它不必是有意义的词——更像是随机密码生成,但要注意的是——它们应该是唯一的.我将把它用于某种包/产品代码.哪种方法最好?:)

解决方案

生成具有唯一元素和随机元素的序列通常是不可能的:显然,为了唯一,算法必须考虑序列中先前生成的元素,所以接下来的就不是真的随机了.

因此,您最好的选择是检测冲突并重试(在您的特定情况下这可能非常昂贵).

如果您仅限于 7 个字符,那么您在上面无能为力:

$allowed_chars = 'abcdefghijklmnopqrstuvwxz';$allowed_count = strlen($allowed_chars);$密码=空;$password_length = 7;while($password === null || already_exists($password)) {$密码='';for($i = 0; $i < $password_length; ++$i) {$password .= $allowed_chars{mt_rand(0, $allowed_count - 1)};}}

这最终应该会给你一个新密码.

然而,在我遇到的类似情况下,我通常会选择一个更大的密码大小,它也恰好是流行散列函数的十六进制表示的大小(例如 md5).然后你可以让自己更轻松,更不容易出错:

$password = time();//如果你有一些其他的随机"输入在这里使用会更好做 {$password = md5(time().$password);}while (already_exists($password));

这还有一个额外的好处,即序列空间更大,因此冲突更少.您可以根据将来生成的预期密码数量来选择哈希函数的大小,以保证"低冲突概率,从而减少对可能昂贵的 already_exists 函数的调用.p>

It need not be meaningful words - more like random password generation, but the catch is - they should be unique. I will be using this for some kind of package / product code. Which is the best method available? :)

解决方案

It is generally not possible to generate sequences with both unique and random elements: obviously to be unique the algorithm has to take into account the previously generated elements in the sequence, so the next ones will not really be random.

Therefore your best bet would be to detect collisions and just retry (which could be very expensive in your particular case).

If you are constrained to just 7 chars, there's not much you can do above:

$allowed_chars = 'abcdefghijklmnopqrstuvwxz';
$allowed_count = strlen($allowed_chars);
$password = null;
$password_length = 7;

while($password === null || already_exists($password)) {
    $password = '';
    for($i = 0; $i < $password_length; ++$i) {
        $password .= $allowed_chars{mt_rand(0, $allowed_count - 1)};
    }
}

This should eventually give you a new password.

However, in similar cases I have encountered I usually pick a larger password size which also happens to be the size of the hex representation of a popular hash function (e.g. md5). Then you can make it easier on yourself and less error prone:

$password = time(); // even better if you have some other "random" input to use here

do {
    $password = md5(time().$password);
}
while (already_exists($password));

This also has the added advantage that the sequence space is larger, hence there will be less collisions. You can pick the size of the hash function according to the expected numbers of passwords you will generate in the future to "guarantee" a low collision probability and thus less calls to the possibly expensive already_exists function.

相关文章