bash: TOTP From the Terminal With oathtool

TOTP is Time-based One Time Password. Most people use applications on their phone for TOTP, such as andOTP, Google Authenticator, and related apps. But, as we move from using a phone as a second factor for what we are doing on a computer to a phone being the primary way we interact with the Internet, it makes sense to make the computer the second factor. This is the idea behind this script. It is based on analyth’s script, except I stripped out the I/O.

#!/bin/bash

# Assign variables
google=$(oathtool --base32 --totp "YOUR SECRET KEY" -d 6)
wordpress=$(oathtool --base32 --totp "YOUR SECRET KEY" -d 6)
amazon=$(oathtool --base32 --totp "YOUR SECRET KEY" -d 6)

# Print variables
echo "google: ${google} | wordpress: ${wordpress} | amazon: ${amazon}"

This will print:

google: 123456 | wordpress: 123456 | amazon: 123456

However, I didn’t like the idea of my one time password codes only being protected by normal file protections on a Linux system. I thought it should be encrypted with gpg. So, I saved it to a file in my scripts directory, totp, and encrypted it with my public key. If you don’t have a gpg key pair, instructions are available online.

$ gpg -r your@email.com -e ~/pathto/totp

Then, to run the shell script, do:

$ gpg -d ~/pathto/totp.gpg 2>/dev/null | bash

This will prompt you for your gpg password and then run this script. You likely won’t want to remember this string of commands, so you could make your life easier by adding it as an alias under .bash_aliases

alias totp='gpg -d ~/pathto/totp.gpg 2>/dev/null | bash'