Generating Two-Factor Authentication Codes on Linux

I recently almost-broke my phone. If I had fully broken it, I would be locked out of most of my accounts, because I use Google Authenticator for two-factor authentication on every account that supports this option. Here is a quick note about how to generate authentication codes on your Linux machine, in the same way that Google Authenticator does on your phone.

First, you need to find out the TOTP secret for your account. This secret is displayed in plain text when you set up two-factor authentication, as highlighted in green in the image below.

Google 2-factor auth setup

For sites that only display a QR code, you can take a screenshot and parse the QR code using the zbarimg command (provided by the zbar-tools package). You don't even need to crop the image beforehand.

$ zbarimg screenshot.png
QR-Code:otpauth://totp/<ACCOUNT>?secret=<SECRET>&issuer=<ISSUER>

Treat the TOTP secret like a password. Save it to an encrypted file, or use a password manager. Don't store it somewhere in plain text, and definitely don't email it to yourself.

Once you have your secret, you can generate authentication codes using the oathtool command (provided by the oathtool package):

oathtool --base32 --totp "<SECRET>"

You can verify that this generates the same codes as Google Authenticator on your phone.