Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
TOTP (Google Authenticator) two-factor auth proof of concept.

Depends on

pip install -e "git://"

1: Generate key, install key

Generate a secret key (and for fun, the QR code URL that can be imported by the Google Authenticator scanner) with

See for what to do with this.

2: Attempt to authenticate

Then, use like this: [secret] [code_from_authenticator]


$ python
Hex secret: 229249c943c32afca61b

===== Google URL =====
Scan this with Google Authenticator or enter the base32
value above as 'key' when manually adding.

(See )

Example of a valid auth:

$ python 229249c943c32afca61b 123456
(True, 0)

Example of an invalid auth:

$ python 229249c943c32afca61b 987654
(False, 0)
from oath import totp, accept_totp
import sys
if __name__ == "__main__":
if len(sys.argv) < 3:
print "Usage:"
print " [secret] [code_from_authenticator]"
secret = sys.argv[1]
code = sys.argv[2]
print accept_totp(secret, code, "dec6")
from base64 import b32encode
from binascii import hexlify, unhexlify
import socket
import sys
from urllib import urlencode
# Secure random generators
import random
random = random.SystemRandom()
from os import urandom
urandom = None
def random_seed(rawsize=10):
""" Generates a random seed, which is hex encoded. """
if urandom:
randstr = urandom(rawsize)
randstr = ''.join([ chr(random.randint(0, 255)) for i in range(rawsize) ])
return hexlify(randstr)
def get_google_url(hex_secret, hostname=None):
# Note: Google uses base32 for it's encoding rather than hex.
b32secret = b32encode( unhexlify(hex_secret) )
if not hostname:
hostname = socket.gethostname()
data = "otpauth://totp/%(hostname)s?secret=%(secret)s" % {
url = "" + urlencode({
return b32secret, url
if __name__ == "__main__":
secret = random_seed()
b32secret, url = get_google_url(secret, )
print "Hex secret: %s" % secret
print "...base32: %s" % b32secret
print "===== Google URL ====="
print "Scan this with Google Authenticator or enter the base32"
print "value above as 'key' when manually adding.\n %s" % url
print "(See )"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment