随机数是密码学的基石。密钥、IV、盐值、Session ID 等都需要高质量的随机数。OpenSSL 的 rand 命令是生成密码学安全随机数的实用工具。

基本语法

1
openssl rand [选项] 字节数

常用选项:

  • -hex:输出十六进制格式
  • -base64:输出 Base64 编码格式
  • -out <文件>:输出到文件

常用示例

生成十六进制随机数

1
2
# 生成 16 字节(128 位)的十六进制随机数
openssl rand -hex 16

输出示例:

1
5254ce50aaf9b31ae6c6ecf2ef75f4de

生成 Base64 随机数

1
2
# 生成 32 字节(256 位)的 Base64 随机数
openssl rand -base64 32

输出示例:

1
n8EZAZAQ4PL60cFHcP0KIeT8dlhsa8m1K8QP1dQVnlQ=

生成不同长度的随机数

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# 8 字节(64 位)
openssl rand -hex 8
# 输出:67194de56e50d52b

# 32 字节(256 位)
openssl rand -hex 32
# 输出:7be8420779779ecd1253f6be94e7d717b9a75e7aa5d0767c95414e8f811d6b29

# 64 字节(512 位)
openssl rand -hex 64

实战场景

1. 生成密钥文件

用于对称加密的密钥文件:

1
2
3
4
5
# 生成 32 字节(256 位)AES 密钥
openssl rand -hex 32 > aes_key.txt

# 或 Base64 格式
openssl rand -base64 32 > aes_key_b64.txt

2. 生成初始化向量(IV)

对称加密需要随机 IV:

1
2
3
4
5
# AES-128-CBC 需要 16 字节 IV
openssl rand -hex 16

# AES-256-GCM 需要 12 字节 IV(GCM 推荐 12 字节)
openssl rand -hex 12

3. 生成密码盐值

密码哈希需要随机盐值:

1
2
# 生成 16 字节盐值
openssl rand -hex 16

4. 生成 Session Ticket 密钥

Nginx SSL Session Ticket 需要 80 字节密钥:

1
2
3
# 生成 Session Ticket 密钥
openssl rand 80 > /etc/nginx/ssl/ticket.key
chmod 600 /etc/nginx/ssl/ticket.key

5. 生成 API Token

1
2
# 生成 32 字节的 API Token
openssl rand -hex 32

6. 生成数据库密码

1
2
# 生成 24 字节的随机密码(Base64 格式)
openssl rand -base64 24

字节数 vs 位数

注意区分字节数位数

命令 字节数 位数 十六进制长度
openssl rand -hex 8 8 64 16 字符
openssl rand -hex 16 16 128 32 字符
openssl rand -hex 32 32 256 64 字符

十六进制输出长度 = 字节数 × 2。

输出格式对比

格式 优点 缺点 适用场景
十六进制 纯文本,易于复制 长度翻倍 密钥、IV、盐值
Base64 更紧凑,支持二进制 包含特殊字符 API Token、密码
二进制 最紧凑 不便于文本传输 文件、管道

安全性说明

OpenSSL rand 使用密码学安全的伪随机数生成器(CSPRNG):

  • 基于 OpenSSL 的熵池
  • 从操作系统获取熵(/dev/urandom 或等效源)
  • 适用于密码学场景

注意:不要使用普通的 rand()Math.random(),它们不是密码学安全的。

与其他工具对比

工具 安全性 说明
openssl rand ✅ 安全 密码学安全随机数
/dev/urandom ✅ 安全 操作系统随机源
/dev/random ✅ 安全 可能阻塞等待熵
head /dev/urandom | xxd ✅ 安全 需要额外工具
bash $RANDOM ❌ 不安全 仅 15 位,不用于密码学

完整示例脚本

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#!/bin/bash
# 生成各类密码学参数

echo "=== 密钥文件 ==="
openssl rand -hex 32

echo "=== 初始化向量(IV)==="
openssl rand -hex 16

echo "=== 盐值 ==="
openssl rand -hex 16

echo "=== API Token ==="
openssl rand -hex 32

echo "=== 数据库密码 ==="
openssl rand -base64 24

echo "=== Session Ticket 密钥(80 字节)==="
openssl rand -hex 80

小结

需求 命令
16 字节十六进制 openssl rand -hex 16
32 字节 Base64 openssl rand -base64 32
输出到文件 openssl rand -hex 32 -out key.txt
Session Ticket 密钥 openssl rand 80 > ticket.key

OpenSSL rand 是生成密码学安全随机数的可靠工具,适用于密钥、IV、盐值、Token 等各类场景。

参考来源