Hack: How to Use SecureRandom with Kubernetes and Docker

Tamas Polgar
3 min readMar 14, 2017

--

Cryptographically secure pseudo-random number generator depends on good entropy; however from Docker containers we don’t always get this. This can cause the random generation be to block the execution of the application.

Bone die found at Cantonment Clinch (1823–1834). (source: Kolby Kirk on Wikimedia Commons)

The Problem

I had a simple piece of Scala code generating random user ids by using java.security.SecureRandom.getInstanceStrong(). Something like:

It worked perfectly on local environment with the official OpenJDK docker image. However after deploying the application to Google Container Engine the application was just hanging, no exception thrown.

After some investigation I found the cause; /dev/random source is not gathering enough entropy in Google Container Engine environment.

Solution

In OpenJDK docker image (and most installations) the strong secure random algorithm is NativePRNGBlocking:SUN. This algorithm is using /dev/random source to get entropy, if there’s not enough entropy it blocks until enough entropy is gathered. On average this algorithm needs 21 seconds to generate a single random byte in my Google Container Engine cluster.

Other alternative to this source is /dev/urandom (“unlimited” random) source. This source uses a pool of entropy already gathered but it generates pseudorandom numbers if it runs out of entropy. It is still intended for most cryptographic purposes. See the sources below.

One option to use /dev/urandom as random source is to explicitly get NativePRNGNonBlocking SecureRandom instance instead of using the getInstanceStrong() method. After applying the following change my problem was fixed:

Sources

Thanks for reading, your comments are appreciated.

Hacker Noon is how hackers start their afternoons. We’re a part of the @AMI family. We are now accepting submissions and happy to discuss advertising & sponsorship opportunities.

If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!

--

--