base32-key 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
base32_key/__init__.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""Human-friendly Base32 keys with a check digit per group.
|
|
2
|
+
|
|
3
|
+
A Python port of the core of the base32-key npm package: hex and bytes
|
|
4
|
+
encoding, decoding with per-group errors, and the same test vectors.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"Base32KeyError",
|
|
11
|
+
"from_hex",
|
|
12
|
+
"to_hex",
|
|
13
|
+
"validate",
|
|
14
|
+
"from_bytes",
|
|
15
|
+
"to_bytes",
|
|
16
|
+
"MAX_LENGTH_PREFIXED_BYTES",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
UPPER = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"
|
|
20
|
+
LOWER = "abcdefghijkmnpqrstuvwxyz23456789"
|
|
21
|
+
_CRC5 = [
|
|
22
|
+
0, 5, 10, 15, 20, 17, 30, 27, 13, 8, 7, 2, 25, 28, 19, 22,
|
|
23
|
+
26, 31, 16, 21, 14, 11, 4, 1, 23, 18, 29, 24, 3, 6, 9, 12,
|
|
24
|
+
]
|
|
25
|
+
_HEX = "0123456789abcdef"
|
|
26
|
+
|
|
27
|
+
MAX_LENGTH_PREFIXED_BYTES = 0xFFFFF
|
|
28
|
+
"""Largest byte length a ``with_length`` key can store (20 bits)."""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Base32KeyError(ValueError):
|
|
32
|
+
"""Invalid input. ``code`` matches the JavaScript error codes and
|
|
33
|
+
``invalid_groups`` lists the 0-based indexes of the groups that failed."""
|
|
34
|
+
|
|
35
|
+
def __init__(self, code: str, message: str, invalid_groups: list[int] | None = None):
|
|
36
|
+
super().__init__(message)
|
|
37
|
+
self.code = code
|
|
38
|
+
self.invalid_groups = list(invalid_groups or [])
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _crc5(digits: list[int]) -> int:
|
|
42
|
+
crc = 0
|
|
43
|
+
for d in digits:
|
|
44
|
+
crc = _CRC5[d ^ crc]
|
|
45
|
+
return crc
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _alphabet(case: str) -> str:
|
|
49
|
+
if case == "upper":
|
|
50
|
+
return UPPER
|
|
51
|
+
if case == "lower":
|
|
52
|
+
return LOWER
|
|
53
|
+
raise ValueError(f'case must be "upper" or "lower", got {case!r}')
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def from_hex(hex_string: str, *, grouped: bool = True, checked: bool = True,
|
|
57
|
+
case: str = "upper") -> str:
|
|
58
|
+
"""Encode a hex string (an optional ``0x`` prefix is allowed) as a key."""
|
|
59
|
+
alphabet = _alphabet(case)
|
|
60
|
+
if not isinstance(hex_string, str):
|
|
61
|
+
raise TypeError("Invalid hex string: expected a string")
|
|
62
|
+
h = hex_string[2:] if hex_string[:2].lower() == "0x" else hex_string
|
|
63
|
+
h = h.lower()
|
|
64
|
+
if not h or any(c not in _HEX for c in h):
|
|
65
|
+
raise Base32KeyError("INVALID_HEX", f'Invalid hex string: "{hex_string}"')
|
|
66
|
+
h = h.zfill(-(-len(h) // 5) * 5)
|
|
67
|
+
digits: list[int] = []
|
|
68
|
+
for i in range(0, len(h), 5):
|
|
69
|
+
word = int(h[i:i + 5], 16)
|
|
70
|
+
digits += [(word >> 15) & 31, (word >> 10) & 31, (word >> 5) & 31, word & 31]
|
|
71
|
+
if grouped:
|
|
72
|
+
groups = []
|
|
73
|
+
for i in range(0, len(digits), 4):
|
|
74
|
+
group = digits[i:i + 4]
|
|
75
|
+
if checked:
|
|
76
|
+
group.append(_crc5(group))
|
|
77
|
+
groups.append("".join(alphabet[d] for d in group))
|
|
78
|
+
return "-".join(groups)
|
|
79
|
+
if checked:
|
|
80
|
+
digits.append(_crc5(digits))
|
|
81
|
+
i = 0
|
|
82
|
+
while i + 1 < len(digits) and digits[i] == 0:
|
|
83
|
+
i += 1
|
|
84
|
+
return "".join(alphabet[d] for d in digits[i:])
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _decode_group(group: str, alphabet: str, grouped: bool, checked: bool):
|
|
88
|
+
digits = []
|
|
89
|
+
for c in group:
|
|
90
|
+
d = alphabet.find(c)
|
|
91
|
+
if d < 0:
|
|
92
|
+
return None, "INVALID_CHARACTER"
|
|
93
|
+
digits.append(d)
|
|
94
|
+
if not digits or (grouped and len(digits) != 4 + (1 if checked else 0)):
|
|
95
|
+
return None, "INVALID_LENGTH"
|
|
96
|
+
if checked:
|
|
97
|
+
check = digits.pop()
|
|
98
|
+
if _crc5(digits) != check:
|
|
99
|
+
return None, "CHECKSUM_MISMATCH"
|
|
100
|
+
while len(digits) % 4:
|
|
101
|
+
digits.insert(0, 0)
|
|
102
|
+
out = ""
|
|
103
|
+
for i in range(0, len(digits), 4):
|
|
104
|
+
word = (digits[i] << 15) | (digits[i + 1] << 10) | (digits[i + 2] << 5) | digits[i + 3]
|
|
105
|
+
out += f"{word:05x}"
|
|
106
|
+
return out, None
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
_MESSAGES = {
|
|
110
|
+
"INVALID_CHARACTER": "a character outside the alphabet",
|
|
111
|
+
"INVALID_LENGTH": "the wrong length",
|
|
112
|
+
"CHECKSUM_MISMATCH": "a check digit that does not match",
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _analyze(key: str, grouped: bool, checked: bool, case: str):
|
|
117
|
+
if not isinstance(key, str):
|
|
118
|
+
raise TypeError("Invalid: expected a string")
|
|
119
|
+
alphabet = _alphabet(case)
|
|
120
|
+
groups = key.split("-")
|
|
121
|
+
hex_out, invalid, code = "", [], None
|
|
122
|
+
for index, group in enumerate(groups):
|
|
123
|
+
h, err = _decode_group(group, alphabet, grouped, checked)
|
|
124
|
+
if err:
|
|
125
|
+
invalid.append(index)
|
|
126
|
+
code = code or err
|
|
127
|
+
else:
|
|
128
|
+
hex_out += h
|
|
129
|
+
return hex_out, invalid, code
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def validate(key: str, *, grouped: bool = True, checked: bool = True,
|
|
133
|
+
case: str = "upper") -> tuple[bool, list[int], str | None]:
|
|
134
|
+
"""Return ``(valid, invalid_groups, code)`` without raising."""
|
|
135
|
+
_, invalid, code = _analyze(key, grouped, checked, case)
|
|
136
|
+
return code is None, invalid, code
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _padded_hex(key: str, grouped: bool, checked: bool, case: str) -> str:
|
|
140
|
+
hex_out, invalid, code = _analyze(key, grouped, checked, case)
|
|
141
|
+
if code:
|
|
142
|
+
where = (f"group {invalid[0] + 1}" if len(invalid) == 1
|
|
143
|
+
else "groups " + ", ".join(str(i + 1) for i in invalid))
|
|
144
|
+
verb = "has" if len(invalid) == 1 else "have"
|
|
145
|
+
raise Base32KeyError(code, f"Invalid key: {where} {verb} {_MESSAGES[code]}", invalid)
|
|
146
|
+
return hex_out
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def to_hex(key: str, *, grouped: bool = True, checked: bool = True,
|
|
150
|
+
case: str = "upper") -> str:
|
|
151
|
+
"""Decode a key to a hex string without leading zeros.
|
|
152
|
+
|
|
153
|
+
Raises :class:`Base32KeyError` naming every group that failed.
|
|
154
|
+
"""
|
|
155
|
+
return _padded_hex(key, grouped, checked, case).lstrip("0") or "0"
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def from_bytes(data: bytes, *, with_length: bool = False, grouped: bool = True,
|
|
159
|
+
checked: bool = True, case: str = "upper") -> str:
|
|
160
|
+
"""Encode bytes. With ``with_length`` the first group stores the byte
|
|
161
|
+
count, so leading zero bytes survive and cut keys are detected."""
|
|
162
|
+
data = bytes(data)
|
|
163
|
+
if not with_length:
|
|
164
|
+
if not data:
|
|
165
|
+
raise ValueError("Cannot encode empty bytes without with_length")
|
|
166
|
+
return from_hex(data.hex(), grouped=grouped, checked=checked, case=case)
|
|
167
|
+
if not grouped:
|
|
168
|
+
raise TypeError("with_length requires grouped keys")
|
|
169
|
+
if len(data) > MAX_LENGTH_PREFIXED_BYTES:
|
|
170
|
+
raise ValueError(f"with_length supports at most {MAX_LENGTH_PREFIXED_BYTES} bytes")
|
|
171
|
+
h = data.hex()
|
|
172
|
+
return from_hex(f"{len(data):05x}" + h.zfill(-(-len(h) // 5) * 5),
|
|
173
|
+
grouped=True, checked=checked, case=case)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def to_bytes(key: str, *, with_length: bool = False, length: int | None = None,
|
|
177
|
+
grouped: bool = True, checked: bool = True, case: str = "upper") -> bytes:
|
|
178
|
+
"""Decode a key to bytes. See :func:`from_bytes`."""
|
|
179
|
+
if with_length:
|
|
180
|
+
if not grouped:
|
|
181
|
+
raise TypeError("with_length requires grouped keys")
|
|
182
|
+
h = _padded_hex(key, True, checked, case)
|
|
183
|
+
n = int(h[:5], 16)
|
|
184
|
+
data = h[5:]
|
|
185
|
+
expected = -(-n * 2 // 5) * 5
|
|
186
|
+
padding = data[:expected - n * 2]
|
|
187
|
+
if len(data) != expected or padding.strip("0"):
|
|
188
|
+
raise Base32KeyError(
|
|
189
|
+
"INVALID_LENGTH",
|
|
190
|
+
f"Invalid key: a {n}-byte value needs {expected // 5 + 1} groups, got {len(h) // 5}",
|
|
191
|
+
)
|
|
192
|
+
return bytes.fromhex(data[len(padding):])
|
|
193
|
+
h = to_hex(key, grouped=grouped, checked=checked, case=case)
|
|
194
|
+
out = bytes.fromhex(h.zfill(len(h) + len(h) % 2))
|
|
195
|
+
if length is None:
|
|
196
|
+
return out
|
|
197
|
+
if not isinstance(length, int) or length < 0:
|
|
198
|
+
raise ValueError(f"length must be a non-negative integer, got {length}")
|
|
199
|
+
if out == b"\x00":
|
|
200
|
+
out = b""
|
|
201
|
+
if len(out) > length:
|
|
202
|
+
raise Base32KeyError(
|
|
203
|
+
"INVALID_LENGTH",
|
|
204
|
+
f"Invalid key: the value needs {len(out)} bytes, more than {length}",
|
|
205
|
+
)
|
|
206
|
+
return out.rjust(length, b"\x00")
|
base32_key/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: base32-key
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Human-friendly Base32 keys with a check digit per group
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Homepage, https://github.com/ducminhquan/base32-key
|
|
7
|
+
Project-URL: Source, https://github.com/ducminhquan/base32-key/tree/master/python
|
|
8
|
+
Project-URL: Changelog, https://github.com/ducminhquan/base32-key/blob/master/python/CHANGELOG.md
|
|
9
|
+
Keywords: base32,key,license-key,voucher,checksum
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Typing :: Typed
|
|
13
|
+
Requires-Python: >=3.9
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# base32-key for Python
|
|
19
|
+
|
|
20
|
+
A Python port of the core of [base32-key](https://github.com/ducminhquan/base32-key): the same alphabets, the same check digit per group and the same keys. It is tested against the shared [test-vectors.json](https://github.com/ducminhquan/base32-key/blob/master/test-vectors.json), so keys made in JavaScript decode here and the other way round.
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
pip install base32-key
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Python 3.9 or later, no dependencies.
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
from base32_key import from_hex, to_hex, from_bytes, to_bytes, validate, Base32KeyError
|
|
30
|
+
|
|
31
|
+
from_hex("c0ffee") # '222ET-3ZZGN'
|
|
32
|
+
to_hex("222ET-3ZZGN") # 'c0ffee'
|
|
33
|
+
from_hex("c0ffee", grouped=False, case="lower") # 'nb99qj'
|
|
34
|
+
from_bytes(b"\x00\xff", with_length=True) # '2224C-229ZN'
|
|
35
|
+
validate("222ET-3ZZGX") # (False, [1], 'CHECKSUM_MISMATCH')
|
|
36
|
+
|
|
37
|
+
try:
|
|
38
|
+
to_hex("222ET-3ZZGX")
|
|
39
|
+
except Base32KeyError as e:
|
|
40
|
+
print(e.code, e.invalid_groups) # CHECKSUM_MISMATCH [1]
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Keyword options are `grouped`, `checked` and `case` (`"upper"` or `"lower"`), with the same defaults as the npm package. Input normalisation, prefixes, typo suggestions and signed keys are only in the JavaScript package for now.
|
|
44
|
+
|
|
45
|
+
Run the tests from this folder with `python -m unittest discover -s tests -t .` after `pip install -e .`, or with `PYTHONPATH=src`.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
base32_key/__init__.py,sha256=O6DGIB23aB82wtswrYFhUJ67RsJPkmhOowLASdh8fOk,7445
|
|
2
|
+
base32_key/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
+
base32_key-1.0.0.dist-info/licenses/LICENSE,sha256=xBWZZJev8lHjvsw48HSkQ8Q7OFRJ8kySBHSM_qLAC00,1065
|
|
4
|
+
base32_key-1.0.0.dist-info/METADATA,sha256=zx636XZpzroJ49jPwGcUdRrUWV46mVtu7Uv4M29SPDE,2008
|
|
5
|
+
base32_key-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
6
|
+
base32_key-1.0.0.dist-info/top_level.txt,sha256=PNTcNQYxqEgmmhNM9xrbvctTo1uaHAnpnu1PGjKB2Ek,11
|
|
7
|
+
base32_key-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2019 QuanNDM2
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
base32_key
|