Announcement

👇Official Account👇

Welcome to join the group & private message

Article first/tail QR code

Skip to content

Lesson 3.4: 安全随机数

学习目标

  • 区分安全与非安全随机数

对比

go
// ❌ 不安全:math/rand(伪随机、可预测)
import "math/rand"
token := rand.Int63()  // 线性同余生成器,不适合安全场景

// ✅ 安全:crypto/rand(真随机、不可预测)
import "crypto/rand"
func generateToken() (string, error) {
    bytes := make([]byte, 32)
    _, err := rand.Read(bytes)
    if err != nil {
        return "", err
    }
    return hex.EncodeToString(bytes), nil
}
特性math/randcrypto/rand
随机性伪随机密码学安全
可预测性已知种子可预测不可预测
性能较慢
用途模拟、游戏Token、密钥、密码

上次更新于: