# Can I truncate a CSPRNG psuedorandom number?

This might be too broad to apply for all CSPRNG, but it might apply for the general case, I'm not sure. I need this specifically for python os.urandom() and SystemRandom() which get a seed from /dev/urandom, and on Windows CryptGenRandom(),

Is it possible to truncate or even modify the random number but still retains its randomness. The reason I need to do this is because the OS has nanosleep and the overflowing digits I will need to cut off.

• you want all the numbers to appear with equal probability after truncate? – crypt Jun 17 '17 at 18:42
• @Raza i can understand that, but there exist truncated probability distribution such as truncated exponential dist. to produce random numbers and rejection sampling. While, im no statistician/cryptographer I was wondering if there was anything on similar lines – Anderson Jun 17 '17 at 18:47
• to keep the distribution probability satisfied, you take mod of the number with nearest power(n) to 2 such that desired range of random numbers is less than 2^n. after that if your number is in desired range, you use it, if not, you repeat the process. this way you will get sufficient level of randomness. if you just truncate the result to your desired range, it may loose randomness – crypt Jun 17 '17 at 18:57
• define your new upper range as a 2^n to avoid validating a simple rnd % upper operation. if you end on a non-power-of-2, it's a lot more complicated to assure uniform distro, especially on the "end caps" – dandavis Jun 17 '17 at 19:06
• @dandavis Not that hard, Raza just showed a not very efficient but valid way of doing so for any kind of number. – Maarten Bodewes Jun 17 '17 at 19:43