Skip to content

Commit 0c9eb9a

Browse files
committed
refactor: 完善实现类
1 parent e2a9b39 commit 0c9eb9a

1 file changed

Lines changed: 39 additions & 1 deletion

File tree

src/components/BootstrapBlazor.Authenticator/Services/DefaultAuthenticatorServices.cs

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,10 @@
77

88
namespace BootstrapBlazor.Components;
99

10-
internal class DefaultAuthenticatorServices(IOptionsMonitor<AuthenticatorOptions> optionsMonitor) : IAuthenticatorService
10+
class DefaultAuthenticatorServices(IOptionsMonitor<AuthenticatorOptions> optionsMonitor) : IAuthenticatorService
1111
{
12+
public TOTPInstance? TOTPInstance { get; private set; }
13+
1214
public string GenerateOtpUri(AuthenticatorOptions? options = null)
1315
{
1416
options ??= optionsMonitor.CurrentValue;
@@ -17,4 +19,40 @@ public string GenerateOtpUri(AuthenticatorOptions? options = null)
1719
var uri = new OtpUri(type, options.SecretKey, options.UserName, options.IssuerName, mode, options.Digits, options.Period, options.Counter);
1820
return uri.ToString();
1921
}
22+
23+
public string ComputeTotp(string secretKey, DateTime? timestamp = null)
24+
{
25+
var totp = new Totp(Base32Encoding.ToBytes(secretKey));
26+
TOTPInstance = new DefaultTOTPInstance(totp);
27+
return timestamp == null ? totp.ComputeTotp() : totp.ComputeTotp(timestamp.Value);
28+
}
29+
30+
public int GetRemainingSeconds(DateTime? timestamp = null)
31+
{
32+
if (TOTPInstance != null)
33+
{
34+
return timestamp == null ? TOTPInstance.GetRemainingSeconds() : TOTPInstance.GetRemainingSeconds(timestamp.Value);
35+
}
36+
var totp = new Totp(Base32Encoding.ToBytes("OMM2LVLFX6QJHMYI"));
37+
return timestamp == null ? totp.RemainingSeconds() : totp.RemainingSeconds(timestamp.Value);
38+
}
39+
40+
public string GenerateSecretKey(int length = 20)
41+
{
42+
var secretKey = KeyGeneration.GenerateRandomKey(length);
43+
return Base32Encoding.ToString(secretKey);
44+
}
45+
46+
public byte[] GetSecretKeyBytes(string input)
47+
{
48+
return Base32Encoding.ToBytes(input);
49+
}
50+
}
51+
52+
class DefaultTOTPInstance(Totp totp) : TOTPInstance
53+
{
54+
public override int GetRemainingSeconds(DateTime? timestamp = null)
55+
{
56+
return timestamp == null ? totp.RemainingSeconds() : totp.RemainingSeconds(timestamp.Value);
57+
}
2058
}

0 commit comments

Comments
 (0)