我想在我的 C# .NET 應用程式中生成一個 OTP 6 位 pin。但是,出于安全原因,我聽說使用 Random() 包來執行此操作可能不是最合適的。還有其他可用的方法嗎?
uj5u.com熱心網友回復:
如果您想要System.Security.Cryptography比System.Random.
這是 Eric Lippert 在他精彩的Fixing Random系列中撰寫的一個方便的實作。
public static class BetterRandom
{
private static readonly ThreadLocal<System.Security.Cryptography.RandomNumberGenerator> crng = new ThreadLocal<System.Security.Cryptography.RandomNumberGenerator>(System.Security.Cryptography.RandomNumberGenerator.Create);
private static readonly ThreadLocal<byte[]> bytes = new ThreadLocal<byte[]>(() => new byte[sizeof(int)]);
public static int NextInt()
{
crng.Value.GetBytes(bytes.Value);
return BitConverter.ToInt32(bytes.Value, 0) & int.MaxValue;
}
public static double NextDouble()
{
while (true)
{
long x = NextInt() & 0x001FFFFF;
x <<= 31;
x |= (long)NextInt();
double n = x;
const double d = 1L << 52;
double q = n / d;
if (q != 1.0)
return q;
}
}
}
現在您可以輕松創建 OTP 字串:
string otp = (BetterRandom.NextInt() % 1000000).ToString("000000");
uj5u.com熱心網友回復:
生成 6 位 OTP 的一種方法是使用加密安全偽亂數生成器 (CSPRNG)。CSPRNG 是一種亂數生成器,旨在抵御試圖預測將生成的數字的攻擊者。
一種流行的 CSPRNG 是 Microsoft 加密服務提供程式 (CSP) 亂數生成器。要使用此 CSPRNG,您可以呼叫該System.Security.Cryptography.RNGCryptoServiceProvider.GetBytes方法,傳入要生成的位元組數。此方法將回傳一個位元組陣列,然后您可以通過獲取前 6 個位元組并將它們轉換為十六進制來將其轉換為一個 6 位數字的字串。
另一種選擇是使用System.Random該類,但只有當您確定您使用的種子值是真正隨機的并且攻擊者無法預測時,您才應該這樣做。
uj5u.com熱心網友回復:
這對我有用:
public static string GetRandomOneTimePin()
{
char[] chars = new char[10];
chars = "1234567890".ToCharArray();
byte[] data = new byte[1];
using(var crypto = RandomNumberGenerator.Create())
{
crypto.GetNonZeroBytes(data);
data = new byte[6];
crypto.GetNonZeroBytes(data);
}
StringBuilder result = new StringBuilder(6);
foreach(byte b in data)
{
result.Append(chars[b % (chars.Length)]);
}
return result.ToString();
}
但是建議將 OTP 分配給特定目的地,即。手機號碼/電子郵件,您可以對其進行額外驗證。然后還為 OTP 分配了一個短暫的到期時間。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/533354.html
標籤:C#。网
下一篇:在最小API中設定身份驗證端點類
