Understanding 2FA
User
I want to activate 2FA
Server
OK - let me generate a secret key (in base 32, minimum 16 characters)
Scan this QR code on your device
![](/2fa-qr.png)
OK
Hash the secret key with the UTC timestamp to the nearest 30 seconds, then dynamically truncate to 6 numbers
My code is: 501-042
OK - let me make the same calculation
Yeah - I get the same code. 2FA is now setup. 👍
If you lose your 2FA secret you’ll be locked out, so you might want to back that up 😜
How do I back it up?
Save your secret key in a text file / QR code image in a safe place
Will it work in another authenticator app?
Yeah - the secret key can be used in as many 2FA apps as you like 👍
Backing up 2FA
The only thing you need to backup your 2FA is your secret keys (or QR codes) that were given to you.
Generating your own codes
Once you know your own secret, you can generate your own 2FA codes using any library that supports TOTP:
import { TOTP } from "totp-generator"
const { otp /*, expires */ } = TOTP.generate( YOUR_KEY )
console.log(otp)
Creating QR codes
The server creates a secret (a base 32 encoded string) and shares it with the user.
The QR code has a specific string (https://github.com/google/google-authenticator/wiki/Key-Uri-Format):
otpath://totp/ISSUER:USERNAME?secret=SECRET&issuer=ISSUER&period=30&digits=6