Skip to main content

Command Palette

Search for a command to run...

How 2FA Actually Works (and why it’s cool)

Published
1 min read
How 2FA Actually Works (and why it’s cool)

2FA (Two Factor Authentication) looks complicated, but it's actually really simple once you break it down.

At its core, it uses 2 things:

A realtime element (time):

A secret key:

Example secret key:
Bob1234

Make your own 2FA generator

You can actually build your own basic 2FA system in a few lines of code.

What you need

import time
import hmac
import hashlib
import struct

secret = "Bob1234"

counter = int(time.time() // 30)
counter_bytes = struct.pack(">Q", counter)

h = hmac.new(secret.encode(), counter_bytes, hashlib.sha1).digest()

offset = h[-1] & 0x0F
code = struct.unpack(">I", h[offset:offset+4])[0] & 0x7FFFFFFF
code = code % 1000000

print(str(code).zfill(6))

When you run this, it will generate and print a 6 digit verification code directly in your terminal.