Pseudo-random generation able to regenerate backwards Using the accepted answer from this question, I made a random number generator which can regenerate previous numbers in order.

Ideone version

byte[] Encrypt(byte[] ClearData, byte[] Key)
{
   MemoryStream ms = new MemoryStream();

    Rijndael alg = Rijndael.Create();
    alg.KeySize = 128;
    alg.BlockSize = 128;
    alg.Mode = CipherMode.ECB;

    alg.Key = Key;

    CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write);

    cs.Write(ClearData, 0, ClearData.Length);

    cs.Close();

    byte[] encryptedData = ms.ToArray();

    return encryptedData;
}

int RandomValue(int Max)
{
    byte[] FirstHalf = BitConverter.GetBytes(Key);
    byte[] SecondHalf = BitConverter.GetBytes(Key);

    byte[] KeyBytes = new Byte[FirstHalf.Length + SecondHalf.Length];
    FirstHalf.CopyTo(KeyBytes, 0);
    SecondHalf.CopyTo(KeyBytes, FirstHalf.Length);

    byte[] RandValue = Encrypt(new byte[0], KeyBytes);

    int Rand = Math.Abs(BitConverter.ToInt32(RandValue, 0));

    return Rand % Max;
}

int NextValue(int Max)
{
    ++Key;
    return RandomValue(Max);

}

int PreviousValue(int Max)
{
    --Key;
    return RandomValue(Max);

}

static void Main()
{
    byte[] buffer = new byte[sizeof(Int64)];
    Rand.NextBytes(buffer);
    Key = BitConverter.ToInt64(buffer, 0);

    for(int i = 0 ; i &lt; 4 ; ++i)
    {
        Console.WriteLine(NextValue(10));
    }

    Console.WriteLine();

    for(int i = 0 ; i &lt; 4 ; ++i)
    {
        Console.WriteLine(PreviousValue(10));
    }
}


Sample output:




Value 0: 8
Value 1: 1
Value 2: 0
Value 3: 8

Value 2: 0
Value 1: 1
Value 0: 8
Value -1: 7



The desired output from the asker of the stackoverflow question could be obtained by incrementing Key after getting a random value in the NextValue function but for my use this output is more appropriate.

It won't generate backwards properly if the Max changes. It doesn't need to be able to do this especially since Max in unlikely to change between calls, but seeing as how the whole purpose of this is to generate forward and backwards accurately, it seems like something should change.

I'm using Encrypt blindly since I don't understand how it works or even what the ClearData is used for.

What can be changed to improve it and make it more understandable?
Dispose of IDisposable objects with the using statement. For example, objects of type Rijndael, MemoryStream, and CryptoStream. Follow C#'s capitalization conventions, in particular camelCase for parameters (and though not specified in the link, for local variables).