2-factor Authentication using TOTP

Puran Joshi
5 min readJul 11, 2023

--

Strengthening online security using TOTP

Audience

Anyone who wants to enhance the security of their online application, or any technology enthusiasts who want to understand the technical aspect of the two-factor authentication using TOTP.

Overview

In this article, I aim to provide insights into the concept of two-factor authentication, its significance in enhancing security, and a comprehensive explanation of the Time-Based One-Time Password (TOTP) algorithm. Additionally, I will showcase a sample implementation to offer a practical understanding of how TOTP works.

What is 2FA (two-factor authentication)?

In the digital world today, we’re seeing a sharp increase in websites losing user data to cyberattacks. These attacks are becoming more advanced, leaving companies exposed and unable to defend against them. It’s not just a matter of trust being broken; organisations of all sizes, from big companies to small businesses and non-profits, suffer serious financial and reputational damage. It’s clear that old security systems can’t keep up with these new threats. We need to take action and strengthen our defenses to protect both data and trust.

2-Factor Authentication (2FA) adds an extra layer of security to make sure that only the right people can access an online account. Here’s how it works: When you log in, you enter your username and password like usual. But instead of getting in right away, you’ll need to provide another piece of information. This can fall into three categories:

  1. Something you know: Some piece of information that only you should know, like a PIN, a password, answers to secret questions, etc…
  2. Something you have: This means having a physical item, like a device that could generates token, credit card, etc...
  3. Something you are: This means something unique about you like your bio-metics, eye scan, etc...

By using 2FA with these different factors, we can make it much harder for unauthorised people to get into our accounts and keep our information safe.

What is TOTP?

In simple terms, Time-Based One-Time Password (TOTP) belongs to the “Something you have” category of 2FA. It means that TOTP relies on something physical that you possess, like your smartphone or a special token. These devices generate unique passwords that change over time. This extra step makes it harder for bad guys to get into your account because they would need both your regular password and the constantly changing special password from your device.

RFC 6238 defines the technical specifications and guidelines for implementing TOTP as a time-based authentication mechanism. This document outlines the algorithm, encoding, and validation process for generating and verifying one-time passwords based on a shared secret key and the current time.

Implementing TOTP

Here’s the algorithm for Time-Based One-Time Password (TOTP) based on RFC 6238:

  1. Set up a shared secret key: The user and the server establish a shared secret key. This key is securely exchanged or generated during the initial setup.
  2. Determine the current time: Obtain the current time in Unix time format, which is the number of seconds elapsed since January 1, 1970 (UTC).
  3. Generate a counter value: Divide the current time by a predefined time interval (typically 30 seconds) to obtain a counter value. This ensures that the counter value changes at regular intervals.
  4. Convert the counter to an 8-byte array: Represent the counter value as an 8-byte array using big-endian byte order.
  5. Apply the HMAC-SHA1 algorithm: Use the shared secret key as the HMAC-SHA1 algorithm key to hash the counter value. This produces a 20-byte hash value.
  6. Dynamic Truncation: Take the last 4 bytes of the hash value (specifically, the 31st to 34th bytes) as an offset. Perform a bitwise AND operation with a binary mask to obtain a 4-byte dynamic truncation value.
  7. Apply a specific encoding: Convert the dynamic truncation value to a human-readable format. This can be done by taking the 4-byte value modulo 10^d, where “d” is the desired number of digits (typically 6).
  8. Format the result: Pad the resulting value with leading zeros if needed to achieve the desired number of digits.

The resulting value is the TOTP, which is a time-based one-time password that can be used for authentication. This algorithm ensures that the TOTP is generated based on the shared secret key, the current time, and a consistent hashing process, allowing for secure and synchronised authentication between the user and the server.

Sequence Diagram

1. Registration flow

TOTP Registration Flow

2. OTP Validation flow

OTP Validation Flow

Sample Code

Below is a sample code that would generate an TOTP based on current timestamp and shared secret.

fun generateTOTP(sharedSecret: ByteArray): String {
val timeStep = 30 // Time step in seconds
val digits = 6 // Number of digits in the generated TOTP

val counter = Instant.now().epochSecond / timeStep
val counterBytes = ByteBuffer.allocate(8).putLong(counter).array()

val hmacKey = SecretKeySpec(sharedSecret, "HmacSHA1")
val hmac = Mac.getInstance("HmacSHA1")
hmac.init(hmacKey)

val hash = hmac.doFinal(counterBytes)
val offset = hash[hash.size - 1].toInt() and 0x0F

val truncatedHash = (hash[offset].toInt() and 0x7F shl 24) or
(hash[offset + 1].toInt() and 0xFF shl 16) or
(hash[offset + 2].toInt() and 0xFF shl 8) or
(hash[offset + 3].toInt() and 0xFF)

val otp = truncatedHash % Math.pow(10.0, digits.toDouble()).toInt()
return otp.toString().padStart(digits, '0')
}

Considerations and Best Practices

Secure Key Storage: The shared secret key must be securely stored to prevent unauthorised access.

User Education: Users should be educated about the importance of protecting their TOTP secrets, avoiding phishing attacks, and enabling account recovery mechanisms.

Time Synchronisation

Handling the time difference between the server and client device is an important consideration for TOTP to ensure synchronisation.
Which can be addressed by using any one of these steps:

  1. Time drift tolerance: TOTP typically allows for a certain degree of time drift between the server and the client device. This tolerance accounts for minor variations in clock times. A commonly used value is ±1 time step, where a time step is the interval at which TOTP changes (e.g., 30 seconds).
  2. Time synchronisation: It’s crucial to ensure that the server and client device are using synchronised time sources. Both should rely on accurate time references, such as Network Time Protocol (NTP) or a similar mechanism, to minimise the time difference between them.
  3. Time correction on the client: In situations where there is a significant time difference between the server and client device, the client can adjust its clock by fetching the server’s time through a secure time synchronisation protocol or by using the server’s time as a reference during the TOTP generation process.
  4. Server-side validation window: The server can maintain a validation window that allows TOTP codes generated within a certain time period to be accepted. For example, if the server’s time is ahead of the client’s time, it can validate TOTP codes generated within the previous time step.

By considering these factors and implementing appropriate time synchronisation measures, the time difference between the server and client device can be effectively managed to ensure the successful verification of TOTP codes.

--

--

Puran Joshi

Experienced Software Engineer & Technical Lead | Expertise in Full-stack Development, Object Oriented Programming, Agile Methodologies, and Team Leadership