# 前言

一篇简单的 OpenSSL CLI 随机数生成器使用经验,不定期更新。


# 获取帮助

openssl rand -h

输出如下:

Usage: rand [options] num
General options:
 -help               Display this summary
 -engine val         Use engine, possibly a hardware device
Output options:
 -out outfile        Output file
 -base64             Base64 encode output
 -hex                Hex encode output
Random state options:
 -rand val           Load the given file(s) into the random number generator
 -writerand outfile  Write random data to the specified file
Provider options:
 -provider-path val  Provider load path (must be before 'provider' argument if required)
 -provider val       Provider to load (can be specified multiple times)
 -propquery val      Property query used when fetching algorithms
Parameters:
 num                 Number of bytes to generate

# 生成随机数

一个最基本的 OpenSSL rand 指令大致是这样的:

openssl rand -hex 32

这个指令让 OpenSSL 生成一个 32 字节(256 位)的随机数,并以 16 进制的形式进行输出。

一个输出示例是这样:

993500b078f18f45a87176f27b75a836d55a674de4981eec9c3016b7c40adb81

# 总体选项


# -help 或 -h

获取帮助,例如:

openssl rand -help

或:

openssl rand -h

个人使用的 OpenSSL 版本是 3.1.2,它的输出如下:

Usage: rand [options] num
General options:
 -help               Display this summary
 -engine val         Use engine, possibly a hardware device
Output options:
 -out outfile        Output file
 -base64             Base64 encode output
 -hex                Hex encode output
Random state options:
 -rand val           Load the given file(s) into the random number generator
 -writerand outfile  Write random data to the specified file
Provider options:
 -provider-path val  Provider load path (must be before 'provider' argument if required)
 -provider val       Provider to load (can be specified multiple times)
 -propquery val      Property query used when fetching algorithms
Parameters:
 num                 Number of bytes to generate

# engine

使用指定的引擎来产生随机数。

你可以首先尝试使用 OpenSSL 的 engine 指令来查一下本机支持的引擎:

openssl engine -t

如果你的机器是 Intel CPU,那么一般会有 RDRAND 引擎,输出类似于这样:

(rdrand) Intel RDRAND engine
     [ available ]
(dynamic) Dynamic engine loading support
     [ unavailable ]

那么此时你可以使用 Intel 的 RDRAND 引擎作为熵源之一来生成随机数,例如:

openssl rand -engine rdrand -hex 32

一个示例输出如下:

Engine "rdrand" set.
7ad8327169d40997c58d350f7e03d6805b2de240303ab5501fe7081719e8e150

# 输出选项


# -out

把生成的随机数据写入到指定的位置,例如,写入到 rand.bin 文件中:

openssl rand -out rand.bin 32

它会向 rand.bin 写入 32 字节(256 位)的随机数据。


# -base64

输出以 Base64 进行编码,例如:

openssl rand -base64 32

一个示例输出为:

LyAhQ/wFwbvpAhibZUb1zUbQWyKQ/DNgjDO5A+cmgsI=

# -hex

输出为 16 进制,例如:

openssl rand -hex 32

示例输出为:

LyAhQ/wFwbvpAhibZUb1zUbQWyKQ/DNgjDO5A+cmgsI=

# 随机状态选项


# -rand

把指定的文件加入到随机数生成器的熵源当中,例如:

openssl rand -base64 -rand rand.bin 32

示例输出为:

VwphXVGWk+ImerchS+rlR6VCy6EFNuiqjV9NU88Ty1Y=

# -writerand

向指定文件写入随机数据,例如:

openssl rand -writerand rand.bin 32

它会向 rand.bin 写入 32 字节(256 位)的随机数据。


# 参数

# num

附在指令的最后,单位为字节,代表希望生成的随机数长度,例如:

openssl rand 32

这代表生成 32 字节(256 位)的随机数。