简体   繁体   中英

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?

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

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.

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 .

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();       
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM