Hash function for game.

I need a random function which whenever I given X it’ll give me Y.

So this is sound like how hash work.

Speed is very concern while it maybe called >20 times for an Update() loop.

Murmur is what I considered here. But what to know if it’s a good choice.

all objects in .net/mono have a ‘GetHashCode’ method.

Any object will return the same hashcode for itself no matter what. The hashcode is not necessarily unique, but it is consistent.

2 Likes

Here’s a few different implementations from my utils class that may be of use:

Sha1:

    public static string Sha1Sum2 (string str)
    {
        System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding ();
        byte[] bytes = encoding.GetBytes (str);
        var sha = new System.Security.Cryptography.SHA1CryptoServiceProvider ();
        return System.BitConverter.ToString (sha.ComputeHash (bytes));
    }

Sha256:

    public static string sha256(string str)
    {
        System.Security.Cryptography.SHA256Managed crypt = new System.Security.Cryptography.SHA256Managed();
        System.Text.StringBuilder hash = new System.Text.StringBuilder();
        byte[] crypto = crypt.ComputeHash(Encoding.UTF8.GetBytes(str), 0, Encoding.UTF8.GetByteCount(str));
        foreach (byte bit in crypto)
        {
            hash.Append(bit.ToString("x2"));
        }
        return hash.ToString().ToLower();
    }

md5:

    public static string md5 (string str)
    {
        System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding ();
        byte[] bytes = encoding.GetBytes (str);      
        var sha = new System.Security.Cryptography.MD5CryptoServiceProvider();
        return System.BitConverter.ToString (sha.ComputeHash (bytes));
    }

System.Security.Cryptography has many crypto service providers to choose from, take your pick :slight_smile:

Hope that helps.

3 Likes

Depending on what you’re doing it’s possible Mathf.PerlinNoise will be useful?

2 Likes

@andymads That’ll be extremely useful

Could you elaborate on what X is? Is it a gameobject?
You could try GetInstanceID()

In the editor, right-click on the Inspector tab, and choose “Debug”. The editor will tell you what the Instance ID is.

2 Likes

thanks for these, but do you have the method to go the other way around too ? ie decrypt.

Hash functions are one way functions. They are not encryptions at all. I don’t quite understand how so many people think that hashing == encryption, it does not. If you’re looking for encryption, you’re in the wrong thread.

1 Like

Oh I can real dumb sometimes :slight_smile: guess I dont quite know what hash is lol