Why does dd only copy 128 bytes from /dev/random when I request more?

10

I'm trying to understand the output of the dd command. I tried

dd if=/dev/zero of=/dev/null bs=512 count=1

and got (as expected):

 1+0 records in
 1+0 records out
 512 bytes (512 B) copied, 2e-05 seconds, 26 MB/s

However when I tried

dd if=/dev/random of=/dev/null bs=512 count=1

I got

 0+1 records in
 0+1 records out
 128 bytes (128 B) copied, 0.00012 seconds, 1.1 MB/s

Why is it only copying 128 bytes?

fo_x86

Posted 2012-12-17T19:06:16.680

Reputation: 287

See http://superuser.com/questions/359599/why-is-my-dev-random-so-slow-when-using-dd for a more complete discussion of /dev/random and urandom

– BobT – 2012-12-17T19:29:09.620

Answers

8

You need to use /dev/urandom, or the "unblocking" random source.

/dev/random uses a kind of entropy pool to increase the randomness of the bit source. This method will only return as many random bits/bytes as can be returned based on the entropy pool's state at the time, so if a hardware random number generator is used, this can sometimes be a constant. From the Linux manpage:

The generator also keeps an estimate of the number of bits of noise in the entropy pool. From this entropy pool random numbers are created.

The /dev/urandom file keeps reusing the internal pool as-is to generate a number as long as you need. The side-effect of this is: do not use /dev/urandom for cryptographic purposes, as it is less random than the bits produced by /dev/random. See the manpage link above for details.

Breakthrough

Posted 2012-12-17T19:06:16.680

Reputation: 32 927

1http://www.2uo.de/myths-about-urandom/ – LawrenceC – 2015-03-11T14:38:22.187

3

Since reading /dev/random returns only the amount of bytes that is available, you have to specify block size 1. In your example, you set block size to 512 which fails after the first read.

Therefore, the correct arguments that reads exactly 512 bytes is:

dd if=/dev/random of=filename bs=1 count=512

Note the command will block until there's enough entropy in the system to generate all the data. That's how /dev/random works. If you don't want to wait and you are fine with less entropy, use /dev/urandom instead. In vast majority of cases using /dev/urandom is preferred.

Viliam

Posted 2012-12-17T19:06:16.680

Reputation: 131

+1 for the explanation, though it should be said that with byte counts as high as 512 using /dev/random becomes virtually unusable, because the command can take many minutes to finish. Also, even with bs=512 count=1 it seems that the call still blocks if there no bytes are available at all, correct? An alternative to switching bs and count values is to use iflag=fullblock; i.e., bs=512 count=1 iflag=fullblock. – mklement0 – 2015-02-01T05:44:47.247

IMHO, this answer should be merged into @Breakthrough's one. (It was the answer to my problem while Breakthrough's was not). – superbob – 2016-01-22T09:30:06.137