This answer assumes you know what you're doing. In other cases, use of /dev/random should be minimized.
/dev/random
acts like a normal file, therefore any program which can read any file can read from /dev/random
. You probably know that cat /dev/random
outputs random data directly from it, and if it does this fast enough, you might in fact want to use it. So, if everything else fails, you'll be always be able to directly read that file...
So, if you look at the source of SecureRandom
, you discover that it uses SecureRandomSpi
for the actual work. It turns out that NativePRNG.Blocking
does what you want:
A NativePRNG-like class that uses /dev/random for both seed and random material. Note that it does not respect the egd properties, since we have no way of knowing what those qualities are. This is very similar to the outer NativePRNG class, minimizing any breakage to the serialization of the existing implementation.
Since:
1.8
The problem might be the Since 1.8
, which leaves you with the possibility to backport it to earlier platforms, if you can't use Java 8 yet. The sourcecode is available after all.
So, now let's put this in code:
We have to select the specific implementation to use. To find the exact name, we output all available services with the following line:
for (Provider p: Security.getProviders()) p.getServices().forEach(System.out::println);
We then search for Native
in there, and we find the folllowing entry:
SUN: SecureRandom.NativePRNGBlocking -> sun.security.provider.NativePRNG$Blocking
This means we can instantiate the SecureRandom
object like below to do what you want:
SecureRandom sr = SecureRandom.getInstance("NativePRNGBlocking", "SUN");
A simple test
byte[] b = new byte[10000];
sr.nextBytes(b);
System.out.println(Arrays.toString(b));
takes ages, I had to lower the amount of read bytes. If it works for you, congratulations, you're reading from /dev/random
!
Notice though that this class is in the sun.security.provider
package, which is not guaranteed to be available everywhere. For example, it will probably not work on Android. If this fine, then this solution will work, otherwise you should just directly read it as a file.
Don't read from /dev/random
on Android. Please.
/dev/urandom
anymore, even if it wants? – Repose/dev/urandom
shall not be used at all, maybe a combination is needed... – Reposemknod /dev/urandom 1 8
would certainly suffice to ensure that the HPRNG is always used. And when you do control the code, you get to choose which one is easiest! – Aether