-
-
Notifications
You must be signed in to change notification settings - Fork 0
Basic example
Eugene Fox edited this page Sep 18, 2024
·
1 revision
This tutorial shows a basic example of how to use the library.
using SimpleOTP;
// Create a new secret
// Make sure to dispose of the secret after use
using OtpSecret secret = OtpSecret.CreateNew();
// Create a new generator
Otp generator = new Totp(secret);
// Optionally, you can customize default options
// generator.Period = 30;
// generator.Digits = 6;
// generator.Algorith = OtpAlgorithm.SHA1;
// Generate the code
OtpCode code = generator.Generate(); // { _value = 1234, _digits = 6, CanExpire = true, ExpirationTime = <current date + 30 seconds> }
Console.WriteLine(code); // 012345
// Verify the code
generator.Validate(code); // True
await Task.Delay(30000); // 30 seconds
generator.Validate(code); // False
generator.Validate(code, new ToleranceSpan(behind: 1, ahead: 3)); // True
// Create new config
OtpConfig config = new("user@example.com", "My app");
// Optionally, you can set pre-generated secret and customize other properties
// OtpConfig config = new("user@example.com", "My app", secret);
// config.Algorithm = OtpAlgorithm.SHA256;
// config.Digits = 8;
// ...
// Create a URI
Uri uri = config.ToUri();
Console.WriteLine(uri); // otpauth://totp/user@example.com?secret=KRUGKIDROVUWG2ZAMJZG653OEBTG66BO&issuer=My%20app
// Read config from URI
OtpConfig config2 = OtpConfig.Parse(uri);
Console.WriteLine(config == config2); // True
// Make sure to dispose of created secrets
config.Secret.Dispose();
config2.Secret.Dispose();©2025 Eugene Fox. Licensed under MIT license