Hacker News new | past | comments | ask | show | jobs | submit login

If you generate 1000 random integers, but we know there's a 28% chance it will be 0 and a 14% chance it will be 1,2,3,4, or 5, a clever attacker can more accurately predict/brute force outputs.

When you're working with cryptography, you want a uniform distribution of possible values as well as unpredictable randomness.




For 0..max random integer it depends on max and length. If max is 2^32 and 2^32 modulo charset.length = 0 it should be fine. Am I right? In our case length is 85 and it is indeed biased. Needs a pull request.


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/5aa6689651a5...

I'll open a PR tonight if nobody beats me to it.


In 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,


Your RNG is not cryptographically secure, I'd wager.

http://3v4l.org/DC0RM


I 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.


This also works i guess

max = 100

length = 85

num = rand(max)

puts (num * length)/max




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: