Two-Factor Authentication (2FA) adds a critical security layer beyond passwords. One-Time Passwords (OTPs) generate temporary codes that expire quickly, reducing replay attack risks. This guide covers the two primary OTP standards with practical C# implementation examples.
📋 Overview of OTP Protocols
What Is OTP?
A One-Time Password is a unique code valid for only one login session or transaction. Unlike static passwords, OTPs cannot be reused if intercepted.
Two Main Standards: Complete C# Implementation
Protocol | RFC Standard | Trigger Mechanism | Typical Use Case |
|---|---|---|---|
HOTP | RFC 4226 | Counter increment | Hardware tokens, backup codes |
TOTP | RFC 6238 | Time interval | Mobile authenticator apps, desktop apps |
TOTP extends HOTP by incorporating time, making both code and counter derivable from synchronized clocks rather than physical counters.
🔧 Core Building Block: Base32 Encoding
Before diving into HOTP/TOTP, we need Base32 encoding, a way to represent binary data using printable ASCII characters (A-Z, 2-7). This makes secrets human-readable and safe to transfer via QR codes or text.
using System.Text;
using System.Collections.Generic;
namespace Pxoqxo.Otp2fa
{
internal static class Base32
{
private const string Base32Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
/// <summary>
/// Encodes byte array to Base32 string per RFC 4648
/// </summary>
internal static string ToBase32(byte[] bytes)
{
var result = new StringBuilder();
int buffer = 0;
int bitsLeft = 0;
foreach (byte b in bytes)
{
buffer = (buffer << 8) | b;
bitsLeft += 8;
while (bitsLeft >= 5)
{
int index = (buffer >> (bitsLeft - 5)) & 0x1F;
result.Append(Base32Chars[index]);
bitsLeft -= 5;
}
}
// Handle remaining bits (padding not shown for simplicity)
if (bitsLeft > 0)
{
int index = (buffer << (5 - bitsLeft)) & 0x1F;
result.Append(Base32Chars[index]);
}
return result.ToString();
}
/// <summary>
/// Decodes Base32 string back to byte array
/// </summary>
internal static byte[] FromBase32(string text)
{
string cleanText = text.ToUpper().Replace(" ", "").Replace("-", "");
var result = new List<byte>();
int buffer = 0;
int bitsLeft = 0;
foreach (char c in cleanText)
{
int index = Base32Chars.IndexOf(c);
if (index < 0)
{
throw new FormatException("Invalid Base32 character encountered.");
}
buffer = (buffer << 5) | index;
bitsLeft += 5;
if (bitsLeft >= 8)
{
result.Add((byte)(buffer >> (bitsLeft - 8)));
bitsLeft -= 8;
}
}
if (bitsLeft > 0)
{
result.Add((byte)(buffer << (8 - bitsLeft)));
}
return result.ToArray();
}
}
}
Key Learning Points
Concept | Explanation |
|---|---|
5-bit chunks | Base32 encodes 5 bits per character (2⁵ = 32 possible values) |
8-bit bytes | Input is processed in 8-bit bytes |
Bit shifting | Buffer accumulates bits, then extracts 5-bit indices |
Padding omitted | Production libraries add "=" padding per RFC 4648 |
🔢 HOTP (HMAC-Based One-Time Password)
Technical Background
HOTP generates codes using HMAC-SHA1 hashing:
HOTP(K, C) = Truncate(HMAC-SHA-1(K, C))
Where:
K: Shared secret key (base32 encoded typically)
C: Moving factor (counter value)
Truncate: Extracts 4 bytes from HMAC result, converts to 31-bit integer
The algorithm applies modulo operation to produce the final code length.
Algorithm Visualization
┌─────────────┐ ┌──────────────┐ ┌──────────────┐ ┌─────────────┐
│ Secret Key │ + │ Counter │ → │ HMAC-SHA1 │ → │ Truncation │
└─────────────┘ └──────────────┘ └──────────────┘ └─────────────┘
│ │
└────────────────────────────────────────────────────────────────────────────┘
│
┌──────────▼──────────┐
│ Modulo 10^digits │
└──────────┬──────────┘
│
┌────────▼────────┐
│ Final Code │
└─────────────────┘
Complete C# Implementation
using System.Security.Cryptography;
namespace Pxoqxo.Otp2fa
{
public static class Hotp
{
/// <summary>
/// Generates a cryptographically secure random secret
/// </summary>
public static string GenerateSecret(int length = 20)
{
byte[] bytes = RandomNumberGenerator.GetBytes(length);
return Base32.ToBase32(bytes);
}
/// <summary>
/// Generates HOTP code per RFC 4226
/// </summary>
/// <param name="secret">Shared secret (base32)</param>
/// <param name="counter">Current counter value</param>
/// <param name="digits">Code length (typically 6)</param>
public static string GenerateCode(string secret, long counter, int digits)
{
byte[] key = Base32.FromBase32(secret);
return Compute(key, counter, digits);
}
/// <summary>
/// Verifies HOTP code (basic version without drift)
/// </summary>
public static bool Verify(string secret, string code, long counter, int digits)
{
byte[] key = Base32.FromBase32(secret);
string computedCode = Compute(key, counter, digits);
if (CodeEquals(computedCode, code))
{
return true;
}
return false;
}
/// <summary>
/// Core HOTP computation per RFC 4226
/// </summary>
private static string Compute(byte[] key, long counter, int digits)
{
// Convert counter to byte array (big-endian)
byte[] counterBytes = BitConverter.GetBytes(counter);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(counterBytes);
}
using (var hmac = new HMACSHA1(key))
{
byte[] hash = hmac.ComputeHash(counterBytes);
// Dynamic truncation per RFC 4226 Section 5.3
int offset = hash[hash.Length - 1] & 0x0F;
int binary = ((hash[offset] & 0x7F) << 24) |
((hash[offset + 1] & 0xFF) << 16) |
((hash[offset + 2] & 0xFF) << 8) |
(hash[offset + 3] & 0xFF);
int otp = binary % (int)Math.Pow(10, digits);
return otp.ToString($"D{digits}");
}
}
/// <summary>
/// Constant-time string comparison prevents timing attacks
/// </summary>
private static bool CodeEquals(string a, string b)
{
if (a.Length != b.Length)
{
return false;
}
int diff = 0;
for (int i = 0; i < a.Length; i++)
{
diff |= a[i] ^ b[i];
}
return diff == 0;
}
}
}
HOTP Step-by-Step Example
class Program
{
static void Main()
{
// Phase 1: Enrollment (One-Time Setup)
string secret = Hotp.GenerateSecret(20);
Console.WriteLine($"Secret (save securely): {secret}");
// Expected output: JBSWY3DPEHPK3PXP (or similar 32-char base32 string)
// Initialize counter (persist this in your database!)
long currentCounter = 0;
// Phase 2: Code Generation
string code = Hotp.GenerateCode(secret, currentCounter, 6);
Console.WriteLine($"Generated code #{currentCounter}: {code}");
// Example output: 123456
// Phase 3: User Verification
Console.WriteLine("Enter the 6-digit code:");
string userInput = Console.ReadLine();
bool isValid = Hotp.Verify(secret, userInput, currentCounter, 6);
if (isValid)
{
Console.WriteLine("✓ Authentication successful!");
// IMPORTANT: Increment counter after success
currentCounter++;
SaveCounterToDatabase(currentCounter);
}
else
{
Console.WriteLine("✗ Invalid code.");
}
}
static void SaveCounterToDatabase(long counter)
{
// Persist to your database/storage
Console.WriteLine($"New counter stored: {counter}");
}
}

Join the conversation! Your thoughts help the community grow.