### Install Otp.NET Package Source: https://github.com/kspearrin/otp.net/blob/master/README.md Instructions for installing the Otp.NET library using NuGet Package Manager or the .NET CLI. ```powershell Install-Package Otp.NET ``` ```bash dotnet add package Otp.NET ``` -------------------------------- ### Install Otp.NET Package Source: https://context7.com/kspearrin/otp.net/llms.txt Commands to install the Otp.NET library via .NET CLI or PowerShell. ```bash dotnet add package Otp.NET ``` ```powershell Install-Package Otp.NET ``` -------------------------------- ### Implement TOTP Setup and Verification in C# Source: https://context7.com/kspearrin/otp.net/llms.txt This snippet demonstrates a service class for handling 2FA lifecycle events. It includes methods for generating a random secret key, creating a provisioning URI for QR codes, and verifying user-provided TOTP codes with time-step tracking. ```csharp using OtpNet; public class TwoFactorAuthService { public TwoFactorSetupResult SetupTwoFactor(string userId, string email) { byte[] secretKey = KeyGeneration.GenerateRandomKey(OtpHashMode.Sha1); string base32Secret = Base32Encoding.ToString(secretKey); var otpUri = new OtpUri(OtpType.Totp, base32Secret, email, issuer: "MyApplication"); return new TwoFactorSetupResult { SecretKey = base32Secret, QrCodeUri = otpUri.ToString() }; } public VerificationResult VerifyCode(string base32Secret, string code, long? lastUsedTimeStep) { byte[] secretKey = Base32Encoding.ToBytes(base32Secret); var totp = new Totp(secretKey); bool isValid = totp.VerifyTotp(code, out long timeStepMatched, VerificationWindow.RfcSpecifiedNetworkDelay); if (!isValid) return new VerificationResult { Success = false, Error = "Invalid code" }; if (lastUsedTimeStep.HasValue && timeStepMatched <= lastUsedTimeStep.Value) return new VerificationResult { Success = false, Error = "Code already used" }; return new VerificationResult { Success = true, TimeStepUsed = timeStepMatched }; } } // Usage example var authService = new TwoFactorAuthService(); var setup = authService.SetupTwoFactor("user123", "user@example.com"); var result = authService.VerifyCode(setup.SecretKey, "123456", lastUsedTimeStep: null); ``` -------------------------------- ### Base32 Encoding and Decoding Source: https://github.com/kspearrin/otp.net/blob/master/README.md Provides examples for generating random keys, encoding them to Base32 strings, and decoding Base32 strings back to bytes. ```APIDOC ## Base32 Encoding and Decoding ### Description This section covers the utility functions for Base32 encoding and decoding, including generating random keys for OTP usage. ### Method `KeyGeneration.GenerateRandomKey`, `Base32Encoding.ToString`, `Base32Encoding.ToBytes` ### Endpoint N/A (Utility Class Methods) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```csharp using OtpNet; // Generate a random 20-byte key var keyBytes = KeyGeneration.GenerateRandomKey(20); // Encode the key to a Base32 string var base32String = Base32Encoding.ToString(keyBytes); // Decode the Base32 string back to bytes var decodedBytes = Base32Encoding.ToBytes(base32String); // Example of creating a Totp object with decoded bytes var otp = new Totp(decodedBytes); ``` ### Response #### Success Response (200) - **string** - The Base32 encoded string. - **byte[]** - The decoded byte array. #### Response Example ```json { "base32String": "JBSWY3DPEHPK3PXP", "decodedBytes": [74, 66, 83, 87, 89, 51, 68, 80, 69, 72, 80, 75, 51, 80, 88, 80] } ``` ``` -------------------------------- ### Generate OTP Authentication URIs Source: https://context7.com/kspearrin/otp.net/llms.txt This example shows how to generate standard OTP authentication URIs using the `OtpUri` class, which are compatible with applications like Google Authenticator. It covers creating URIs for both TOTP and HOTP, including specifying parameters like secret key, user, issuer, algorithm, digits, period, and counter. The generated URIs can be converted to `Uri` objects for QR code generation. ```csharp using OtpNet; // Generate a secret key byte[] secretKey = KeyGeneration.GenerateRandomKey(20); string base32Secret = Base32Encoding.ToString(secretKey); // Create a TOTP URI var totpUri = new OtpUri( OtpType.Totp, base32Secret, "user@example.com", issuer: "MyApp", algorithm: OtpHashMode.Sha1, digits: 6, period: 30 ); string uriString = totpUri.ToString(); Console.WriteLine(uriString); // Output: otpauth://totp/MyApp:user%40example.com?secret=JBSWY3DPEHPK3PXP&issuer=MyApp&algorithm=SHA1&digits=6&period=30 // Get as Uri object for QR code generation Uri uri = totpUri.ToUri(); // Create an HOTP URI var hotpUri = new OtpUri( OtpType.Hotp, secretKey, // Can pass byte array directly "user@example.com", issuer: "MyApp", algorithm: OtpHashMode.Sha1, digits: 6, counter: 0 ); Console.WriteLine(hotpUri.ToString()); // Output: otpauth://hotp/MyApp:user%40example.com?secret=JBSWY3DPEHPK3PXP&issuer=MyApp&algorithm=SHA1&digits=6&counter=0 // Access URI properties Console.WriteLine($"Type: {totpUri.Type}"); Console.WriteLine($"User: {totpUri.User}"); Console.WriteLine($"Issuer: {totpUri.Issuer}"); Console.WriteLine($"Algorithm: {totpUri.Algorithm}"); Console.WriteLine($"Digits: {totpUri.Digits}"); Console.WriteLine($"Period: {totpUri.Period}"); ``` -------------------------------- ### Data Structures for 2FA Source: https://context7.com/kspearrin/otp.net/llms.txt Defines the data structures used for returning setup information and verification results. ```APIDOC ## Data Structures for 2FA ### Description These classes represent the data structures used by the `TwoFactorAuthService` to return information about 2FA setup and verification results. ### Classes #### TwoFactorSetupResult ##### Description Holds the results of the 2FA setup process. ##### Properties - **SecretKey** (string) - The generated Base32 encoded secret key for the user. - **QrCodeUri** (string) - The OTP URI that can be used to generate a QR code for authenticator app enrollment. #### VerificationResult ##### Description Indicates the outcome of a TOTP code verification attempt. ##### Properties - **Success** (bool) - True if the code is valid and has not been reused, false otherwise. - **Error** (string) - A message describing the reason for failure, if `Success` is false. - **TimeStepUsed** (long) - The time step at which the code was successfully verified. This should be stored to prevent reuse of the same code. ``` -------------------------------- ### Get Remaining Time for TOTP Window Source: https://github.com/kspearrin/otp.net/blob/master/README.md Demonstrates how to check the remaining time in seconds for the current TOTP time step window. An overload allows specifying a custom DateTime. ```csharp using OtpNet; // Get remaining seconds for the current time window var remainingTime = totp.RemainingSeconds(); // Get remaining seconds for a specific timestamp var remainingSeconds = totp.RemainingSeconds(DateTime.UtcNow); ``` -------------------------------- ### Verify TOTP Code Source: https://github.com/kspearrin/otp.net/blob/master/README.md Provides examples of verifying a given TOTP code against the current time or a specified timestamp. The method returns a boolean indicating validity and an output parameter for the time window used. ```csharp using OtpNet; long timeWindowUsed; // Verify TOTP using current UTC time bool isValid = totp.VerifyTotp("123456", out timeWindowUsed); // Verify TOTP for a specific timestamp DateTime specificTimestamp = DateTime.UtcNow; bool isValidSpecific = totp.VerifyTotp(specificTimestamp, "123456", out timeWindowUsed); ``` -------------------------------- ### Create HOTP Object in C# Source: https://github.com/kspearrin/otp.net/blob/master/README.md Demonstrates how to instantiate an HOTP object with default settings, custom hash algorithms like Sha512, and custom digit lengths. ```csharp using OtpNet; var hotp = new Hotp(secretKey); var hotpSha512 = new Hotp(secretKey, mode: OtpHashMode.Sha512); var hotp8Digits = new Hotp(secretKey, hotpSize: 8); ``` -------------------------------- ### Configure Custom TOTP Settings Source: https://context7.com/kspearrin/otp.net/llms.txt Shows how to initialize a TOTP generator with custom hash algorithms, time steps, and code lengths. ```csharp using OtpNet; byte[] secretKey = KeyGeneration.GenerateRandomKey(OtpHashMode.Sha512); var totp = new Totp(secretKey, step: 15, mode: OtpHashMode.Sha512, totpSize: 8); string code = totp.ComputeTotp(); Console.WriteLine($"8-digit SHA-512 code: {code}"); ``` -------------------------------- ### Create TOTP Object with Default Settings Source: https://github.com/kspearrin/otp.net/blob/master/README.md Demonstrates the basic creation of a TOTP object using the default SHA1 hash mode and a 30-second time step. The secret key must be provided as a byte array. ```csharp using OtpNet; // Assuming secretKey is a byte[] representing your shared secret var totp = new Totp(secretKey); ``` -------------------------------- ### Create TOTP Object with Custom Settings Source: https://github.com/kspearrin/otp.net/blob/master/README.md Shows how to instantiate a TOTP object with custom configurations for hash algorithm (SHA512), time step (15 seconds), and TOTP code length (8 digits). ```csharp using OtpNet; // Example with SHA512, 15-second step, and 8-digit code var totp = new Totp(secretKey, step: 15, totpSize: 8, mode: OtpHashMode.Sha512); ``` -------------------------------- ### HOTP Object Creation Source: https://github.com/kspearrin/otp.net/blob/master/README.md Demonstrates how to create an HOTP object with default settings and how to customize it using different hash algorithms (SHA256, SHA512) and truncation levels. ```APIDOC ## HOTP Object Creation ### Description This section covers the creation of an HOTP object, including default initialization and customization options for hash algorithms and code length. ### Method Constructor ### Endpoint N/A (Class Constructor) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```csharp using OtpNet; // Default HOTP object creation var secretKey = "your_secret_key"; // Replace with your actual secret key var hotp = new Hotp(secretKey); // HOTP object creation with SHA512 hash mode var hotpSha512 = new Hotp(secretKey, mode: OtpHashMode.Sha512); // HOTP object creation with a specific truncation size (e.g., 8 digits) var hotpCustomSize = new Hotp(secretKey, hotpSize: 8); ``` ### Response #### Success Response (200) N/A (Object instantiation) #### Response Example N/A ``` -------------------------------- ### TOTP Initialization and Code Generation Source: https://github.com/kspearrin/otp.net/blob/master/README.md Explains how to instantiate a Totp object with custom hash modes, time steps, and digit sizes, and how to compute the current TOTP code. ```APIDOC ## TOTP Initialization and Computation ### Description Creates a new TOTP instance using a shared secret key and computes the current one-time password based on the system clock. ### Method Constructor / Method Call ### Parameters #### Constructor Parameters - **secretKey** (byte[]) - Required - The shared secret key. - **mode** (OtpHashMode) - Optional - Hash algorithm (Sha1, Sha256, Sha512). Default: Sha1. - **step** (int) - Optional - Time window in seconds. Default: 30. - **totpSize** (int) - Optional - Number of digits for the code. Default: 6. ### Request Example var totp = new Totp(secretKey, mode: OtpHashMode.Sha512, step: 30, totpSize: 6); ### Response #### Success Response (200) - **code** (string) - The generated TOTP code. ### Response Example "123456" ``` -------------------------------- ### Manage Secret Keys with InMemoryKey and IKeyProvider Source: https://context7.com/kspearrin/otp.net/llms.txt Shows how to wrap secret keys in an InMemoryKey object for use with TOTP and HOTP. It also demonstrates how to implement a custom IKeyProvider for scenarios like HSM or smart card integration. ```csharp using OtpNet; byte[] secretKey = KeyGeneration.GenerateRandomKey(20); var keyProvider = new InMemoryKey(secretKey); var totp = new Totp(keyProvider); string code = totp.ComputeTotp(); var hotp = new Hotp(keyProvider); string hotpCode = hotp.ComputeHOTP(0); byte[] data = new byte[] { 0x01, 0x02, 0x03, 0x04 }; byte[] hmac = keyProvider.ComputeHmac(OtpHashMode.Sha256, data); public class HsmKeyProvider : IKeyProvider { private readonly string _keyId; public HsmKeyProvider(string keyId) { _keyId = keyId; } public byte[] ComputeHmac(OtpHashMode mode, byte[] data) { throw new NotImplementedException(); } } ``` -------------------------------- ### Generate Cryptographically Secure Keys with KeyGeneration Source: https://context7.com/kspearrin/otp.net/llms.txt Demonstrates how to generate random keys of specific lengths or based on RFC-recommended hash modes. It also shows how to derive device-specific keys from a master key using unique identifiers or serial numbers. ```csharp using OtpNet; byte[] key20 = KeyGeneration.GenerateRandomKey(20); byte[] key32 = KeyGeneration.GenerateRandomKey(32); byte[] key64 = KeyGeneration.GenerateRandomKey(64); byte[] sha1Key = KeyGeneration.GenerateRandomKey(OtpHashMode.Sha1); byte[] sha256Key = KeyGeneration.GenerateRandomKey(OtpHashMode.Sha256); byte[] sha512Key = KeyGeneration.GenerateRandomKey(OtpHashMode.Sha512); var masterKey = new InMemoryKey(KeyGeneration.GenerateRandomKey(32)); byte[] deviceId = new byte[] { 0x01, 0x02, 0x03, 0x04 }; byte[] derivedKey = KeyGeneration.DeriveKeyFromMaster(masterKey, deviceId, OtpHashMode.Sha256); int serialNumber = 12345; byte[] derivedFromSerial = KeyGeneration.DeriveKeyFromMaster(masterKey, serialNumber, OtpHashMode.Sha1); ``` -------------------------------- ### Perform Base32 Encoding in C# Source: https://github.com/kspearrin/otp.net/blob/master/README.md Demonstrates generating a random key and converting it to and from a Base32 string representation. ```csharp var key = KeyGeneration.GenerateRandomKey(20); var base32String = Base32Encoding.ToString(key); var base32Bytes = Base32Encoding.ToBytes(base32String); var otp = new Totp(base32Bytes); ``` -------------------------------- ### Key Generation and Derivation Source: https://context7.com/kspearrin/otp.net/llms.txt Demonstrates how to generate random cryptographic keys of specified lengths or based on hash modes, and how to derive device-specific keys from a master key. ```APIDOC ## Key Generation The `KeyGeneration` class provides cryptographically secure key generation and key derivation functions. ### Method Static methods of `KeyGeneration` class. ### Endpoints N/A (Class methods) ### Parameters #### Key Generation Methods - **GenerateRandomKey(int length)**: Generates a random key of the specified byte length. - **GenerateRandomKey(OtpHashMode mode)**: Generates a random key with RFC-recommended length for the given hash mode. - **DeriveKeyFromMaster(IKeyProvider masterKey, byte[] identifier, OtpHashMode mode)**: Derives a key from a master key using a byte array identifier. - **DeriveKeyFromMaster(IKeyProvider masterKey, int identifier, OtpHashMode mode)**: Derives a key from a master key using an integer identifier. ### Request Example ```csharp using OtpNet; // Generate a random key with specific length byte[] key20 = KeyGeneration.GenerateRandomKey(20); // 160 bits for SHA-1 byte[] key32 = KeyGeneration.GenerateRandomKey(32); // 256 bits for SHA-256 byte[] key64 = KeyGeneration.GenerateRandomKey(64); // 512 bits for SHA-512 // Generate a key with RFC-recommended length for the hash mode byte[] sha1Key = KeyGeneration.GenerateRandomKey(OtpHashMode.Sha1); // 20 bytes byte[] sha256Key = KeyGeneration.GenerateRandomKey(OtpHashMode.Sha256); // 32 bytes byte[] sha512Key = KeyGeneration.GenerateRandomKey(OtpHashMode.Sha512); // 64 bytes Console.WriteLine($"SHA-1 key length: {sha1Key.Length} bytes"); Console.WriteLine($"SHA-256 key length: {sha256Key.Length} bytes"); Console.WriteLine($"SHA-512 key length: {sha512Key.Length} bytes"); // Derive device-specific keys from a master key (RFC 4226 Section 7.5) var masterKey = new InMemoryKey(KeyGeneration.GenerateRandomKey(32)); byte[] deviceId = new byte[] { 0x01, 0x02, 0x03, 0x04 }; // Unique device identifier byte[] derivedKey = KeyGeneration.DeriveKeyFromMaster( masterKey, deviceId, OtpHashMode.Sha256 ); Console.WriteLine($"Derived key length: {derivedKey.Length} bytes"); // Derive key using serial number int serialNumber = 12345; byte[] derivedFromSerial = KeyGeneration.DeriveKeyFromMaster( masterKey, serialNumber, OtpHashMode.Sha1 ); ``` ### Response N/A (Methods return byte arrays representing keys.) ``` -------------------------------- ### Verify HOTP Codes with Counter Source: https://context7.com/kspearrin/otp.net/llms.txt This snippet demonstrates how to verify counter-based One-Time Password (HOTP) codes using the OtpNet library. It includes generating a secret key, computing an HOTP, verifying it against a server-side counter, and handling potential counter desynchronization by checking a window of future counters. ```csharp using OtpNet; byte[] secretKey = KeyGeneration.GenerateRandomKey(20); var hotp = new Hotp(secretKey); // Store the current counter (typically in a database) long serverCounter = 42; // User submits a code string userCode = hotp.ComputeHOTP(serverCounter); // Verify the code bool isValid = hotp.VerifyHotp(userCode, serverCounter); Console.WriteLine($"HOTP valid: {isValid}"); // Output: HOTP valid: true // On successful verification, increment the counter if (isValid) { serverCounter++; Console.WriteLine($"Counter incremented to: {serverCounter}"); } // Handle counter desynchronization by checking a window of counters bool found = false; for (long i = serverCounter; i < serverCounter + 10; i++) { if (hotp.VerifyHotp(userCode, i)) { serverCounter = i + 1; // Resync and increment found = true; Console.WriteLine($"Resynchronized at counter: {i}"); break; } } ``` -------------------------------- ### HOTP Implementation Source: https://github.com/kspearrin/otp.net/blob/master/README.md Briefly introduces the implementation of the HOTP (HMAC-based One Time Password) algorithm in C#. ```APIDOC ## HOTP (HMAC-based One Time Password) ### Description This library also provides an implementation for the HOTP algorithm, which is counter-based rather than time-based. ### Method N/A (Implementation details not provided in the text) ### Endpoint N/A (This is a method within a library) ### Parameters None specified in the provided text. ### Request Example None specified in the provided text. ### Response None specified in the provided text. ``` -------------------------------- ### Configure TOTP Verification Window in C# Source: https://github.com/kspearrin/otp.net/blob/master/README.md Demonstrates how to set an acceptable time window for TOTP code validation using the VerificationWindow class. This allows for network delays and client-server time differences. The RFC SpecifiedNetworkDelay constant provides a convenient way to adhere to RFC 6238 recommendations. ```csharp var window = new VerificationWindow(previous:1, future:1); totp.VerifyTotp(totpCode, out timeWindowUsed, VerificationWindow.RfcSpecifiedNetworkDelay); ``` -------------------------------- ### Generate HOTP Codes Source: https://context7.com/kspearrin/otp.net/llms.txt Demonstrates generating counter-based one-time passwords (HOTP) with default and custom configurations. ```csharp using OtpNet; byte[] secretKey = KeyGeneration.GenerateRandomKey(20); var hotp = new Hotp(secretKey); long counter = 0; string code0 = hotp.ComputeHOTP(counter); var hotpCustom = new Hotp(secretKey, mode: OtpHashMode.Sha256, hotpSize: 8); string customCode = hotpCustom.ComputeHOTP(counter); ``` -------------------------------- ### HOTP Verification Source: https://github.com/kspearrin/otp.net/blob/master/README.md Explains how to verify a given HOTP code against a counter value using the `VerifyHotp` method. ```APIDOC ## HOTP Verification ### Description This section details the process of verifying an HOTP code against a specific counter value using the library's verification method. ### Method `VerifyHotp(string hotp, long counter)` ### Endpoint N/A (Method Call) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```csharp // Assuming 'hotp' is an instance of Hotp and 'providedHotpCode' and 'counterValue' are defined bool isValid = hotp.VerifyHotp(providedHotpCode, counterValue); ``` ### Response #### Success Response (200) - **bool** - Returns `true` if the HOTP code is valid for the given counter, `false` otherwise. #### Response Example ```json { "isValid": true } ``` ``` -------------------------------- ### Verify TOTP with Tolerance Source: https://context7.com/kspearrin/otp.net/llms.txt Explains how to verify user-submitted TOTP codes using RFC-recommended windows to account for clock drift and network latency. ```csharp using OtpNet; var totp = new Totp(secretKey); string userSubmittedCode = "123456"; bool isValidWithWindow = totp.VerifyTotp(userSubmittedCode, out long timeStepUsed, VerificationWindow.RfcSpecifiedNetworkDelay); var customWindow = new VerificationWindow(previous: 2, future: 1); bool isValidCustom = totp.VerifyTotp(userSubmittedCode, out long matchedStep, customWindow); ``` -------------------------------- ### Two-Factor Authentication Service Source: https://context7.com/kspearrin/otp.net/llms.txt This service demonstrates how to set up two-factor authentication for a user and verify TOTP codes. ```APIDOC ## Two-Factor Authentication Service ### Description This class provides methods for setting up two-factor authentication (2FA) by generating a secret key and OTP URI, and for verifying Time-based One-Time Password (TOTP) codes. ### Class `TwoFactorAuthService` ### Methods #### SetupTwoFactor ##### Description Generates a new secret key and an OTP URI suitable for displaying as a QR code to enroll a user in 2FA. ##### Parameters - **userId** (string) - Required - The unique identifier for the user. - **email** (string) - Required - The user's email address, used in the OTP URI. ##### Returns - `TwoFactorSetupResult` - An object containing the generated `SecretKey` and `QrCodeUri`. #### VerifyCode ##### Description Verifies a provided TOTP code against a user's secret key. It includes checks for validity within a time window and prevents code reuse. ##### Parameters - **base32Secret** (string) - Required - The user's stored Base32 encoded secret key. - **code** (string) - Required - The TOTP code entered by the user. - **lastUsedTimeStep** (long?) - Optional - The time step of the last successfully used code for the user, used to prevent code reuse. ##### Returns - `VerificationResult` - An object indicating `Success` and potentially an `Error` message or the `TimeStepUsed`. ``` -------------------------------- ### OTP URI Generation Source: https://github.com/kspearrin/otp.net/blob/master/README.md Shows how to generate OTP URIs using the `OtpUri` class, compatible with applications like Google Authenticator. ```APIDOC ## OTP URI Generation ### Description This section demonstrates how to generate OTP URIs in the standard 'Key Uri Format' using the `OtpUri` class, which can be used with authenticator apps. ### Method `OtpUri` Constructor and `ToString()` ### Endpoint N/A (Class Usage) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```csharp using OtpNet; var uriString = new OtpUri( OtpType.Totp, "JBSWY3DPEHPK3PXP", // Secret key "alice@google.com", // Account name "ACME Co" // Issuer ).ToString(); // uriString will be: otpauth://totp/ACME%20Co:alice%40google.com?secret=JBSWY3DPEHPK3PXP&issuer=ACME%20Co&algorithm=SHA1&digits=6&period=30 ``` ### Response #### Success Response (200) - **string** - A string representing the generated OTP URI. #### Response Example ```json { "uri": "otpauth://totp/ACME%20Co:alice%40google.com?secret=JBSWY3DPEHPK3PXP&issuer=ACME%20Co&algorithm=SHA1&digits=6&period=30" } ``` ``` -------------------------------- ### Generate and Validate TOTP Codes Source: https://context7.com/kspearrin/otp.net/llms.txt Demonstrates how to generate a TOTP code using a secret key and verify it against the current time window. ```csharp using OtpNet; byte[] secretKey = KeyGeneration.GenerateRandomKey(20); var totp = new Totp(secretKey); string code = totp.ComputeTotp(); Console.WriteLine($"Current code: {code}"); int remainingSeconds = totp.RemainingSeconds(); DateTime windowStart = totp.WindowStart(); ``` -------------------------------- ### Generate OTP URI in C# Source: https://github.com/kspearrin/otp.net/blob/master/README.md Uses the OtpUri class to generate a standard Key Uri Format string compatible with Google Authenticator. ```csharp var uriString = new OtpUri(OtpType.Totp, "JBSWY3DPEHPK3PXP", "alice@google.com", "ACME Co").ToString(); ``` -------------------------------- ### TOTP Generation Source: https://context7.com/kspearrin/otp.net/llms.txt Demonstrates how to generate Time-Based One-Time Passwords (TOTP) using the Otp.NET library with default and custom configurations. ```APIDOC ## TOTP Generation ### Description Generates Time-Based One-Time Passwords (TOTP) using a shared secret key and the current time. This is the algorithm used by authenticator apps like Google Authenticator. ### Method N/A (Library Usage) ### Endpoint N/A (Library Usage) ### Parameters N/A (Library Usage) ### Request Example ```csharp using OtpNet; // Generate a random secret key (20 bytes for SHA-1) byte[] secretKey = KeyGeneration.GenerateRandomKey(20); // Create a TOTP generator with default settings (30-second window, 6 digits, SHA-1) var totp = new Totp(secretKey); // Compute the current TOTP code string code = totp.ComputeTotp(); Console.WriteLine($"Current code: {code}"); // Compute TOTP for a specific timestamp string codeAtTime = totp.ComputeTotp(DateTime.UtcNow); Console.WriteLine($"Code at specific time: {codeAtTime}"); // Check how many seconds remain before the code changes int remainingSeconds = totp.RemainingSeconds(); Console.WriteLine($"Code expires in: {remainingSeconds} seconds"); // Get the start of the current time window DateTime windowStart = totp.WindowStart(); Console.WriteLine($"Window started at: {windowStart:HH:mm:ss}"); ``` ### Response #### Success Response (200) N/A (Library Usage) #### Response Example ``` Current code: 123456 Code at specific time: 123456 Code expires in: 15 seconds Window started at: 10:00:00 ``` ## TOTP with Custom Configuration ### Description Customizes the TOTP generator with different hash algorithms, time steps, and code lengths to match server requirements. ### Method N/A (Library Usage) ### Endpoint N/A (Library Usage) ### Parameters N/A (Library Usage) ### Request Example ```csharp using OtpNet; byte[] secretKey = KeyGeneration.GenerateRandomKey(OtpHashMode.Sha512); // Create TOTP with custom settings: // - 15-second time step // - SHA-512 hash algorithm // - 8-digit codes var totp = new Totp( secretKey, step: 15, mode: OtpHashMode.Sha512, totpSize: 8 ); string code = totp.ComputeTotp(); Console.WriteLine($"8-digit SHA-512 code: {code}"); ``` ### Response #### Success Response (200) N/A (Library Usage) #### Response Example ``` 8-digit SHA-512 code: 12345678 ``` ``` -------------------------------- ### HOTP Generation Source: https://context7.com/kspearrin/otp.net/llms.txt Details on how to generate Counter-Based One-Time Passwords (HOTP) using the Otp.NET library, including custom configurations. ```APIDOC ## HOTP Generation ### Description Generates counter-based one-time passwords (HOTP). Unlike TOTP, HOTP uses a counter that must be synchronized between client and server. ### Method N/A (Library Usage) ### Endpoint N/A (Library Usage) ### Parameters N/A (Library Usage) ### Request Example ```csharp using OtpNet; byte[] secretKey = KeyGeneration.GenerateRandomKey(20); // Create HOTP generator with default settings (6 digits, SHA-1) var hotp = new Hotp(secretKey); // Generate codes for different counter values long counter = 0; string code0 = hotp.ComputeHOTP(counter); Console.WriteLine($"Counter {counter}: {code0}"); string code1 = hotp.ComputeHOTP(counter + 1); Console.WriteLine($"Counter {counter + 1}: {code1}"); // Create HOTP with custom settings var hotpCustom = new Hotp( secretKey, mode: OtpHashMode.Sha256, hotpSize: 8 ); string customCode = hotpCustom.ComputeHOTP(counter); Console.WriteLine($"8-digit SHA-256 code: {customCode}"); ``` ### Response #### Success Response (200) N/A (Library Usage) #### Response Example ``` Counter 0: 755224 Counter 1: 287082 8-digit SHA-256 code: 12345678 ``` ``` -------------------------------- ### Verify HOTP Code in C# Source: https://github.com/kspearrin/otp.net/blob/master/README.md Shows the method signature for verifying an HOTP code against a specific counter value. ```csharp public bool VerifyHotp(string hotp, long counter); ``` -------------------------------- ### Compute TOTP Code Source: https://github.com/kspearrin/otp.net/blob/master/README.md Illustrates how to compute the current TOTP code using the ComputeTotp method. It can optionally take a specific DateTime, otherwise it defaults to DateTime.UtcNow. ```csharp using OtpNet; // Compute TOTP using current UTC time var totpCode = totp.ComputeTotp(); // Compute TOTP for a specific timestamp var specificTotpCode = totp.ComputeTotp(DateTime.UtcNow); ``` -------------------------------- ### InMemoryKey Provider Source: https://context7.com/kspearrin/otp.net/llms.txt Details on using the InMemoryKey class to securely store secret keys in memory and its implementation of the IKeyProvider interface for OTP and HMAC computations. ```APIDOC ## InMemoryKey Provider The `InMemoryKey` class provides a secure wrapper for storing secret keys in memory, implementing the `IKeyProvider` interface for custom key storage solutions. ### Description This class allows you to use a byte array as a secret key for OTP and HMAC operations. It implements the `IKeyProvider` interface, enabling its use with `Totp` and `Hotp` classes, and for direct HMAC computation. ### Method Constructor: `InMemoryKey(byte[] secretKey)` Interface Implementation: `IKeyProvider` ### Endpoint N/A (Class) ### Parameters #### Constructor Parameters - **secretKey** (byte[]) - Required - The secret key to be stored in memory. #### IKeyProvider Methods (Implemented) - **ComputeHmac(OtpHashMode mode, byte[] data)**: Computes the HMAC for the given data using the stored secret key and specified hash mode. ### Request Example ```csharp using OtpNet; // Create a key and wrap it in InMemoryKey byte[] secretKey = KeyGeneration.GenerateRandomKey(20); var keyProvider = new InMemoryKey(secretKey); // Use with TOTP var totp = new Totp(keyProvider); string code = totp.ComputeTotp(); Console.WriteLine($"TOTP code: {code}"); // Use with HOTP var hotp = new Hotp(keyProvider); string hotpCode = hotp.ComputeHOTP(0); Console.WriteLine($"HOTP code: {hotpCode}"); // InMemoryKey implements IKeyProvider for HMAC computation byte[] data = new byte[] { 0x01, 0x02, 0x03, 0x04 }; byte[] hmac = keyProvider.ComputeHmac(OtpHashMode.Sha256, data); Console.WriteLine($"HMAC length: {hmac.Length} bytes"); // Implement custom IKeyProvider for HSM/smart card integration public class HsmKeyProvider : IKeyProvider { private readonly string _keyId; public HsmKeyProvider(string keyId) { _keyId = keyId; } public byte[] ComputeHmac(OtpHashMode mode, byte[] data) { // Call HSM to compute HMAC without exposing the key // return HsmClient.ComputeHmac(_keyId, mode, data); throw new NotImplementedException(); } } ``` ### Response - **TOTP code** (string) - The computed Time-based One-Time Password. - **HOTP code** (string) - The computed HMAC-based One-Time Password for a given counter. - **HMAC** (byte[]) - The computed HMAC value. ``` -------------------------------- ### Encode and Decode Base32 Secret Keys Source: https://context7.com/kspearrin/otp.net/llms.txt This section covers the Base32 encoding and decoding functionalities provided by the `Base32Encoding` class in OtpNet. It demonstrates how to generate a random secret key, encode it into a Base32 string for sharing, and then decode a Base32 string back into its original byte array representation. This is crucial for managing secret keys used in OTP generation. ```csharp using OtpNet; using System.Linq; // Generate a random key byte[] key = KeyGeneration.GenerateRandomKey(20); // Encode to Base32 string (for sharing with users) string base32String = Base32Encoding.ToString(key); Console.WriteLine($"Base32 encoded: {base32String}"); // Output: Base32 encoded: GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ // Decode Base32 string back to bytes byte[] decodedKey = Base32Encoding.ToBytes(base32String); Console.WriteLine($"Keys match: {key.SequenceEqual(decodedKey)}"); // Output: Keys match: true // Use decoded key with TOTP var totp = new Totp(decodedKey); string code = totp.ComputeTotp(); Console.WriteLine($"Generated code: {code}"); // Handle user-provided Base32 keys (they may have padding) string userKey = "JBSWY3DPEHPK3PXP===="; // With padding byte[] userKeyBytes = Base32Encoding.ToBytes(userKey); // Padding is automatically trimmed ``` -------------------------------- ### TOTP Verification with Expanded Time Window Source: https://github.com/kspearrin/otp.net/blob/master/README.md This section details how to use the VerificationWindow parameter in the VerifyTotp method to accept codes within a specified time frame, adhering to RFC 6238 recommendations. ```APIDOC ## TOTP Verification with Expanded Time Window ### Description Allows for the acceptance of TOTP codes within a defined time window, accommodating network delays or clock skew between client and server. ### Method `VerifyTotp` (part of the `Totp` class) ### Endpoint N/A (This is a method within a library) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None - **VerificationWindow** (VerificationWindow) - Optional - An object that defines the acceptable range of time steps (previous and future) for validation. If omitted, only the current time step is considered. ### Request Example ```csharp // To allow one step prior and one step future (RFC 6238 recommendation) var window = new VerificationWindow(previous: 1, future: 1); totp.VerifyTotp(totpCode, out timeWindowUsed, window); // Using the pre-defined RFC constant totp.VerifyTotp(totpCode, out timeWindowUsed, VerificationWindow.RfcSpecifiedNetworkDelay); ``` ### Response #### Success Response (200) Indicates successful validation of the TOTP code within the specified or default time window. #### Response Example (The `VerifyTotp` method typically returns a boolean indicating success or failure. The `timeWindowUsed` output parameter would contain details about the time step that matched.) ```json { "success": true, "timeWindowUsed": { "stepOffset": 0 // Example: 0 for current step, -1 for previous, 1 for future } } ``` ``` -------------------------------- ### Implement Time Correction for TOTP in C# Source: https://github.com/kspearrin/otp.net/blob/master/README.md Shows how to use the TimeCorrection class to compensate for discrepancies between client and server system times when calculating TOTP codes. This involves providing a correct UTC DateTime to the TimeCorrection constructor and then passing this object to the Totp constructor. ```csharp var correction = new TimeCorrection(correctTime); var totp = new Totp(secretKey, timeCorrection: correction); ``` -------------------------------- ### TOTP Verification Source: https://github.com/kspearrin/otp.net/blob/master/README.md Details the process of verifying a provided TOTP code against the current time window. ```APIDOC ## VerifyTotp ### Description Validates a provided TOTP string against the current time window. Returns a boolean indicating success and the time window used for persistence tracking. ### Method POST (Logical) ### Parameters #### Method Parameters - **totp** (string) - Required - The code to verify. - **timeWindowUsed** (out long) - Required - Returns the time window index for replay protection. - **window** (VerificationWindow) - Optional - Defines the drift allowance for verification. ### Request Example string inputCode = "123456"; long timeWindow; bool isValid = totp.VerifyTotp(inputCode, out timeWindow); ### Response #### Success Response (200) - **isValid** (bool) - True if the code is valid for the window. - **timeWindowUsed** (long) - The window index used for validation. ``` -------------------------------- ### Time Correction for Clock Skew Source: https://github.com/kspearrin/otp.net/blob/master/README.md Explains the use of the TimeCorrection class to compensate for discrepancies between the client's system time and the server's time when generating or validating OTP codes. ```APIDOC ## Time Correction for Clock Skew ### Description Compensates for differences between the client's system clock and the authoritative time, ensuring accurate OTP generation and validation. ### Method `Totp` constructor overload, `TimeCorrection` class ### Endpoint N/A (This is a method within a library) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None - **TimeCorrection** (TimeCorrection) - Optional - An object used to adjust time calculations. It takes a `correctTime` (DateTime UTC) representing the authoritative current time. - **correctTime** (DateTime) - Required - The authoritative current UTC time. - **referenceTime** (DateTime) - Optional - A reference time to use if not using UTC. ### Request Example ```csharp // Assuming 'correctUtcTime' is obtained from a reliable source (e.g., NTP, Date header) var correction = new TimeCorrection(correctUtcTime); var totp = new Totp(secretKey, timeCorrection: correction); // Example using both correct and reference time var correctionWithReference = new TimeCorrection(correctUtcTime, referenceTime); var totpWithReference = new Totp(secretKey, timeCorrection: correctionWithReference); ``` ### Response #### Success Response (200) Indicates successful initialization of the `Totp` object with time correction applied. #### Response Example (The `Totp` constructor does not return a value in the traditional sense but initializes the object for subsequent operations.) ```json { "message": "Totp object initialized with time correction." } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.