Notice that nowadays, unlike 2 years ago, people usually recommend to use the last technique I presented there in the last paragraph before the Conclusion. Which is to generate a random value that is <i>big enough</i>, so that n-log(p) > 128 so that the bias will be too small to be exploitable in practice. It's simpler and unlike rejection sampling ensures your code cannot fall into an infinite loop in case your PRNG is broken. (I'd argue you might want your code to fail in that case anyway, but YMMV.)
A cleaner example without bit masking: <a href="https://github.com/openbsd/src/blob/master/lib/libc/crypt/arc4random_uniform.c" rel="nofollow">https://github.com/openbsd/src/blob/master/lib/libc/crypt/ar...</a>
Everything here is focused on cryptography, but there's other common issues that can fall into this trap too. For example, naive implementations of a hash function for a basic array + linked list hash table. If you generate a hash, and then modulo that to pick a hash bucket, you could end up with a biased distribution across the buckets, and customers complaining your performance varies wildly based on the input value.<p>Just more things to think about :)
If you need to generate multiple such random numbers, an alternative way to resolve modulo bias with minimal entropy waste is to batch the random number generation. For example, you can generate 6 random integers in [0, 100) by generating a random integer in [0, 100^6) and performing modulo reductions on the result to get your 6 integers. 100^6 is slightly less than 256^5, so if your RNG works in units of bytes, then you can use 5 bytes to generate 6 integers in [0, 100) instead of 6 bytes.
> You shouldn’t rely on these claims, because even 1 bit of bias on a 256 bit nonce value can be enough to attack certain cryptographic schemes!<p>This seems like a very high bar for a random generator to clear. It also raises a question: would using a larger nonce size actually <i>increase</i> risk, if the additional bits were biased?
The claim "even 1 bit of bias on a 256 bit nonce value can be enough to attack certain cryptographic schemes" is true but there have been no practical attacks against 256 bit secured schemes. And the example of the mod 107 issue only reduces the amount of bits from 6.74bits to 6.71bits (a reduction of 0.4%) so hardly worth worrying about in the real world.
I remember very old versions of <i>man random</i> [1] warning against that sort of thing and recommending to pick the high (or low) bits of the random value. Probably the piece of advice was not correct.