James
James

Reputation: 31738

Generate predictable random numbers C#

I would like the generate random numbers - except given the same seed, they should always be the same. How could this be done?

e.g. Given the seed 'I like turtles' it should generate a number e.g. 1234 no matter when/how many times it was called. I need this for a security application.

Upvotes: 2

Views: 2487

Answers (3)

If you're doing security, You'd really be better served by using a library, but if you absolutely must do it yourself...

It looks like you'd rather compute a hash code.

here is some information on generating a MD5 hash code from a string

Here is the code sample on that page

public static  string CalculateMD5Hash(string strInput)
{
  MD5 md5 = System.Security.Cryptography.MD5.Create();
  byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(strInput);
  byte[] hash = md5.ComputeHash(inputBytes);            

  StringBuilder sb = new StringBuilder();           
  for (int i = 0; i < hash.Length; i++)           
  {               
    sb.Append(hash[i].ToString("x2")); 
  }         
  return sb.ToString();       
}

Upvotes: 0

Robert Harvey
Robert Harvey

Reputation: 180787

The Random class will generate the same sequence of numbers, if you supply it with the same seed.

If you just want to return a predictable number from a given string, use a hash.

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612794

That is precisely how pseudo random number generators (PRNGs) work. When seeded the same way, they yield the same sequence of pseudo random numbers.

Take a look at the documentation for the constructor of the Random class:

Providing an identical seed value to different Random objects causes each instance to produce identical sequences of random numbers.

Only do note that PRNGs use numeric seeds rather than strings, as per your example in the question. And if you need a cryptographically secure PRNG, then you'll need to use a class other than Random, although the same principles regarding seeds apply.

Upvotes: 2

Related Questions