jeudi 12 avril 2018

Generate random number between 1 and 100 using integer as input and hash function

I'm using the following code snippet to generate a random number between 0 and 99 from an integer (n). I'm not sure the conversion of the integer into a string (and then into a byte array is a good idea and also if converting the hashed value using 8 bytes (toUInt64) instead of, for example, toUInt32 is necessary. How would you improve the code below to make it cryptographycally secure ?

    public int GenerateRandom(int n, byte[] key)
    {
        string input = n.ToString("D10");

        using (HMACSHA256 hmac = new HMACSHA256(key))
        {
            byte[] hash = hmac.ComputeHash(new ASCIIEncoding().GetBytes(input));
            return (int)(BitConverter.ToUInt64(hash, 0) % 100);
        }
    }




Aucun commentaire:

Enregistrer un commentaire