OpenSSLで乱数生成
概要
OpenSSLが提供しているC言語のAPIを使って乱数を生成します。OpenSSLのマニュアルを見ると,OpenSSLは信頼されたエントロピーソースからのシードを提供された場合には,256bitのセキュリティレベルをサポートすると書いてあります。
メジャーなプラットホームでは,OSの乱数生成機能を使ってエントロピーソースを取得しています。
利用するAPI
乱数生成を実行するためのAPIを使います。
- RAND_bytes()
乱数を生成します。
乱数の生成はこの関数を実行するだけでOKです。
サンプルプログラム
乱数生成のサンプルプログラムです。16Byteの乱数を生成して画面に表示します。
#include "openssl/rand.h"
#include "openssl/err.h"
int PrintBytes(unsigned char* bytes, unsigned int bytesLen)
{
printf("Data is: 0x");
for (int i = 0; i < bytesLen; i++)
printf("%02x ", *bytes++);
printf("\n");
return 1;
}
int main()
{
unsigned char buffer[256];
int len = 16;
int ret = 0;
/* 乱数を10回生成してプリントする */
for (int i = 0; i < 10; i++) {
ret = RAND_bytes(buffer, len);
if (1 != ret) {
/* error */
printf("Error: %s\n", ERR_reason_error_string(ERR_get_error()));
break;
}
PrintBytes(buffer, len);
memset(buffer, 0x00, sizeof(buffer));
}
}
実行結果
10回乱数を生成した結果です。それっぽい乱数列が出力されています。
Data is: 0x8d f5 6f 6d c7 28 78 47 1a 27 5d a6 aa 56 21 d7
Data is: 0xfd d7 2a 5c fa 01 cb 1c b2 59 aa a4 4b 02 d8 9d
Data is: 0x78 10 68 13 32 59 b4 79 fc 56 58 11 7d dd 85 d0
Data is: 0xa7 7a 2b a0 b0 34 54 23 e7 f1 69 91 13 5e c2 5e
Data is: 0xf6 4a 88 99 76 cb b1 98 87 70 d3 1d 0e 39 ba 86
Data is: 0x04 90 44 97 79 7e 32 f0 fc 96 c6 44 3d b3 a8 f3
Data is: 0x51 15 ff 1e 5b d5 a5 af 4b cc ee 0a 45 db 13 7d
Data is: 0x39 9a 99 0b 8d e4 b8 37 29 4b 0e 93 16 1f 74 2b
Data is: 0x7b 29 ae 7a d5 34 5d b2 07 b9 5e 53 21 58 b2 bc
Data is: 0xfb ab 35 62 33 7c 8d 7d 22 da 9f b5 f4 0b 26 92