0

I am using C# RNGCryptoServiceProvider inside a using block

byte[] values = new byte[ammountToCreate];


using (RNGCryptoServiceProvider randomizer = new RNGCryptoServiceProvider())
{
   randomizer.GetBytes(values);
}

The result values are then normalized to interval [0:15], therefore no modulo bias should affect the output.

Normalization is done in this way:

byte n = (byte)(this.maxRandomValue + 1);

// loop all element in the input value, an apply modulo.
for (int i = 0; i < values.Length; i++)
{
  values[i] = (byte)(values[i] % n);
}

Where maxRandomValue is equal to 15.

However, from the first test, the output seems to be not uniform. I have generated 2916 numbers, and this is the values distribution:

+-------+--------------+
| Value | % On Total   |
+-------+--------------+
|     0 | 6.52%        |
|     1 | 5.90%        |
|     2 | 6.10%        |
|     3 | 6.34%        |
|     4 | 5.73%        |
|     5 | 6.89%        |
|     6 | 5.49%        |
|     7 | 6.86%        |
|     8 | 5.66%        |
|     9 | 5.97%        |
|    10 | 6.58%        |
|    11 | 6.04%        |
|    12 | 6.48%        |
|    13 | 5.97%        |
|    14 | 7.17%        |
|    15 | 6.31%        |
+-------+--------------+

As you can see: 6 --> 5.49% of generated numbers 14 --> 7.17% of generated numbers

My fear is that maybe I have generated just few numbers and with bigger volumes the distribution becomes uniform. Or, RNGCryptoServiceProvider inside a using is not working as expected.

Do you have any idea?

Slevin
  • 141
  • 1
  • 8
  • 2
    Easy way to check would be to increase the number of values generated. I don't understand why you'd think the `using` block would have anything to do with the values generated. – itsme86 Oct 12 '16 at 16:43
  • 3
    Using your code and generating 1 million values I get: 0 - 6.25%, 1 - 6.27%, 2 - 6.19%, 3 - 6.27%, 4 - 6.22%, 5 - 6.26%, 6 - 6.26%, 7 - 6.25%, 8 - 6.26%, 9 - 6.24%, 10 - 6.25%, 11 - 6.31%, 12 - 6.25%, 13 - 6.25%, 14 - 6.21%, 15 - 6.26%. Seems pretty evenly distributed to me. – itsme86 Oct 12 '16 at 16:52
  • Thank you both for the answer. I am now more confident with mine implementation. – Slevin Oct 12 '16 at 18:37

0 Answers0