There might be a need occasionally to generate sequences of random numbers in your real-world programs. While there is a special class in Java to deal just with that — java.util.Random — it’s not cryptographically strong, and the numbers chosen are not completely random because a definite mathematical algorithm (based on Donald E. Knuth’s subtractive random number generator algorithm) is used to select them. Therefore it is not safe to use this class for tasks that require high level of security, like creating a random password, for example.

Fortunately, there’s another, much more cryptographically strong random number generator provided with every Java Runtime Environment by default. It can be accessed via the java.security.SecureRandom class, which is a subclass of class Random mentioned above. That means that you can use it the same way you did when you used the generator implemented by the Random class, it even allows you to set the random seed of your choice if it happens so that you need to repeat the sequence of numbers generated, which is good as for example the .NET equivalent — System.Security.Cryptography.RNGCryptoServiceProvider — does not allow to do that. However, there is one or two issues that, if not addressed, might turn into real problems and cause lots of headaches. But before I describe those, let me talk you into how to start using this strong random number generator.

Read more...