Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save eiginn/2c871955d33df0ff771e5b604df3fd75 to your computer and use it in GitHub Desktop.
Save eiginn/2c871955d33df0ff771e5b604df3fd75 to your computer and use it in GitHub Desktop.
Google authenticator (base32) and OATH (hex) TOTP QR code generator
#!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# Required packages (available from pip) : pyqrcode, pypng
import pyqrcode
import base64
import os
import binascii
#We want a secret of at least 30 hex chars for security reasons
SECRET_LEN = 30
def convert_secret_to_base32(secret):
return base64.b32encode(base64.b16decode(secret.upper()))
# Google authenticator format:
#otpauth://totp/[KEY NAME]?secret=[KEY SECRET, BASE 32].
#"Myphone nr" for example, but it can be anything, a login/uid, etc.
keyname = '4155701111'
#if you want to generate a code for non-Google (ie standard OATH Hex secret):
#secret = binascii.b2a_hex(os.urandom(SECRET_LEN))
#For Google or Google-compatible authenticators:
secret = convert_secret_to_base32(binascii.b2a_hex(os.urandom(SECRET_LEN)))
#For HOTP, just replace totp by hotp ;-)
qrdata = 'otpauth://totp/{keyname}?secret={secret}'.format(keyname=keyname, secret=secret)
code = pyqrcode.create(qrdata)
# Generate on disk
code.png('code.png', scale=10)
# Generate in memory example:
# import io
# buffer = io.BytesIO()
# url.png(buffer)
# print('<img data="{}" />'.format(buffer.getvalue(())))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment