linux随机数使用熵不足导致程序运行缓慢

熵池不足导致的运行缓慢问题


有些程序运行加密时,系统会从虚拟设备(/dev/random)中取用随机数以供使用。
然而,/dev/random会使用熵池中的数据来生成随机数.在熵不足时,生成随机数非常缓慢,导致阻塞.
nginx,apache,tomcat,PHP等很多程序都会用到随机数,可以说很重要.
2024年更新:5.6+内核已经不再阻塞,5.10+内核生成的随机数已足够强大。如果你使用了新内核,本文可以略过。

什么熵


Entropy(熵,[shāng])在信息论中表示数据的混乱程度或者不确定性,可理解为随机数据。

在 GNU/Linux 中有两个虚拟设备专门用于生成随机数以供系统使用。分别为 /dev/random /dev/urandom,又称 PRNG(Pseudorandom Number Generator,伪随机数发生器),其中 /dev/random 数据来源为硬件设备的活动(键盘输入、磁盘读写、内存错误等)和其他操作系统资源,默认熵池随机数资源大小为 4kB ,由内核参数/proc/sys/kernel/random/poolsize控制。

查询熵池


cat /proc/sys/kernel/random/entropy_avail

一般VPS会在200左右,随机数据严重不足

补充熵池的解决方法

CentOS 7补充熵池


yum install rng-tools haveged -y
systemctl enable haveged
systemctl enable rngd.service
systemctl restart rngd.service

Debian 9补充熵池


apt install rng-tools haveged -y
sed -i -r '/^HRNGDEVICE/d;/#HRNGDEVICE=\/dev\/null/a HRNGDEVICE=/dev/urandom' /etc/default/rng-tools
systemctl enable haveged
systemctl enable rng-tools
systemctl restart rng-tools

rng-tools 和 haveged默认配置文件路径


/etc/default/rng-tools
/etc/default/haveged

参考来源:
https://www.vvave.net/archives/linux/use-haveged-or-rng-tools-to-speed-up-entropy-for-random-number-generation-on-gnu.html
https://zh.wikipedia.org/wiki//dev/random

此处评论已关闭