Reference article: Yang Zhengko Teacher's "random number is deceptive,. Net, Java, C for me to testify" http://www.cnblogs.com/rupeng/p/3723018.html#!comments 1. Principle of random number: "Linear with Congruential": Section n+ One number = (nth number *29+37)% 10002. Write a random of your own
1 Static voidMain (string[] args)2 {3Myrandom Mr =NewMyrandom (8);//The same seed, each time will generate the same random sequence, in order to ensure that the generated random number is different, you need to have a different seed every time, Envoironment.tickcount4 for(inti =0; I <Ten; i++)5 {6 Console.WriteLine (Mr. Next ());7 }8 Console.readkey ();9 }Ten } One classMyrandom A { - Private intSeed//Field Seed - PublicMyrandom (intSeed//constructor Function the { - This. Seed =seed; - } - Public intNext () + { - intNext = (Seed * in+Panax Notoginseng) % +; +Seed =Next; A returnNext; at } -}View CodeThe 3..net internal random () uses the Decompile tool to see that the seed is environment.tickcount, so that the random number generated each time is basically different. 4. However, the Random ran=new random () must be placed outside the for loop because the for loop is running fast, So the runtime Enviroment.clickcount is the same as the last value, so the same random number 5 is generated. However, if the website generates a verification code with random numbers, when it encounters high concurrency, there will be more than one person concurrently accessing it, which will result in several people requesting the same verification code, and the system has potential vulnerabilities. So how can such a problem be solved? 1) Use the Random object as a global instance, and the random in Java is thread-safe (internal locking), While. NET random is thread insecure, requires locking, locking reduces efficiency, and because the initial seed is deterministic, the attacker has the possibility of inferring a "random number seed" based on a number of random sequence numbers. 2) Use the GUID value to get the hashcode or MD5 value as the seed. But the GUID is also calculated based on some algorithm, although the probability of random increase, but not the real random number 3) True random number generator. NET can also use the RNGCryptoServiceProvider class (under the System.Security.Cryptography namespace) to generate a true random number
The secret of random numbers