4 ms·
Correct, that's the edge case where it actually falls together neatly. If you're starting with a random byte and charset.length is an even power of 2, you end
by sarciszewski 11y ago
Correct, that's the edge case where it actually falls together neatly.
If you're starting with a random byte and charset.length is an even power of 2, you end up with no bias.
It's better to design functions like this to discard values outside of an acceptable range and try again until they generate a safe value (also, apply a & bit mask to reduce the number of retries). This allows you to accept any arbitrary charset size without being concerned about security.
See also:
https://github.com/paragonie/random_compat/blob/5aa6689651a58a1f97e87d9e1188e5d90c871cc3/lib/random.php#L393-L447 https://github.com/paragonie/random_compat/blob/5aa6689651a5...
I'll open a PR tonight if nobody beats me to it.
- homakov 11y agoIn theory, haha. In practice it gives me some numbers twice more. [2001954, 1000322, 998546, 1001551, 999105, 2000886, 998760, 998705, 1000001, 998424, 1000978, 2000907, 1002097, 998786, 1000101, 998818, 1000381, 1999818, 999662, 1001260, 999531, 1000076,
- sarciszewski 11y agoYour RNG is not cryptographically secure, I'd wager. http://3v4l.org/DC0RM http://3v4l.org/DC0RM
- homakov 11y agoI thought instead of cutting off out of range results we could num*85/4294967296 and round it. But now realized buckets for rounding won't be of equal size and it's wrong.
- homakov 11y agoThis also works i guess max = 100 length = 85 num = rand(max) puts (num * length)/max