Generating a Time-Based One-Time Password (TOTP) with a Shared Secret


In the realm of digital security, Time-Based One-Time Passwords (TOTPs) play a pivotal role, particularly in two-factor authentication systems. A TOTP is a unique passcode that is valid for only a short period of time, enhancing security by adding a dynamic layer to the authentication process. These passwords are generated by combining a shared secret key with the current time, processed through a cryptographic hash function.

The use of TOTPs is widespread in various security protocols due to their effectiveness in safeguarding against common threats like replay attacks. In this guide, we will delve into how to generate a TOTP using:

  • SHA-1 hash algorithm,

  • producing a 6-digit output,

  • with a 30-second validity interval.

The process hinges on the user's shared secret, which is a critical element in ensuring that the generated TOTP is both secure and unique to each user.

This guide provides an initial step towards integrating TOTP generation into your authentication systems, using Python and Node.js. The methods outlined here are straightforward and can be easily incorporated into a variety of security frameworks.

Generating TOTP in Python


  • Python library: pyotp


pip install pyotp

Code Example

import pyotp

def generate_totp(shared_secret):
    totp = pyotp.TOTP(shared_secret, interval=30, digits=6)

# Example Usage
shared_secret = 'YOUR_SHARED_SECRET_HERE'

Generating TOTP in Node.js


  • Node.js library: otplib


npm install otplib

Code Example

const { totp } = require('otplib');

function generateTOTP(sharedSecret) {
    totp.options = { digits: 6, algorithm: 'SHA1', step: 30 };
    return totp.generate(sharedSecret);

// Example Usage
const sharedSecret = 'YOUR_SHARED_SECRET_HERE';

Last updated