Search code examples
c#securitytwo-factor-authenticationmulti-factor-authentication

Securely Generate 6 MFA Pin


I'm trying to Generate a 6 digit code to be used for 2 factor authentication, at a first glance I might do something like this:

Random random = new Random();
var securitycode = random.Next(1000000, 10000000);

However this seems somewhat insecure to me because, there probably is a way to predict the next number if you can figure out the seeds by grabbing alot of security codes.

I'm thinking there is a better way to get a secure code using RNGCryptoServiceProvider but i'm a bit confused on how I can assure that the code generated is 6 digits

private string GenerateSecurityCode(int length)
{
    var provider = new RNGCryptoServiceProvider();
    var byteArray = new byte[8];
    provider.GetBytes(byteArray);
    var code = BitConverter.ToUInt32(byteArray, 0);
    //how can I assure the code is 6 digits
}

Is this a secure way to generate MFA Codes, if not what would be a good method for Generating numeric codes?


Solution

  • I've just modulo the bytes now to return the code:

    private string GenerateSecurityCode()
    {
        var buffer = new byte[sizeof(UInt64)];
        var cryptoRng = new RNGCryptoServiceProvider();
        cryptoRng.GetBytes(buffer);
        var num = BitConverter.ToUInt64(buffer, 0);
        var code = num % 1000000;
        return code.ToString("D6");
    }