2013/08/21

Raspberry Pi的硬體亂數產生器

還記得在C語言標準程式庫裡的int rand()與srand(unsigned int seed),可產生虛擬亂數(pseudorandom number,或稱假亂數),為了每次都能得到不同的序列,通常需先srand(time(NULL))然後再呼叫rand()得到亂數,但畢竟只是假亂數了,不是真真正正的亂數,真亂數必須以類比元件的熱雜訊(thermal noise)作為熵源(entrypy source),

Raspberry Pi的主晶片裡頭其實擁有硬體亂數產生器(hardware random number generator),而新版的韌體加入了此功能,請以底下指令更新韌體(最好先備份記憶卡),

$ sudo rpi-update
(我使用2013-07-26-wheezy-raspbian.zip,便不需要作此動作。)

然後載入硬體亂數的模組,

$ sudo modprobe bcm2708-rng

便可從/dev/hwrng取得亂數。

若想要讓系統自動載入該模組,請修改/etc/modules,加入底下這行:

bcm2708-rng

另外,可安裝rng-tools這個套件,

$ sudo apt-get install rng-tools

它裡頭也包含了rngd這個亂數服務,安裝後便會自動啟動,

Starting Hardware RNG entropy gatherer daemon: rngd.

rngd會利用熵源(/dev/hwrng)將亂數放進/dev/random與/dev/urandom。

以底下指令可進行測試(根據FIPS 140-2標準)是否為真亂數,

$ sudo cat /dev/hwrng | rngtest -c 1000
rngtest 2-unofficial-mt.14
Copyright (c) 2004 by Henrique de Moraes Holschuh
This is free software; see the source for copying conditions.  There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

rngtest: starting FIPS tests...
rngtest: bits received from input: 20000032
rngtest: FIPS 140-2 successes: 999
rngtest: FIPS 140-2 failures: 1
rngtest: FIPS 140-2(2001-10-10) Monobit: 0
rngtest: FIPS 140-2(2001-10-10) Poker: 0
rngtest: FIPS 140-2(2001-10-10) Runs: 1
rngtest: FIPS 140-2(2001-10-10) Long run: 0
rngtest: FIPS 140-2(2001-10-10) Continuous run: 0
rngtest: input channel speed: (min=75.254; avg=1068.674; max=1953125.000)Kibits/s
rngtest: FIPS tests speed: (min=843.573; avg=4171.791; max=8247.994)Kibits/s
rngtest: Program run time: 23315840 microseconds

但因為資料的亂數特性,有可能得到少量的failures。

嗯,有了真亂數,可以幹些什麼呢?


參考資料:

2 comments:

  1. 你好,請問這要怎麼在程式中使用呢?

    ReplyDelete
    Replies
    1. 一般程式會去讀取/dev/urandom吧。

      Delete