Search code examples
ntlfinite-field

Generating random element in $GF(2^x)$ in NTL


I'm trying to study part of the NTL functionality related to finite field arithmetics, but something weird is happening. I'm trying to generate 2 random elements in the field $GF(2^8)$ and do addition and subtraction with them. But it seems that the two 'random' element that I obtain are equal in every execution of the test program. Do you give any idea?

My test code:

void test3(long n) {
    NTL::GF2X P;
    NTL::BuildIrred(P, n);
    // P is now x^2+x+1, this is irreducable since P(1)=1 and P(0)=1
    NTL::GF2E::init(P);

    NTL::GF2E xx = NTL::random_GF2E();
    NTL::GF2E yy = NTL::random_GF2E();

    std::cout << "xx: " << xx << std::endl; // Prints something like "[0 1]"
    std::cout << "yy: " << yy << std::endl; // Prints something like "[0 1]"

    xx += yy;
    std::cout << "xx: " << xx << std::endl; // Prints something like "[0 1]"
    xx -= yy;
    std::cout << "xx: " << xx << std::endl; // Prints something like "[0 1]"
    xx -= yy;
    std::cout << "xx: " << xx << std::endl; // Prints something like "[0 1]"
}

The output of the test program when run several times:

~\Release>test.exe
xx: [0 1 0 0 1 0 0 1]
yy: [0 1 0 0 1]
xx: [0 0 0 0 0 0 0 1]
xx: [0 1 0 0 1 0 0 1]
xx: [0 0 0 0 0 0 0 1]

~\Release>test.exe
xx: [0 1 0 0 1 0 0 1]
yy: [0 1 0 0 1]
xx: [0 0 0 0 0 0 0 1]
xx: [0 1 0 0 1 0 0 1]
xx: [0 0 0 0 0 0 0 1]

~\Release>test.exe
xx: [0 1 0 0 1 0 0 1]
yy: [0 1 0 0 1]
xx: [0 0 0 0 0 0 0 1]
xx: [0 1 0 0 1 0 0 1]
xx: [0 0 0 0 0 0 0 1]

~\Release>test.exe
xx: [0 1 0 0 1 0 0 1]
yy: [0 1 0 0 1]
xx: [0 0 0 0 0 0 0 1]
xx: [0 1 0 0 1 0 0 1]
xx: [0 0 0 0 0 0 0 1]

Solution

  • Functions in NTL that uses randomness, are using the random number gernerators that you can find in NTL/ZZ (Pseudo-Random Numbers).

    So if you want to have different random elements from the extension field you have to set a seed for the random number generator first. If you don't, the seed is always the same and so you get alsways the same sequence of elements.

    You can set the seed as follows:

    NTL::SetSeed(conv<ZZ>((long) time(0)));
    

    Notice: for this you have to #include <time.h>.

    This is only a suggestion. You can also use rand() or any other number as seed.