0

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]);
    }
Community
  • 1
  • 1
TechAurelian
  • 5,561
  • 5
  • 50
  • 65
  • Define "true random" in this context. – Lasse V. Karlsen Mar 13 '14 at 15:11
  • 1
    Please note that the point of RNGCryptoServiceProvider is not to provide truly random values, it's about making it for all practical purposes impossible to guess the next random number even if you have a lot of previously generated random numbers. The ability to guess what the sequence is if you have previously generated numbers is a problem with the normal basic RNG implementations, but not with RNGCryptoServiceProvider. – Lasse V. Karlsen Mar 13 '14 at 15:13
  • @LasseV.Karlsen As I mentioned in the question, "true random" in this context can be described as "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.)" – TechAurelian Mar 13 '14 at 15:14
  • Seems correct, though note that your colors will in fact have varying alpha value. – decPL Mar 13 '14 at 15:16
  • 1
    @decPL I'm converting them using System.Drawing.ColorTranslator.ToWin32, so the alpha value will simply be ignored. – TechAurelian Mar 13 '14 at 15:19

0 Answers0