你如何创建“好”的?随机MD5哈希在PHP? [英] How do you create "good" random md5 hashes in php?

查看:169
本文介绍了你如何创建“好”的?随机MD5哈希在PHP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在几种情况下,我需要创建随机MD5散列。你知道这样做的最好/最安全的方法是什么吗?

For several cases I would need to create random md5 hashes. Do you know what the best / most secure ways of doing this are?


  • 验证电子邮件地址
  • 重置密码

  • 用于身份验证的某种会话ID,而不是密码(例如:点击记住我,我不想将通行证存储在cookie中)

我知道 rand()不应该用于安全相关的应用程序。出于这个原因,我去了:

I know that rand() should not be used for security relevant applications. For that reason I went with:

md5( uniqid(mt_rand(),true) );

现在我阅读 uniqid()的/en/function.uniqid.phprel =nofollow> php手册,它不能用于安全目的

Now I read in the php manual about uniqid(), that it must not be used for security purposes. Which kind of makes sense because it usually just gives something like a timestamp.

但是,如果结合随机前缀 - mt_rand(),这很好吗? - 像我这样做,还是有更好的应该在这种情况下使用?

But is it fine when combined with a random prefix - mt_rand() - like I do, or is there something better that should be used in this case?

Thx提前!

推荐答案

你不需要MD5哈希,你只需要一个随机字符串。这些与MD5完全无关。所以你需要的是一个好的PRNG。例如:

You don't need "MD5 hashes", you simply need a random string of characters. These need not have anything to do with MD5 at all. So all you need is a good PRNG. For instance:

$token = mcrypt_create_iv($rawLength, MCRYPT_DEV_URANDOM);
// or
$token = openssl_random_pseudo_bytes($rawLength);
// or
$token = file_get_contents('/dev/urandom', false, null, 0, $rawLength);

然后 base64_encode bin2hex 获取ASCII字符串的原始值。

Then base64_encode or bin2hex the raw value to get an ASCII character string.

这篇关于你如何创建“好”的?随机MD5哈希在PHP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆