1. How do you generate 5 digit long numbers with RNGCSP?
For the numbers, you can use a range. You'll have to think of the lower bound yourself though. Ranges for number are treated in RNGCryptoServiceProvider.
So for a 5 digit number min
would be 0
or 10000
and max
would be 100000
, because max
is exclusive.
2. How do you generate numbers from 1 to 6 (excluding zeroes)?
Basically the same way, you generate a range [1, 7) where 7 - the max
value - is exclusive.
If you just want a dice result you can just do something like this (untested!):
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] singleByteBuf = new byte[1];
int max = Byte.MaxValue - Byte.MaxValue % 6;
while (true) {
rng.GetBytes(singleByteBuf);
int b = singleByteBuf[0];
if (b < max) {
return b % 6 + 1;
}
}
Basically the same idea, but is only requests 1 byte at a time from the RNGCryptoServiceProvider
, so it doesn't waste 3 additional bytes.