三種隨機數產生器比較
| 類別 | 命名空間 | 特性 | 適用場景 |
| Random | System | 偽隨機、高速、非加密安全 | 遊戲、測試資料、非安全業務 |
| RandomNumberGenerator | System.Security.Cryptography | 密碼學安全隨機 (CSPRNG)、較慢 | Token、密碼、Session ID、加密金鑰 |
| Random.Shared (.NET 6+) | System | 執行緒安全、單例、偽隨機 | 高併發非安全隨機需求 |
通用隨機工具類別
using System;
using System.Security.Cryptography;
using System.Text;
public static class RandomUtil
{
private const string Digits = "0123456789";
private const string LettersUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private const string LettersLower = "abcdefghijklmnopqrstuvwxyz";
private const string Special = "!@#$%^&*_-+=";
/// 產生指定長度的純數字隨機碼
public static string Numeric(int length, bool crypto = false)
=> Generate(length, Digits, crypto);
/// 產生英數混合隨機碼
public static string Alphanumeric(int length, bool crypto = false)
=> Generate(length, Digits + LettersUpper + LettersLower, crypto);
/// 產生含特殊符號的強密碼
public static string StrongPassword(int length = 16, bool requireSpecial = true)
{
if (length < 8) throw new ArgumentException("強密碼長度至少 8");
var charset = Digits + LettersUpper + LettersLower + (requireSpecial ? Special : "");
return Generate(length, charset, crypto: true);
}
/// 產生 GUID 字串 (無連字號)
public static string Guid32() => Guid.NewGuid().ToString("N");
/// 核心產生邏輯
private static string Generate(int length, string charset, bool crypto)
{
if (length <= 0) return string.Empty;
if (string.IsNullOrEmpty(charset)) throw new ArgumentException("字元集不可為空");
char[] buffer = new char[length];
int maxIndex = charset.Length - 1;
if (crypto)
{
using (var rng = RandomNumberGenerator.Create())
{
byte[] bytes = new byte[length * 4]; // 取足夠熵
rng.GetBytes(bytes);
for (int i = 0; i < length; i++)
{
// 取 4 bytes 組成 uint,避免模數偏差
uint rand = BitConverter.ToUInt32(bytes, i * 4);
buffer[i] = charset[(int)(rand % (uint)charset.Length)];
}
}
}
else
{
// .NET 6+ 使用 Random.Shared,舊版需自行管理 static Random 實例
var rnd = Random.Shared;
for (int i = 0; i < length; i++)
buffer[i] = charset[rnd.Next(0, charset.Length)];
}
return new string(buffer);
}
/// 產生指定範圍內的隨機整數 [min, max]
public static int NextInt(int min, int max, bool crypto = false)
{
if (min > max) throw new ArgumentException("min 不可大於 max");
if (crypto)
{
using (var rng = RandomNumberGenerator.Create())
{
byte[] bytes = new byte[4];
rng.GetBytes(bytes);
uint rand = BitConverter.ToUInt32(bytes, 0);
return (int)(min + (rand % (uint)(max - min + 1)));
}
}
return Random.Shared.Next(min, max + 1);
}
/// 洗牌演算法 (Fisher-Yates)
public static void Shuffle(T[] array, bool crypto = false)
{
var rnd = crypto ? null : Random.Shared;
for (int i = array.Length - 1; i > 0; i--)
{
int j = crypto ? NextInt(0, i, true) : rnd.Next(i + 1);
(array[i], array[j]) = (array[j], array[i]);
}
}
}
使用範例
// 6 位數字驗證碼
string otp = RandomUtil.Numeric(6);
// 10 碼英數混合序號
string sn = RandomUtil.Alphanumeric(10);
// 16 碼強密碼 (含特殊符號)
string pwd = RandomUtil.StrongPassword(16);
// 密碼學安全隨機整數 1~10000
int lucky = RandomUtil.NextInt(1, 10000, crypto: true);
// 打亂陣列
var items = new[] { "A", "B", "C", "D", "E" };
RandomUtil.Shuffle(items, crypto: true);
效能與安全性選擇指南
- **驗證碼、OTP、重設密碼 Token** → `crypto: true` (CSPRNG)。
- **測試資料、遊戲骰子、顯示順序隨機化** → `crypto: false` (高速 `Random`)。
- **高併發環境** → .NET 6+ 直接用 `Random.Shared`;舊版自行實作 `ThreadLocal` 避免鎖競爭。