From 42f968171bf1313bb39f867cffbb732e8efd6a87 Mon Sep 17 00:00:00 2001 From: Eugene Fox Date: Sun, 5 Dec 2021 20:44:17 +0000 Subject: [PATCH] Fixed invalid code generation on formatted secrets --- SimpleOTP.Test/OTPServiceUnitTest.cs | 25 +++++++++++++++++++++++++ SimpleOTP/OTPService.cs | 2 +- SimpleOTP/SimpleOTP.csproj | 5 ++--- 3 files changed, 28 insertions(+), 4 deletions(-) diff --git a/SimpleOTP.Test/OTPServiceUnitTest.cs b/SimpleOTP.Test/OTPServiceUnitTest.cs index a5238bd..36b7be2 100644 --- a/SimpleOTP.Test/OTPServiceUnitTest.cs +++ b/SimpleOTP.Test/OTPServiceUnitTest.cs @@ -41,6 +41,31 @@ namespace SimpleOTP.Test Assert.AreEqual(293657, code.Code); } + /// + /// Test time-based OTP generator with customly formatted secret. + /// + [TestMethod("Secret format test")] + public void FormatTest() + { + Console.Write("Uppercase space-separated: "); + var config = totpConfig with { Secret = "JBSW Y3DP EHPK 3PXP" }; + var code = OTPService.GenerateCode(ref config, time); + Assert.AreEqual(160102, code.Code); + Console.WriteLine("Passed."); + + Console.Write("Lowercase space-separated: "); + config = totpConfig with { Secret = "jbsw y3dp ehpk 3pxp" }; + code = OTPService.GenerateCode(ref config, time); + Assert.AreEqual(160102, code.Code); + Console.WriteLine("Passed."); + + Console.Write("Lowercase: "); + config = totpConfig with { Secret = "jbswy3dpehpk3pxp" }; + code = OTPService.GenerateCode(ref config, time); + Assert.AreEqual(160102, code.Code); + Console.WriteLine("Passed."); + } + /// /// Test HOTP generator with pre-calculated code. /// diff --git a/SimpleOTP/OTPService.cs b/SimpleOTP/OTPService.cs index 789909e..fbc1154 100644 --- a/SimpleOTP/OTPService.cs +++ b/SimpleOTP/OTPService.cs @@ -48,7 +48,7 @@ namespace SimpleOTP /// public static OTPCode GenerateCode(ref OTPConfiguration target, DateTime date) { - byte[] keyBytes = Base32Encoder.Decode(target.Secret); + byte[] keyBytes = Base32Encoder.Decode(target.Secret.ToUpperInvariant().Replace(" ", string.Empty)); long counter = target.Type == OTPType.HOTP ? target.Counter : GetCurrentCounter(date.ToUniversalTime(), (int)target.Period.TotalSeconds); byte[] counterBytes = BitConverter.GetBytes(counter); diff --git a/SimpleOTP/SimpleOTP.csproj b/SimpleOTP/SimpleOTP.csproj index 93f655d..7c3b95f 100644 --- a/SimpleOTP/SimpleOTP.csproj +++ b/SimpleOTP/SimpleOTP.csproj @@ -12,7 +12,7 @@ SimpleOTP SimpleOTP - 1.2.2 + 1.2.3 .NET library for TOTP/HOTP implementation on server (ASP.NET) or client (Xamarin) side Eugene Fox FoxDev Studio @@ -22,8 +22,7 @@ https://github.com/XFox111/SimpleOTP en-US otp;totp;dotnet;hotp;authenticator;2fa;mfa;security;oath - - Fixed Base32 encoder -- Updated NuGet dependency packages + - Fixed invalid code generation with secrets which are lowercase or space-separated