#!/usr/bin/python # Copyright 2013 Peter Palfrader # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import base64 import optparse import subprocess import sys import urllib parser = optparse.OptionParser() parser.set_usage("%prog [options] [key]") parser.add_option("-r", "--raw", dest="raw", default=False, action="store_true", help="Encode just the base32 key, not an otpauth:// URL.") parser.add_option("-n", "--name", dest="name", help="Provide a name for this otpauth token.") parser.add_option("-u", "--user", dest="user", help="Provide a username for this otpauth token.") parser.add_option("-b", "--base32", dest="base32", default=False, action="store_true", help="Key already is in base32.") parser.add_option("-v", "--verbose", dest="verbose", default=0, action="count", help="Verbose output.") (options, args) = parser.parse_args() if len(args) >= 2: parser.print_help() sys.exit(1) elif len(args) == 1: hexkey = args[0] else: print "Enter key: ", hexkey = sys.stdin.readline().rstrip() if options.base32: b32key = hexkey else: binkey = base64.b16decode(hexkey, True) b32key = base64.b32encode(binkey) if options.raw: msg = b32key else: name = urllib.quote(options.name) if options.name is not None else 'token' name += ':' + urllib.quote(options.user) if options.user is not None else '' msg = "otpauth://totp/%s?secret=%s"%(name, b32key) msg += '&issuer=%s'%(urllib.quote(options.name),) if options.name is not None else '' if options.verbose > 0: print msg p = subprocess.Popen(['qrencode', '-s', '10', '-o', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) (out, dummy) = p.communicate(msg) if p.returncode != 0: raise Exception("qrencode failed.") p = subprocess.Popen(['display'], stdin=subprocess.PIPE) p.communicate(out) if p.returncode != 0: raise Exception("display failed (exitcode: %d)."%(p.returncode,))