summaryrefslogtreecommitdiff
path: root/oath-qr
blob: 2abd1b1caba00123d23a8866854ef2401538e371 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#!/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


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("-b", "--base32", dest="base32", default=False, action="store_true",
    help="Key already is in base32.")
(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:
    if options.name is None:
        msg = "otpauth://totp/token?secret=%s"%(b32key,)
    else:
        msg = "otpauth://totp/%s?secret=%s"%(options.name, b32key)

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.")