Search code examples
c#cryptographylfsr

random number using LFSR


I am a little new to this subject.

Initial idea is to generate a random number using a LFSR. So far I have developed a LFSR method using c#. Once the function is called it returns the same value all the time.

What I have to change in order to collect a different random number each time I run the programm?

 int lfsr1()
    {
        int start_state = 5;  /* Any nonzero start state will work. */
        int lfsr = start_state;
        int bit;                    /* Must be 16-bit to allow bit<<15 later in the code */



           /* taps: 16 14 13 11; feedback polynomial: x^16 + x^14 + x^13 + x^11 + 1 */
            bit = ((lfsr >> 0) ^ (lfsr >> 2) ^ (lfsr >> 3) ^ (lfsr >> 5)) /* & 1u */;
            lfsr = (lfsr >> 1) | (bit << 15);

        return lfsr;
    }

call

Console.Write(lfsr1());

the output is same all the time.


Solution

  • As Creyke mentioned earlier, a constant seed (or starting value) mean your function will generate a deterministic value.

    In order to collect a different random number each time, you should generate a seed from the state of the computer (usually the time), CSPRNG or an external hardware random number generator.

    Example (using time, with Environment.TickCount):

    using System;
    
    class LSTR
    {
        int GetSeed()
        {
            // & with Int32.MaxValue to remove sign bit, i.e get a positive number
            return Environment.TickCount & Int32.MaxValue;
        }
        int lfsr1()
        {
            int start_state = GetSeed();  /* Any nonzero start state will work. */
            int lfsr = start_state;
            int bit;                    /* Must be 16-bit to allow bit<<15 later in the code */
            /* taps: 16 14 13 11; feedback polynomial: x^16 + x^14 + x^13 + x^11 + 1 */
    
            bit = ((lfsr >> 0) ^ (lfsr >> 2) ^ (lfsr >> 3) ^ (lfsr >> 5)) /* & 1u */;
            lfsr = (lfsr >> 1) | (bit << 15);
    
            return lfsr;
        }
    }