OTP code generation and validation with otp.net
Asked Answered
E

3

11

I'm using the Otp.NET library to generate and validate an OTP. I want to use the TOTP algorithm. The generated OTP needs to be valid for 5 minutes. The library is recommending to use var totp = new Totp(secretKey, step: 300); for this. But the OTP is getting invalid before 5 minutes

Complete code

public static void GenarateTOTP()
        {
            var bytes = Base32Encoding.ToBytes("JBSWY3DPEHPK3PXP");

            var totp = new Totp(bytes, step: 300);

            var result = totp.ComputeTotp(DateTime.UtcNow);

            Console.WriteLine(result);

            var input = Console.ReadLine();
            long timeStepMatched;
            bool verify = totp.VerifyTotp(input, out timeStepMatched, window: null);

            Console.WriteLine("{0}-:{1}", "timeStepMatched",timeStepMatched);
            Console.WriteLine("{0}-:{1}", "Remaining seconds", totp.RemainingSeconds());
            Console.WriteLine("{0}-:{1}", "verify", verify);

        } 
Everybody answered 26/11, 2019 at 12:44 Comment(2)
You're code works perfectly fine. Maybe you're mistaken what a validity of 300sec means. It's the maximum timeframe. If you ComputeTotp at the end of that frame your result might expire within a second. To overcome this you may set the window parameter (var window = new VerificationWindow(previous:1, future:1);).Arnhem
On my side the code based on yours works in 99% cases. But sometime VerifyTotp() returns false, and I don't understand why. Do you have an idea what's wrong with my version of code? dotnetfiddle.net/IOQhMhFuqua
A
2

Check the format for URI https://github.com/google/google-authenticator/wiki/Key-Uri-Format

You can generate QR Code for test with this page 2FA QR Code Generator

If you use Google Authenticator, Microsoft Authenticator, Twilio Authy for generate codes. When you capture the QR Code with the TOTP Uri.

These apps ignore

  • Period parameter it defaults to 30.
  • Algorithm parameter it defaults to SHA1.
  • Digits parameter it defaults to 6.

Your code is fine, as long as you use the same library to validate the otp code. If you use the code generation applications (Google Authenticator, Microsoft Authenticator, Authy) the validation will be incorrect, since they use the default values and ignore the parameters specified in the TOTP Uri.

Akihito answered 11/12, 2021 at 8:9 Comment(0)
B
0

I tested your code and the code has no problem and the generated otp is valid for up to 5 minutes. You can create a timer for further investigation. I think this part of document can help you :

In an ideal world both the client and the server's system time are correct to the second with NIST or other authoritative time standards. This would ensure that the generated code is always correct. If at all possible, sync the system time as closely as with NIST.

There are cases where this simply isn't possible. Perhaps you are writing an app to generate codes for use with a server who's time is significantly off. You can't control the erroneous time of the server. You could set your system clock to match but then your time would be off significantly which isn't the desired result. There is a class called TimeCorrection that helps with these cases.

A time correction object creates an offset that can be used to correct (at least for the purposes of this calculation) the time relative to the incorrect system time. It is created as follows

var correction = new TimeCorrection(correctTime); Where the correct time parameter is a DateTime object that represents the current correct (at least for the purposes of verification) UTC time. For this to work there needs to be some way to get an instance of the current acceptable time. This could be done with an NTP (NTP with NIST is coming soon in this library) or looking for a Date response header from an HTTP request or some other way.

Once this instance is created it can be used for a long time as it always will use the current system time as a base to apply the correction factor. The object is threadsafe and thus can be used by multiple threads or web requests simultaneously.

There is an overload that takes both the correct time and the reference time to use as well. This can be used in cases where UTC time isn't used.

The Totp class constructor can take a TimeCorrection object that will be applied to all time calculations and verifications.

var totp = new Totp(secretKey, timeCorrection: correction);

Barclay answered 11/12, 2021 at 7:8 Comment(0)
R
-3
string[]    arr      =   {  "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"  };
string      IDString =    "";
string      temp;
Random      rand      = new Random();
for (int i = 0; i < 4; i++) 
    {
          temp        = arr[rand.Next(0, arr.Length)];
          IDString   += temp;
          NewPassword = IDString;
    }
Console.WriteLine("OTP=" + NewPassword);
Recuperative answered 1/12, 2022 at 7:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.