vendredi 24 avril 2020

Create pseudorandom seed from string in C#?

For a pseudo random generator (game-related) I need to create a seed from a string. It's not for security, but I still prefer this seed to be as random as possible.

I don't use GetHashCode():

  • the implementation might differ per .NET version.
  • I'm also not sure about the randomness of GetHashCode().

Right now I use MD5 - see code below:

public static int GetSeedFromString(string value)
{
    using ( var md5 = MD5.Create() )
    {
        var inputBytes      = Encoding.ASCII.GetBytes(value);
        byte[] hashBytes    = md5.ComputeHash(inputBytes);

        // FIXME: force endianness for potential different systems
        return BitConverter.ToInt32(hashBytes, 0);
    }
}

Two problems:

  • it is dependent on Endian (for now) - hower this might be easily fixable
  • I'm not sure about the spread of this randomness. It doesn't have to be perfect, but if there's a simpler method with better results I prefer that.

Is there any more common way to generate a pseudo random seed from a string?




Aucun commentaire:

Enregistrer un commentaire