SHA512在PHP中生成随机数 [英] SHA512 to generate random numbers in PHP

查看:174
本文介绍了SHA512在PHP中生成随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用$blockhash[$i] = rand().time().rand()

然后,对于该数组中的每个随机数,我计算对应的SHA512

Then, for each random number in that array I calculate the correspondent SHA512

$SecretKey = "60674ccb549f1988439774adb82ff187e63a2dfd403a0dee852e4e4eab75a0b3";
$sha = hash_hmac('sha512', $value, $SecretKey);

将其拆分:

$pool  = str_split($sha, 2);

然后我从$ pool数组中获得第一个数字,将十六进制转换为dec并将其限制在1到50之间:

Then I get the first number from the $pool array, convert hex to dec and limit it within 1 and 50:

$dec = hexdec($pool[0]) % 50 + 1;

问题在于数字不是那么随机,我也不知道为什么.我正在计算每个数字从1到50的频率,但是数字1,2,3,4,5和6比其他数字经常出现.见图

The problem is that the numbers are not that random and I don't know why. I'm counting the frequency for each number from 1 to 50 but the numbers 1,2,3,4,5 and 6 are coming up often than the others. See graph

为什么会发生这种情况以及如何解决?谢谢!

Why is this happening and how to fix it? Thanks!

推荐答案

由于从哈希中获取两个十六进制数字,您获得1-6的频率更高.那是一个字节,因此它可以存储从0255的值.然后,使用模50.结果,您得到范围0-4950-99100-149150-199200-249和... 250-255.这最后一个是您的结果中1-6普遍存在的原因.

You get 1-6 more often because you fetch two hexadecimal digits from the hash. That's one byte, so it can store values from 0 to 255. Then you use modulo 50. In result you get ranges 0-49, 50-99, 100-149, 150-199, 200-249 and... 250-255. This last one is responsible for extra prevalence of 1-6 in your results.

解决方案:只需使用mt_rand(1,50);

如果您确实需要将数字从0-255范围转换为1-50范围,则解决方案是缩放和舍入.

If you really need to convert a number from 0-255 range to 1-50 range, the solution would be scaling and rounding.

$number = round(($byteValue)/(255/49))+1; 

这篇关于SHA512在PHP中生成随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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