Search code examples
c#hashcryptographyhashcode

Can the random seed of HashCode in C# be considered cryptographically random?


The documentation of HashCode mentions that a 'random seed' is used that is 'only deterministic within the scope of an operating system process'.

My questions are:

  • How is this random seed implemented? Can this random seed be considered cryptographically random?

Solution

  • Let's take a look. The source for HashCode is here. We can see the line:

    private static readonly uint s_seed = GenerateGlobalSeed();
    

    So let's take a look at GenerateGlobalSeed:

    private static unsafe uint GenerateGlobalSeed()
    {
        uint result;
        Interop.GetRandomBytes((byte*)&result, sizeof(uint));
        return result;
    }
    

    OK, and Interop.GetRandomBytes:

    Sys.GetNonCryptographicallySecureRandomBytes(buffer, length);
    

    Pretty big give-away there: NonCryptographicallySecureRandomBytes. This is not a cryptographic source.

    If we look further at the implementation, we can see that it uses arc4random_buf or lrand48, which very definitely aren't cryptographic.

    Even if the seed was cryptographic, note that the it's constant for an entire process. It wouldn't be particularly hard to figure out what it is, depending on what sort of attack you're guarding against.