我想在我的 C# .NET 应用程序中生成 OTP 6 位引脚。但是,出于安全原因,我听说使用 Random() 包来执行此操作可能不是最合适的。还有其他方法可用吗?
如果您想要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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在您可以轻松创建 OTP 字符串:
string otp = (BetterRandom.NextInt() % 1000000).ToString("000000");
Run Code Online (Sandbox Code Playgroud)