I'm trying to generate random colors (without Alpha), using RNGCryptoServiceProvider, in C#, Windows Forms, .NET 2.0. (I will convert the colors using ColorTranslator.ToWin32, so the alpha value will simply be ignored.)
I don't want to use the standard System.Random, after reading some answers to this question Why use the C# class System.Random at all instead of System.Security.Cryptography.RandomNumberGenerator?, especially regarding problems with the distribution of the generated numbers.
Is this a good solution? I really need true random colors, and I need the user to feel that the generated colors one after another feel random, and not somehow repeating or of the same type (brightness, etc.)
Is there anything that can be improved for better randomness?
public class RandomColor
{
private RNGCryptoServiceProvider rng;
public RandomColor()
{
this.rng = new RNGCryptoServiceProvider();
}
public Color Next()
{
return Color.FromArgb(this.NextInt());
}
private int NextInt()
{
byte[] randomBytes = new byte[sizeof(int)];
this.rng.GetBytes(randomBytes);
return BitConverter.ToInt32(randomBytes, 0);
}
}
Or even simpler:
public Color Next()
{
byte[] randomRGB = new byte[3];
this.rng.GetBytes(randomRGB);
return Color.FromArgb(randomRGB[0], randomRGB[1], randomRGB[2]);
}