Building an Okta Clone (Part 1): The Mathematical Core

I work in Mobile Identity. Every day, I deal with SDKs that secure millions of digital interactions. But there is a difference between using a security standard and building one from scratch.For 2026, I set a goal: to move from being a consumer of cryptographic libraries to an authority on them. The best way to do that? Reverse-engineer the gold standard.This year, I am building an Okta Verify clone entirely in Swift. No third-party crypto wrappers, no black boxes. Just raw RFC implementations. In Part 1, we are ignoring the UI and the Network. We are building the Engine—the mathematical core that generates those 6-digit codes. ## The Death of the Static Password We all know why we need Two-Factor Authentication (2FA). Static passwords are flawed because they are permanent. If I steal your password today, it works tomorrow.We needed a password that expires.The industry coalesced around One-Time Passwords (OTP). The math behind them is surprisingly elegant, but implementing it correctly on iOS requires a deep understanding of how memory works. ## The Foundation: HOTP (RFC 4226) Before we can understand Time-Based OTP (what Okta uses), we have to build its parent: HOTP (HMAC-Based One-Time Password). Imagine a checkbook. Each check has a unique number (101, 102, 103). The bank knows that if you just cashed check #101, the next one must be #102. HOTP works the same way. The Secret: A key shared between the app and the server. The Counter: A number that increments every time you press "Generate Code." The algorithm is simple:$$Code = Truncate(HMAC(Secret, Counter))$$ ## Subtle Mistake: Strings vs. Bits When I started implementing this, I hit a wall immediately. I understood the math, but I fundamentally misunderstood how to handle it in Swift.I needed to combine 4 bytes of data into a single Integer. My first instinct was to treat them like // ❌ DON'T DO THIS // I tried to "glue" the bytes together as strings let byte1 = 10 let byte2 = 255 let result = UInt32("\(byte1)\(byte2)")! This worked for small numbers. But the moment a byte hit 255, the resulting string became massive, my Integer overflowed, and the app crashed.I realized I wasn't supposed to be managing text; I was supposed to be managing bits.The "Senior" Fix: Bitwise OperationsTo implement RFC 4226 correctly, you have to operate at the binary level. We don't "glue" bytes; we "shift" them into their slots.Here is the refactored, robust Core Engine. It handles Big Endian byte order (a requirement for network protocols) and uses safe pointer arithmetic to manage memory. struct HOTP { static `func` generate(secret: Data, counter: UInt64, digits: Int = 6) -> String? { // 1. Convert Counter to Big Endian (Network Byte Order) // iOS is Little Endian, so we must flip the bytes for the network standard. var counterBigEndian = counter.bigEndian // We use 'withUnsafeBytes' to safely read the raw memory of the integer let counterData = withUnsafeBytes(of: &counterBigEndian) { Data($0) } // 2. HMAC-SHA1 Hashing // We mix the Secret and the Counter to create a unique hash let key = SymmetricKey(data: secret) let hash = HMAC.authenticationCode(for: counterData, using: key) // 3. Dynamic Truncation // We extract 4 bytes from the hash to create our integer let hashData = Data(hash) guard let lastByte = hashData.last else { return nil } // The last 4 bits of the last byte tell us WHERE to look (the offset) let offset = Int(lastByte & 0x0f) // We use Bitwise Left Shifts (<<) to move bytes into the correct slot var truncatedHash: UInt32 = 0 truncatedHash |= UInt32(hashData[offset]) << 24 truncatedHash |= UInt32(hashData[offset + 1]) << 16 truncatedHash |= UInt32(hashData[offset + 2]) << 8 truncatedHash |= UInt32(hashData[offset + 3]) // 4. Clean up and Modulo truncatedHash = truncatedHash & 0x7fffffff // Remove sign bit let modulus = UInt32(pow(10.0, Float(digits))) let pinValue = truncatedHash % modulus return String(format: "%0*d", digits, pinValue) } } ## The Evolution: TOTP (RFC 6238) HOTP had a flaw: Synchronization. If you generated a code on your phone but didn't use it, your phone's counter would be at 101, but the server would still be at 100. Eventually, they would drift so far apart that the codes would stop working.Enter TOTP (Time-Based One-Time Password).TOTP solves the drift issue by replacing the "Counter" with Time.Instead of incrementing a counter by 1, we use the current time divided by 30 seconds.$$Counter = (CurrentTime - Epoch) / 30$$Since time flows the same for everyone (mostly), the Server and the App stay in sync automatically.The Architecture: The Wrapper PatternThis is where architectural decisions matter. Many developers mix the Time logic with the Crypto logic. This makes the code hard to test (how do you test a function that depends on the current second?).I chose to architect this as a Wrapper. The TOTP struct doesn't know how to do crypto; it just knows how to calculate time. It delegates the heavy lifting to the HOTP core we built above. struct TOTP { static func generate(secret: Data, time: Date, period: TimeInterval = 30) -> String? { // 1. Calculate the Time-Step let secondsPast1970 = time.timeIntervalSince1970 // Floor division gives us the "Step Number" let counter = UInt64(floor(secondsPast1970 / period)) // 2. Delegate to the Core Engine return HOTP.generate(secret: secret, counter: counter) } } ## Conclusion We now have a mathematically correct, RFC-compliant engine that generates 2FA codes. It handles: ✅ Big Endian memory layout. ✅ Bitwise data manipulation. ✅ HMAC-SHA1 signing. ✅ Time-Step synchronization. But an engine is useless without a fuel tank. Right now, our "Secret Key" is just raw data. In a real application, that key is the most sensitive thing on the device.In Part 2, we will tackle Secure Storage. We will move away from Data and look at how to store these secrets in the iOS Keychain and the Secure Enclave, ensuring that even if the phone is compromised, the keys remain safe.