I would like to generate an OTP 6-digit pin in my C# .NET Application. However, for security reasons, I heard that using the Random() package to perform this action might not be the most appropriate. Are there any other methods available?
You definitely want to use something in the System.Security.Cryptography namespace if you want something more secure than System.Random.
Here's a handy implementation written by Eric Lippert in his fabulous Fixing Random series.
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;
}
}
}
Now you can easily create a OTP string:
string otp = (BetterRandom.NextInt() % 1000000).ToString("000000");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With