Otp.NET库TOTP验证窗口配置异常问题求助
Otp.NET TOTP验证码长期有效期配置未达预期
我使用Otp.NET库实现TOTP生成与验证,需求是让生成的TOTP验证码有效期可达7天,但测试代码未达到预期效果。
测试代码
using OtpNet; using System; // 用于TOTP的密钥(所有测试需保持一致) byte[] secretKey = Base32Encoding.ToBytes("JBSWY3DPEHPK3PXP"); // 创建Totp实例 Totp totpGenerator = new Totp(secretKey); // 模拟在当前时间生成TOTP DateTime generationTime = DateTime.Now; string totpCode = totpGenerator.ComputeTotp(generationTime); Console.WriteLine($"TOTP generated on {generationTime}: {totpCode}"); // 测试不同时间点的验证结果 TestTotpValidity(totpCode, generationTime.AddDays(5)); // 5天后验证,预期有效但实际无效 TestTotpValidity(totpCode, generationTime.AddDays(-5)); // 5天前验证,预期无效但实际有效 TestTotpValidity(totpCode, generationTime.AddDays(7)); // 7天后验证,预期有效但实际无效 TestTotpValidity(totpCode, generationTime.AddDays(-7)); // 7天前验证,预期无效但实际有效 TestTotpValidity(totpCode, generationTime.AddDays(8)); // 8天后验证,预期无效且实际无效 TestTotpValidity(totpCode, generationTime.AddDays(-8)); // 8天前验证,预期无效且实际无效 void TestTotpValidity(string totpCode, DateTime verificationTime) { var validator = new Totp(secretKey); long timeStepMatched; // 自定义验证窗口:每天2880个时间步长,预期覆盖7天有效期 bool isValid = validator.VerifyTotp(verificationTime, totpCode, out timeStepMatched, new VerificationWindow(previous: 2, future: 2880 * 7)); Console.ForegroundColor = isValid ? ConsoleColor.DarkGreen : ConsoleColor.DarkRed; Console.WriteLine($"Verifying TOTP on {verificationTime} (time step matched {timeStepMatched}): {isValid}"); Console.ResetColor(); }
控制台输出
TOTP generated on 05/16/2024 10:08:22: 935002 39;49mVerifying TOTP on 05/21/2024 10:08:22 (time step matched 0): False [39;49m[39;49mVerifying TOTP on 05/11/2024 10:08:22 (time step matched 57195136): True [39;49m[39;49mVerifying TOTP on 05/23/2024 10:08:22 (time step matched 0): False [39;49m[39;49mVerifying TOTP on 05/09/2024 10:08:22 (time step matched 57195136): True [39;49m[39;49mVerifying TOTP on 05/24/2024 10:08:22 (time step matched 0): False [39;49m[39;49mVerifying TOTP on 05/08/2024 10:08:22 (time step matched 0): False [39;49m
补充说明
- 生成与验证使用不同的Totp实例,理论上应支持任意时间点的验证
- 最终需求是实现单次验证,但当前需先确保验证窗口配置正确,预期当日生成的TOTP可在7天内有效
请问我是否误解了库的文档内容,或是代码存在错误?
内容的提问来源于stack exchange,提问作者Iker Ocio Zuazo
相关产品推荐
相关产品推荐

