Debian Codegraph @

yubiotp/modhex.py

raw symbols SCIP
1 """
2 Implementation of `modhex encoding <http://www.yubico.com/modhex-calculator>`_,
3 which uses keyboard-independent characters.
4
5 ::
6
7 hex digit: 0123456789abcdef
8 modhex digit: cbdefghijklnrtuv
9 """
10
11 from binascii import hexlify, unhexlify
12 from functools import partial
13 import struct
14
15
16 __all__ = ['modhex', 'unmodhex', 'is_modhex', 'hex_to_modhex', 'modhex_to_hex']
17
18
19 def modhex(data):
20 """
21 Encode a string of bytes as modhex.
22
23 >>> modhex(b'abcdefghijklmnop') == b'hbhdhehfhghhhihjhkhlhnhrhthuhvic'
24 True
25 """
26 return hex_to_modhex(hexlify(data))
27
28
29 def unmodhex(encoded):
30 """
31 Decode a modhex string to its binary form.
32
33 >>> unmodhex(b'hbhdhehfhghhhihjhkhlhnhrhthuhvic') == b'abcdefghijklmnop'
34 True
35 """
36 return unhexlify(modhex_to_hex(encoded))
37
38
39 def is_modhex(encoded):
40 """
41 Returns ``True`` iff the given string is valid modhex.
42
43 >>> is_modhex(b'cbdefghijklnrtuv')
44 True
45 >>> is_modhex(b'cbdefghijklnrtuvv')
46 False
47 >>> is_modhex(b'cbdefghijklnrtuvyy')
48 False
49 """
50 if any(c not in modhex_chars for c in encoded):
51 return False
52 elif len(encoded) % 2 != 0:
53 return False
54 else:
55 return True
56
57
58 def hex_to_modhex(hex_str):
59 """
60 Convert a string of hex digits to a string of modhex digits.
61
62 >>> hex_to_modhex(b'69b6481c8baba2b60e8f22179b58cd56') == b'hknhfjbrjnlnldnhcujvddbikngjrtgh'
63 True
64 >>> hex_to_modhex(b'6j')
65 Traceback (most recent call last):
66 ...
67 ValueError: Illegal hex character in input
68 """
69 try:
70 return b''.join(int2byte(hex_to_modhex_char(b))
71 for b in iter(hex_str.lower()))
72 except ValueError:
73 raise ValueError('Illegal hex character in input')
74
75
76 def modhex_to_hex(modhex_str):
77 """
78 Convert a string of modhex digits to a string of hex digits.
79
80 >>> modhex_to_hex(b'hknhfjbrjnlnldnhcujvddbikngjrtgh') == b'69b6481c8baba2b60e8f22179b58cd56'
81 True
82 >>> modhex_to_hex(b'hbhdxx')
83 Traceback (most recent call last):
84 ...
85 ValueError: Illegal modhex character in input
86 """
87 try:
88 return b''.join(int2byte(modhex_to_hex_char(b))
89 for b in iter(modhex_str.lower()))
90 except ValueError:
91 raise ValueError('Illegal modhex character in input')
92
93
94 #
95 # Internals
96 #
97
98 def int2byte(i):
99 return struct.Struct(">B").pack(i)
100
101
102 def lookup(alist, key):
103 try:
104 return next(v for (k, v) in alist if k == key)
105 except StopIteration:
106 raise ValueError()
107
108
109 hex_chars = b'0123456789abcdef'
110 modhex_chars = b'cbdefghijklnrtuv'
111
112 hex_to_modhex_map = list(zip(iter(hex_chars), iter(modhex_chars)))
113 modhex_to_hex_map = list(zip(iter(modhex_chars), iter(hex_chars)))
114
115 hex_to_modhex_char = partial(lookup, hex_to_modhex_map)
116 modhex_to_hex_char = partial(lookup, modhex_to_hex_map)