Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a way to generate OTP 6-digit pin in C# .NET WCF? (without using Random())

Tags:

c#

.net

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?

like image 558
Jessica Avatar asked Oct 21 '25 06:10

Jessica


1 Answers

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");
like image 127
Enigmativity Avatar answered Oct 23 '25 19:10

Enigmativity



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!