【发布时间】:2020-03-21 21:24:45
【问题描述】:
我正在使用Otp.NET 库来生成和验证 OTP。我想使用 TOTP 算法。生成的 OTP 需要 5 分钟有效。该库建议为此使用var totp = new Totp(secretKey, step: 300);。但是OTP在5分钟前就失效了
完整代码
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);
}
【问题讨论】:
-
您的代码运行良好。也许您误解了 300 秒的有效期是什么意思。这是最大的时间范围。如果您在该帧的末尾
ComputeTotp,您的result可能会在一秒钟内过期。为了克服这个问题,您可以设置window参数 (var window = new VerificationWindow(previous:1, future:1);)。
标签: c# two-factor-authentication one-time-password totp