天天看点

如何创建/dev/random和/dev/urandom字符设备

    /dev/random和/dev/urandom是内核随机数源设备,用于产生随机数。产生随机数的原理是利用当前系统的熵池来计算出固定一定数量的随机比特,然后将这些比特作为字节流返回。熵池就是当前系统的环境噪音,熵指的是一个系统的混乱程度,系统噪音可以通过很多参数来评估,如内存的使用,文件的使用量,不同类型的进程数量等等。如果当前环境噪音变化的不是很剧烈或者当前环境噪音很小,比如刚开机的时候,而当前需要大量的随机比特,这时产生的随机数的随机效果就不是很好了。

    这就是为什么会有/dev/urandom和/dev/random这两种不同的文件,后者在不能产生新的随机数时会阻塞程序,而前者不会(ublock),当然产生的随机数效果就不太好了,这对加密解密这样的应用来说就不是一种很好的选择。/dev/random会阻塞当前的程序,直到根据熵池产生新的随机字节之后才返回,所以使用/dev/random比使用/dev/urandom产生大量随机数的速度要慢。

    如果你的系统不存在这两个文件,可以通过以下命令来进行创建。

<code>mknod</code> <code>-m 644 </code><code>/dev/random</code> <code>c 1 8</code>

<code>mknod</code> <code>-m 644 </code><code>/dev/urandom</code> <code>c 1 9</code>

<code>chown</code> <code>root:root </code><code>/dev/random</code> <code>/dev/urandom</code>

    当一个linux系统启动没有太多交互式操作时,熵池可能处于一个相当可预测的状态。这降低了熵池的实际噪声量低于估计值。为了抵消这种影响,它有助于跨关闭和初创企业进行熵池信息。为此,请将下列行添加到Linux系统启动顺序中运行的适当脚本中:

<code>echo</code> <code>"Initializing random number generator..."</code>

<code>    </code><code>random_seed=</code><code>/var/run/random-seed</code>

<code>    </code><code># Carry a random seed from start-up to start-up</code>

<code>    </code><code># Load and then save the whole entropy pool</code>

<code>    </code><code>if</code> <code>[ -f $random_seed ]; </code><code>then</code>

<code>        </code><code>cat</code> <code>$random_seed &gt;</code><code>/dev/urandom</code>

<code>    </code><code>else</code>

<code>        </code><code>touch</code> <code>$random_seed</code>

<code>    </code><code>fi</code>

<code>    </code><code>chmod</code> <code>600 $random_seed</code>

<code>    </code><code>poolfile=</code><code>/proc/sys/kernel/random/poolsize</code>

<code>    </code><code>[ -r $poolfile ] &amp;&amp; bytes=</code><code>'cat $poolfile'</code> <code>|| bytes=512</code>

<code>    </code><code>dd</code> <code>if</code><code>=</code><code>/dev/urandom</code> <code>of=$random_seed count=1 bs=$bytes</code>

    另外,在Linux系统关闭期间运行的适当脚本中添加以下行:

本文转自 SoulMio 51CTO博客,原文链接:http://blog.51cto.com/bovin,如需转载请自行联系原作者

继续阅读