Commit | Line | Data |
---|---|---|
00401529 MW |
1 | ### -*-python-*- |
2 | ### | |
3 | ### Setup for Catacomb/Python bindings | |
4 | ### | |
5 | ### (c) 2004 Straylight/Edgeware | |
6 | ### | |
7 | ||
8 | ###----- Licensing notice --------------------------------------------------- | |
9 | ### | |
10 | ### This file is part of the Python interface to Catacomb. | |
11 | ### | |
12 | ### Catacomb/Python is free software; you can redistribute it and/or modify | |
13 | ### it under the terms of the GNU General Public License as published by | |
14 | ### the Free Software Foundation; either version 2 of the License, or | |
15 | ### (at your option) any later version. | |
16 | ### | |
17 | ### Catacomb/Python is distributed in the hope that it will be useful, | |
18 | ### but WITHOUT ANY WARRANTY; without even the implied warranty of | |
19 | ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
20 | ### GNU General Public License for more details. | |
21 | ### | |
22 | ### You should have received a copy of the GNU General Public License | |
23 | ### along with Catacomb/Python; if not, write to the Free Software Foundation, | |
24 | ### Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. | |
ed8cc62d | 25 | |
6bd22b53 MW |
26 | from __future__ import with_statement |
27 | ||
d7ab1bab | 28 | from binascii import hexlify as _hexify, unhexlify as _unhexify |
6bd22b53 | 29 | from contextlib import contextmanager as _ctxmgr |
8854bd74 MW |
30 | try: import DLFCN as _dlfcn |
31 | except ImportError: _dlfcn = None | |
a3ae4a9f | 32 | import os as _os |
6bd22b53 | 33 | from struct import pack as _pack |
378ceeef MW |
34 | import sys as _sys |
35 | import types as _types | |
36 | ||
37 | ###-------------------------------------------------------------------------- | |
38 | ### Import the main C extension module. | |
39 | ||
a3ae4a9f MW |
40 | try: |
41 | _dlflags = _odlflags = _sys.getdlopenflags() | |
42 | except AttributeError: | |
43 | _dlflags = _odlflags = -1 | |
44 | ||
45 | ## Set the `deep binding' flag. Python has its own different MD5 | |
46 | ## implementation, and some distributions export `md5_init' and friends so | |
47 | ## they override our versions, which doesn't end well. Figure out how to | |
48 | ## turn this flag on so we don't have the problem. | |
49 | if _dlflags >= 0: | |
50 | try: _dlflags |= _dlfcn.RTLD_DEEPBIND | |
51 | except AttributeError: | |
52 | try: _dlflags |= _os.RTLD_DEEPBIND | |
53 | except AttributeError: | |
54 | if _os.uname()[0] == 'Linux': _dlflags |= 8 # magic knowledge | |
55 | else: pass # can't do this. | |
56 | _sys.setdlopenflags(_dlflags) | |
57 | ||
f7623015 MW |
58 | if _sys.version_info >= (3,): from . import _base |
59 | else: import _base | |
46e6ad89 | 60 | |
a3ae4a9f MW |
61 | if _odlflags >= 0: |
62 | _sys.setdlopenflags(_odlflags) | |
63 | ||
64 | del _dlflags, _odlflags | |
65 | ||
00401529 MW |
66 | ###-------------------------------------------------------------------------- |
67 | ### Basic stuff. | |
ed8cc62d | 68 | |
c04b289c MW |
69 | ## For the benefit of the default keyreporter, we need the program name. |
70 | _base._ego(_sys.argv[0]) | |
d7ab1bab | 71 | |
930d78e3 MW |
72 | ## Register our module. |
73 | _base._set_home_module(_sys.modules[__name__]) | |
74 | def default_lostexchook(why, ty, val, tb): | |
75 | """`catacomb.lostexchook(WHY, TY, VAL, TB)' reports lost exceptions.""" | |
76 | _sys.stderr.write("\n\n!!! LOST EXCEPTION: %s\n" % why) | |
77 | _sys.excepthook(ty, val, tb) | |
78 | _sys.stderr.write("\n") | |
79 | lostexchook = default_lostexchook | |
80 | ||
467c2619 | 81 | ## Text/binary conversions. |
f7623015 MW |
82 | if _sys.version_info >= (3,): |
83 | def _bin(s): return s.encode('iso8859-1') | |
84 | else: | |
85 | def _bin(s): return s | |
467c2619 | 86 | |
d6542364 | 87 | ## Iterating over dictionaries. |
f7623015 MW |
88 | if _sys.version_info >= (3,): |
89 | def _iteritems(dict): return dict.items() | |
90 | def _itervalues(dict): return dict.values() | |
91 | else: | |
92 | def _iteritems(dict): return dict.iteritems() | |
93 | def _itervalues(dict): return dict.itervalues() | |
d6542364 | 94 | |
77535854 | 95 | ## The built-in bignum type. |
f7623015 MW |
96 | try: long |
97 | except NameError: _long = int | |
98 | else: _long = long | |
77535854 | 99 | |
837fa485 MW |
100 | ## How to fix a name back into the right identifier. Alas, the rules are not |
101 | ## consistent. | |
102 | def _fixname(name): | |
103 | ||
104 | ## Hyphens consistently become underscores. | |
105 | name = name.replace('-', '_') | |
106 | ||
107 | ## But slashes might become underscores or just vanish. | |
3e80d327 | 108 | if name.startswith('salsa20'): name = name.replace('/', '') |
837fa485 MW |
109 | else: name = name.replace('/', '_') |
110 | ||
111 | ## Done. | |
112 | return name | |
113 | ||
ed8cc62d MW |
114 | ## Initialize the module. Drag in the static methods of the various |
115 | ## classes; create names for the various known crypto algorithms. | |
d7ab1bab | 116 | def _init(): |
117 | d = globals() | |
118 | b = _base.__dict__; | |
119 | for i in b: | |
120 | if i[0] != '_': | |
121 | d[i] = b[i]; | |
bebf03ab | 122 | for i in [gcciphers, gcaeads, gchashes, gcmacs, gcprps]: |
d6542364 | 123 | for c in _itervalues(i): |
837fa485 | 124 | d[_fixname(c.name)] = c |
d6542364 | 125 | for c in _itervalues(gccrands): |
837fa485 | 126 | d[_fixname(c.name + 'rand')] = c |
d7ab1bab | 127 | _init() |
128 | ||
ed8cc62d MW |
129 | ## A handy function for our work: add the methods of a named class to an |
130 | ## existing class. This is how we write the Python-implemented parts of our | |
131 | ## mostly-C types. | |
d7ab1bab | 132 | def _augment(c, cc): |
133 | for i in cc.__dict__: | |
134 | a = cc.__dict__[i] | |
135 | if type(a) is _types.MethodType: | |
136 | a = a.im_func | |
137 | elif type(a) not in (_types.FunctionType, staticmethod, classmethod): | |
138 | continue | |
139 | setattr(c, i, a) | |
140 | ||
ed8cc62d MW |
141 | ## Parsing functions tend to return the object parsed and the remainder of |
142 | ## the input. This checks that the remainder is input and, if so, returns | |
143 | ## just the object. | |
144 | def _checkend(r): | |
145 | x, rest = r | |
146 | if rest != '': | |
1c7419c9 | 147 | raise SyntaxError('junk at end of string') |
ed8cc62d MW |
148 | return x |
149 | ||
96d7ed6c | 150 | ## Some pretty-printing utilities. |
652e16ea | 151 | PRINT_SECRETS = False |
330e6a74 | 152 | def _clsname(me): return type(me).__name__ |
652e16ea MW |
153 | def _repr_secret(thing, secretp = True): |
154 | if not secretp or PRINT_SECRETS: return repr(thing) | |
155 | else: return '#<SECRET>' | |
96d7ed6c | 156 | def _pp_str(me, pp, cyclep): pp.text(cyclep and '...' or str(me)) |
652e16ea MW |
157 | def _pp_secret(pp, thing, secretp = True): |
158 | if not secretp or PRINT_SECRETS: pp.pretty(thing) | |
159 | else: pp.text('#<SECRET>') | |
582568f1 MW |
160 | def _pp_bgroup(pp, text): |
161 | ind = len(text) | |
162 | pp.begin_group(ind, text) | |
163 | return ind | |
164 | def _pp_bgroup_tyname(pp, obj, open = '('): | |
330e6a74 | 165 | return _pp_bgroup(pp, _clsname(obj) + open) |
652e16ea | 166 | def _pp_kv(pp, k, v, secretp = False): |
582568f1 | 167 | ind = _pp_bgroup(pp, k + ' = ') |
652e16ea | 168 | _pp_secret(pp, v, secretp) |
96d7ed6c MW |
169 | pp.end_group(ind, '') |
170 | def _pp_commas(pp, printfn, items): | |
171 | firstp = True | |
172 | for i in items: | |
173 | if firstp: firstp = False | |
174 | else: pp.text(','); pp.breakable() | |
175 | printfn(i) | |
176 | def _pp_dict(pp, items): | |
85866c8a MW |
177 | def p(kv): |
178 | k, v = kv | |
582568f1 | 179 | pp.begin_group(0) |
96d7ed6c MW |
180 | pp.pretty(k) |
181 | pp.text(':') | |
582568f1 | 182 | pp.begin_group(2) |
96d7ed6c MW |
183 | pp.breakable() |
184 | pp.pretty(v) | |
582568f1 MW |
185 | pp.end_group(2) |
186 | pp.end_group(0) | |
96d7ed6c MW |
187 | _pp_commas(pp, p, items) |
188 | ||
00401529 | 189 | ###-------------------------------------------------------------------------- |
f7623015 MW |
190 | ### Mappings. |
191 | ||
192 | if _sys.version_info >= (3,): | |
193 | class _tmp: | |
194 | def __str__(me): return '%s(%r)' % (type(me).__name__, list(me)) | |
195 | __repr__ = __str__ | |
196 | def _repr_pretty_(me, pp, cyclep): | |
197 | ind = _pp_bgroup_tyname(pp, me, '([') | |
198 | _pp_commas(pp, pp.pretty, me) | |
199 | pp.end_group(ind, '])') | |
200 | _augment(_base._KeyView, _tmp) | |
201 | _augment(_base._ValueView, _tmp) | |
202 | _augment(_base._ItemView, _tmp) | |
203 | ||
204 | ###-------------------------------------------------------------------------- | |
00401529 | 205 | ### Bytestrings. |
ed8cc62d | 206 | |
d7ab1bab | 207 | class _tmp: |
208 | def fromhex(x): | |
209 | return ByteString(_unhexify(x)) | |
210 | fromhex = staticmethod(fromhex) | |
f7623015 MW |
211 | if _sys.version_info >= (3,): |
212 | def hex(me): return _hexify(me).decode() | |
213 | else: | |
214 | def hex(me): return _hexify(me) | |
215 | __hex__ = hex | |
d7ab1bab | 216 | def __repr__(me): |
ab093124 | 217 | return 'bytes(%r)' % me.hex() |
d7ab1bab | 218 | _augment(ByteString, _tmp) |
bfb450cc | 219 | ByteString.__hash__ = str.__hash__ |
d7ab1bab | 220 | bytes = ByteString.fromhex |
221 | ||
00401529 | 222 | ###-------------------------------------------------------------------------- |
bebf03ab MW |
223 | ### Symmetric encryption. |
224 | ||
225 | class _tmp: | |
3e611d87 | 226 | def encrypt(me, n, m, tsz = None, h = ByteString.zero(0)): |
bebf03ab MW |
227 | if tsz is None: tsz = me.__class__.tagsz.default |
228 | e = me.enc(n, len(h), len(m), tsz) | |
229 | if not len(h): a = None | |
230 | else: a = e.aad().hash(h) | |
231 | c0 = e.encrypt(m) | |
232 | c1, t = e.done(aad = a) | |
233 | return c0 + c1, t | |
3e611d87 | 234 | def decrypt(me, n, c, t, h = ByteString.zero(0)): |
bebf03ab MW |
235 | d = me.dec(n, len(h), len(c), len(t)) |
236 | if not len(h): a = None | |
237 | else: a = d.aad().hash(h) | |
238 | m = d.decrypt(c) | |
239 | m += d.done(t, aad = a) | |
240 | return m | |
241 | _augment(GAEKey, _tmp) | |
242 | ||
243 | ###-------------------------------------------------------------------------- | |
bfb450cc MW |
244 | ### Hashing. |
245 | ||
246 | class _tmp: | |
247 | def check(me, h): | |
248 | hh = me.done() | |
249 | return ctstreq(h, hh) | |
250 | _augment(GHash, _tmp) | |
251 | _augment(Poly1305Hash, _tmp) | |
252 | ||
6bd22b53 MW |
253 | class _HashBase (object): |
254 | ## The standard hash methods. Assume that `hash' is defined and returns | |
255 | ## the receiver. | |
05868a05 MW |
256 | def _check_range(me, n, max): |
257 | if not (0 <= n <= max): raise OverflowError("out of range") | |
258 | def hashu8(me, n): | |
259 | me._check_range(n, 0xff) | |
260 | return me.hash(_pack('B', n)) | |
261 | def hashu16l(me, n): | |
262 | me._check_range(n, 0xffff) | |
263 | return me.hash(_pack('<H', n)) | |
264 | def hashu16b(me, n): | |
265 | me._check_range(n, 0xffff) | |
266 | return me.hash(_pack('>H', n)) | |
6bd22b53 | 267 | hashu16 = hashu16b |
05868a05 MW |
268 | def hashu32l(me, n): |
269 | me._check_range(n, 0xffffffff) | |
270 | return me.hash(_pack('<L', n)) | |
271 | def hashu32b(me, n): | |
272 | me._check_range(n, 0xffffffff) | |
273 | return me.hash(_pack('>L', n)) | |
6bd22b53 | 274 | hashu32 = hashu32b |
05868a05 MW |
275 | def hashu64l(me, n): |
276 | me._check_range(n, 0xffffffffffffffff) | |
277 | return me.hash(_pack('<Q', n)) | |
278 | def hashu64b(me, n): | |
279 | me._check_range(n, 0xffffffffffffffff) | |
280 | return me.hash(_pack('>Q', n)) | |
6bd22b53 MW |
281 | hashu64 = hashu64b |
282 | def hashbuf8(me, s): return me.hashu8(len(s)).hash(s) | |
283 | def hashbuf16l(me, s): return me.hashu16l(len(s)).hash(s) | |
284 | def hashbuf16b(me, s): return me.hashu16b(len(s)).hash(s) | |
285 | hashbuf16 = hashbuf16b | |
286 | def hashbuf32l(me, s): return me.hashu32l(len(s)).hash(s) | |
287 | def hashbuf32b(me, s): return me.hashu32b(len(s)).hash(s) | |
288 | hashbuf32 = hashbuf32b | |
289 | def hashbuf64l(me, s): return me.hashu64l(len(s)).hash(s) | |
290 | def hashbuf64b(me, s): return me.hashu64b(len(s)).hash(s) | |
291 | hashbuf64 = hashbuf64b | |
292 | def hashstrz(me, s): return me.hash(s).hashu8(0) | |
293 | ||
294 | class _ShakeBase (_HashBase): | |
295 | ||
296 | ## Python gets really confused if I try to augment `__new__' on native | |
297 | ## classes, so wrap and delegate. Sorry. | |
467c2619 | 298 | def __init__(me, perso = _bin(''), *args, **kw): |
6bd22b53 MW |
299 | super(_ShakeBase, me).__init__(*args, **kw) |
300 | me._h = me._SHAKE(perso = perso, func = me._FUNC) | |
301 | ||
302 | ## Delegate methods... | |
688625b6 | 303 | def copy(me): new = me.__class__._bare_new(); new._copy(me); return new |
614c3bbf | 304 | def _copy(me, other): me._h = other._h.copy() |
6bd22b53 MW |
305 | def hash(me, m): me._h.hash(m); return me |
306 | def xof(me): me._h.xof(); return me | |
307 | def get(me, n): return me._h.get(n) | |
308 | def mask(me, m): return me._h.mask(m) | |
309 | def done(me, n): return me._h.done(n) | |
310 | def check(me, h): return ctstreq(h, me.done(len(h))) | |
311 | @property | |
312 | def state(me): return me._h.state | |
313 | @property | |
314 | def buffered(me): return me._h.buffered | |
315 | @property | |
316 | def rate(me): return me._h.rate | |
688625b6 MW |
317 | @classmethod |
318 | def _bare_new(cls): return cls() | |
6bd22b53 MW |
319 | |
320 | class _tmp: | |
321 | def check(me, h): | |
322 | return ctstreq(h, me.done(len(h))) | |
323 | def leftenc(me, n): | |
324 | nn = MP(n).storeb() | |
325 | return me.hashu8(len(nn)).hash(nn) | |
326 | def rightenc(me, n): | |
327 | nn = MP(n).storeb() | |
328 | return me.hash(nn).hashu8(len(nn)) | |
329 | def stringenc(me, str): | |
330 | return me.leftenc(8*len(str)).hash(str) | |
331 | def bytepad_before(me): | |
332 | return me.leftenc(me.rate) | |
333 | def bytepad_after(me): | |
334 | if me.buffered: me.hash(me._Z[:me.rate - me.buffered]) | |
335 | return me | |
336 | @_ctxmgr | |
337 | def bytepad(me): | |
338 | me.bytepad_before() | |
339 | yield me | |
340 | me.bytepad_after() | |
341 | _augment(Shake, _tmp) | |
342 | _augment(_ShakeBase, _tmp) | |
f22cdfa9 | 343 | Shake._Z = _ShakeBase._Z = ByteString.zero(200) |
6bd22b53 MW |
344 | |
345 | class KMAC (_ShakeBase): | |
467c2619 | 346 | _FUNC = _bin('KMAC') |
6bd22b53 MW |
347 | def __init__(me, k, *arg, **kw): |
348 | super(KMAC, me).__init__(*arg, **kw) | |
349 | with me.bytepad(): me.stringenc(k) | |
350 | def done(me, n = -1): | |
351 | if n < 0: n = me._TAGSZ | |
352 | me.rightenc(8*n) | |
353 | return super(KMAC, me).done(n) | |
354 | def xof(me): | |
355 | me.rightenc(0) | |
356 | return super(KMAC, me).xof() | |
688625b6 | 357 | @classmethod |
467c2619 | 358 | def _bare_new(cls): return cls(_bin("")) |
6bd22b53 MW |
359 | |
360 | class KMAC128 (KMAC): _SHAKE = Shake128; _TAGSZ = 16 | |
361 | class KMAC256 (KMAC): _SHAKE = Shake256; _TAGSZ = 32 | |
362 | ||
bfb450cc | 363 | ###-------------------------------------------------------------------------- |
ce0340b6 MW |
364 | ### NaCl `secretbox'. |
365 | ||
366 | def secret_box(k, n, m): | |
bebf03ab | 367 | y, t = salsa20_naclbox(k).encrypt(n, m) |
bb5c23a4 | 368 | return t + y |
ce0340b6 MW |
369 | |
370 | def secret_unbox(k, n, c): | |
bebf03ab MW |
371 | tsz = poly1305.tagsz |
372 | return salsa20_naclbox(k).decrypt(n, c[tsz:], c[0:tsz]) | |
ce0340b6 MW |
373 | |
374 | ###-------------------------------------------------------------------------- | |
00401529 | 375 | ### Multiprecision integers and binary polynomials. |
ed8cc62d | 376 | |
2ef393b5 | 377 | def _split_rat(x): |
83c77564 | 378 | if isinstance(x, BaseRat): return x._n, x._d |
2ef393b5 | 379 | else: return x, 1 |
83c77564 MW |
380 | class BaseRat (object): |
381 | """Base class implementing fields of fractions over Euclidean domains.""" | |
2ef393b5 | 382 | def __new__(cls, a, b): |
83c77564 | 383 | a, b = cls.RING(a), cls.RING(b) |
2ef393b5 MW |
384 | q, r = divmod(a, b) |
385 | if r == 0: return q | |
386 | g = b.gcd(r) | |
83c77564 | 387 | me = super(BaseRat, cls).__new__(cls) |
2ef393b5 MW |
388 | me._n = a//g |
389 | me._d = b//g | |
390 | return me | |
391 | @property | |
392 | def numer(me): return me._n | |
393 | @property | |
394 | def denom(me): return me._d | |
395 | def __str__(me): return '%s/%s' % (me._n, me._d) | |
330e6a74 | 396 | def __repr__(me): return '%s(%s, %s)' % (_clsname(me), me._n, me._d) |
96d7ed6c | 397 | _repr_pretty_ = _pp_str |
2ef393b5 MW |
398 | |
399 | def __add__(me, you): | |
400 | n, d = _split_rat(you) | |
83c77564 | 401 | return type(me)(me._n*d + n*me._d, d*me._d) |
2ef393b5 MW |
402 | __radd__ = __add__ |
403 | def __sub__(me, you): | |
404 | n, d = _split_rat(you) | |
83c77564 | 405 | return type(me)(me._n*d - n*me._d, d*me._d) |
2ef393b5 MW |
406 | def __rsub__(me, you): |
407 | n, d = _split_rat(you) | |
83c77564 | 408 | return type(me)(n*me._d - me._n*d, d*me._d) |
2ef393b5 MW |
409 | def __mul__(me, you): |
410 | n, d = _split_rat(you) | |
83c77564 | 411 | return type(me)(me._n*n, me._d*d) |
08041ebb | 412 | __rmul__ = __mul__ |
b47818ea | 413 | def __truediv__(me, you): |
2ef393b5 | 414 | n, d = _split_rat(you) |
83c77564 | 415 | return type(me)(me._n*d, me._d*n) |
b47818ea | 416 | def __rtruediv__(me, you): |
2ef393b5 | 417 | n, d = _split_rat(you) |
83c77564 | 418 | return type(me)(me._d*n, me._n*d) |
f7623015 MW |
419 | if _sys.version_info < (3,): |
420 | __div__ = __truediv__ | |
421 | __rdiv__ = __rtruediv__ | |
54ee272d | 422 | def _order(me, you, op): |
2ef393b5 | 423 | n, d = _split_rat(you) |
54ee272d MW |
424 | return op(me._n*d, n*me._d) |
425 | def __eq__(me, you): return me._order(you, lambda x, y: x == y) | |
426 | def __ne__(me, you): return me._order(you, lambda x, y: x != y) | |
427 | def __le__(me, you): return me._order(you, lambda x, y: x <= y) | |
428 | def __lt__(me, you): return me._order(you, lambda x, y: x < y) | |
429 | def __gt__(me, you): return me._order(you, lambda x, y: x > y) | |
430 | def __ge__(me, you): return me._order(you, lambda x, y: x >= y) | |
2ef393b5 | 431 | |
83c77564 MW |
432 | class IntRat (BaseRat): |
433 | RING = MP | |
77535854 MW |
434 | def __new__(cls, a, b): |
435 | if isinstance(a, float) or isinstance(b, float): return a/b | |
436 | return super(IntRat, cls).__new__(cls, a, b) | |
437 | def __float__(me): return float(me._n)/float(me._d) | |
83c77564 MW |
438 | |
439 | class GFRat (BaseRat): | |
440 | RING = GF | |
441 | ||
d7ab1bab | 442 | class _tmp: |
443 | def negp(x): return x < 0 | |
444 | def posp(x): return x > 0 | |
445 | def zerop(x): return x == 0 | |
446 | def oddp(x): return x.testbit(0) | |
447 | def evenp(x): return not x.testbit(0) | |
448 | def mont(x): return MPMont(x) | |
449 | def barrett(x): return MPBarrett(x) | |
450 | def reduce(x): return MPReduce(x) | |
77535854 MW |
451 | def __truediv__(me, you): |
452 | if isinstance(you, float): return _long(me)/you | |
453 | else: return IntRat(me, you) | |
454 | def __rtruediv__(me, you): | |
455 | if isinstance(you, float): return you/_long(me) | |
456 | else: return IntRat(you, me) | |
f7623015 MW |
457 | if _sys.version_info < (3,): |
458 | __div__ = __truediv__ | |
459 | __rdiv__ = __rtruediv__ | |
96d7ed6c | 460 | _repr_pretty_ = _pp_str |
d7ab1bab | 461 | _augment(MP, _tmp) |
462 | ||
d7ab1bab | 463 | class _tmp: |
fbc145f3 | 464 | def zerop(x): return x == 0 |
ed8cc62d | 465 | def reduce(x): return GFReduce(x) |
fbc145f3 MW |
466 | def trace(x, y): return x.reduce().trace(y) |
467 | def halftrace(x, y): return x.reduce().halftrace(y) | |
468 | def modsqrt(x, y): return x.reduce().sqrt(y) | |
469 | def quadsolve(x, y): return x.reduce().quadsolve(y) | |
b47818ea MW |
470 | def __truediv__(me, you): return GFRat(me, you) |
471 | def __rtruediv__(me, you): return GFRat(you, me) | |
f7623015 MW |
472 | if _sys.version_info < (3,): |
473 | __div__ = __truediv__ | |
474 | __rdiv__ = __rtruediv__ | |
96d7ed6c | 475 | _repr_pretty_ = _pp_str |
d7ab1bab | 476 | _augment(GF, _tmp) |
477 | ||
478 | class _tmp: | |
ed8cc62d MW |
479 | def product(*arg): |
480 | 'product(ITERABLE) or product(I, ...) -> PRODUCT' | |
481 | return MPMul(*arg).done() | |
482 | product = staticmethod(product) | |
483 | _augment(MPMul, _tmp) | |
484 | ||
00401529 MW |
485 | ###-------------------------------------------------------------------------- |
486 | ### Abstract fields. | |
ed8cc62d MW |
487 | |
488 | class _tmp: | |
d7ab1bab | 489 | def fromstring(str): return _checkend(Field.parse(str)) |
490 | fromstring = staticmethod(fromstring) | |
491 | _augment(Field, _tmp) | |
492 | ||
493 | class _tmp: | |
e38168e2 | 494 | def __repr__(me): return '%s(%s)' % (_clsname(me), me.p) |
6d481bc6 | 495 | def __hash__(me): return 0x114401de ^ hash(me.p) |
96d7ed6c | 496 | def _repr_pretty_(me, pp, cyclep): |
582568f1 MW |
497 | ind = _pp_bgroup_tyname(pp, me) |
498 | if cyclep: pp.text('...') | |
499 | else: pp.pretty(me.p) | |
500 | pp.end_group(ind, ')') | |
d7ab1bab | 501 | def ec(me, a, b): return ECPrimeProjCurve(me, a, b) |
502 | _augment(PrimeField, _tmp) | |
503 | ||
504 | class _tmp: | |
e38168e2 | 505 | def __repr__(me): return '%s(%#x)' % (_clsname(me), me.p) |
d7ab1bab | 506 | def ec(me, a, b): return ECBinProjCurve(me, a, b) |
96d7ed6c | 507 | def _repr_pretty_(me, pp, cyclep): |
582568f1 MW |
508 | ind = _pp_bgroup_tyname(pp, me) |
509 | if cyclep: pp.text('...') | |
510 | else: pp.text('%#x' % me.p) | |
511 | pp.end_group(ind, ')') | |
d7ab1bab | 512 | _augment(BinField, _tmp) |
513 | ||
514 | class _tmp: | |
6d481bc6 MW |
515 | def __hash__(me): return 0x23e4701c ^ hash(me.p) |
516 | _augment(BinPolyField, _tmp) | |
517 | ||
518 | class _tmp: | |
519 | def __hash__(me): | |
520 | h = 0x9a7d6240 | |
521 | h ^= hash(me.p) | |
522 | h ^= 2*hash(me.beta) & 0xffffffff | |
523 | return h | |
524 | _augment(BinNormField, _tmp) | |
525 | ||
526 | class _tmp: | |
d7ab1bab | 527 | def __str__(me): return str(me.value) |
528 | def __repr__(me): return '%s(%s)' % (repr(me.field), repr(me.value)) | |
96d7ed6c | 529 | _repr_pretty_ = _pp_str |
d7ab1bab | 530 | _augment(FE, _tmp) |
531 | ||
00401529 MW |
532 | ###-------------------------------------------------------------------------- |
533 | ### Elliptic curves. | |
d7ab1bab | 534 | |
535 | class _tmp: | |
536 | def __repr__(me): | |
330e6a74 | 537 | return '%s(%r, %s, %s)' % (_clsname(me), me.field, me.a, me.b) |
96d7ed6c | 538 | def _repr_pretty_(me, pp, cyclep): |
582568f1 | 539 | ind = _pp_bgroup_tyname(pp, me) |
96d7ed6c | 540 | if cyclep: |
582568f1 | 541 | pp.text('...') |
96d7ed6c | 542 | else: |
96d7ed6c MW |
543 | pp.pretty(me.field); pp.text(','); pp.breakable() |
544 | pp.pretty(me.a); pp.text(','); pp.breakable() | |
545 | pp.pretty(me.b) | |
582568f1 | 546 | pp.end_group(ind, ')') |
d7ab1bab | 547 | def frombuf(me, s): |
548 | return ecpt.frombuf(me, s) | |
549 | def fromraw(me, s): | |
550 | return ecpt.fromraw(me, s) | |
551 | def pt(me, *args): | |
5f959e50 | 552 | return me(*args) |
d7ab1bab | 553 | _augment(ECCurve, _tmp) |
554 | ||
555 | class _tmp: | |
6d481bc6 MW |
556 | def __hash__(me): |
557 | h = 0x6751d341 | |
558 | h ^= hash(me.field) | |
559 | h ^= 2*hash(me.a) ^ 0xffffffff | |
560 | h ^= 5*hash(me.b) ^ 0xffffffff | |
561 | return h | |
562 | _augment(ECPrimeCurve, _tmp) | |
563 | ||
564 | class _tmp: | |
565 | def __hash__(me): | |
566 | h = 0x2ac203c5 | |
567 | h ^= hash(me.field) | |
568 | h ^= 2*hash(me.a) ^ 0xffffffff | |
569 | h ^= 5*hash(me.b) ^ 0xffffffff | |
570 | return h | |
571 | _augment(ECBinCurve, _tmp) | |
572 | ||
573 | class _tmp: | |
d7ab1bab | 574 | def __repr__(me): |
330e6a74 MW |
575 | if not me: return '%s()' % _clsname(me) |
576 | return '%s(%s, %s)' % (_clsname(me), me.ix, me.iy) | |
d7ab1bab | 577 | def __str__(me): |
578 | if not me: return 'inf' | |
579 | return '(%s, %s)' % (me.ix, me.iy) | |
96d7ed6c MW |
580 | def _repr_pretty_(me, pp, cyclep): |
581 | if cyclep: | |
582 | pp.text('...') | |
583 | elif not me: | |
584 | pp.text('inf') | |
585 | else: | |
582568f1 | 586 | ind = _pp_bgroup(pp, '(') |
96d7ed6c MW |
587 | pp.pretty(me.ix); pp.text(','); pp.breakable() |
588 | pp.pretty(me.iy) | |
582568f1 | 589 | pp.end_group(ind, ')') |
d7ab1bab | 590 | _augment(ECPt, _tmp) |
591 | ||
592 | class _tmp: | |
593 | def __repr__(me): | |
330e6a74 MW |
594 | return '%s(curve = %r, G = %r, r = %s, h = %s)' % \ |
595 | (_clsname(me), me.curve, me.G, me.r, me.h) | |
96d7ed6c | 596 | def _repr_pretty_(me, pp, cyclep): |
582568f1 | 597 | ind = _pp_bgroup_tyname(pp, me) |
96d7ed6c | 598 | if cyclep: |
582568f1 | 599 | pp.text('...') |
96d7ed6c | 600 | else: |
96d7ed6c MW |
601 | _pp_kv(pp, 'curve', me.curve); pp.text(','); pp.breakable() |
602 | _pp_kv(pp, 'G', me.G); pp.text(','); pp.breakable() | |
603 | _pp_kv(pp, 'r', me.r); pp.text(','); pp.breakable() | |
604 | _pp_kv(pp, 'h', me.h) | |
582568f1 | 605 | pp.end_group(ind, ')') |
6d481bc6 MW |
606 | def __hash__(me): |
607 | h = 0x9bedb8de | |
608 | h ^= hash(me.curve) | |
609 | h ^= 2*hash(me.G) & 0xffffffff | |
610 | return h | |
d7ab1bab | 611 | def group(me): |
612 | return ECGroup(me) | |
613 | _augment(ECInfo, _tmp) | |
614 | ||
615 | class _tmp: | |
616 | def __repr__(me): | |
617 | if not me: return '%r()' % (me.curve) | |
618 | return '%r(%s, %s)' % (me.curve, me.x, me.y) | |
619 | def __str__(me): | |
620 | if not me: return 'inf' | |
621 | return '(%s, %s)' % (me.x, me.y) | |
7a7aa30e MW |
622 | def _repr_pretty_(me, pp, cyclep): |
623 | if cyclep: | |
624 | pp.text('...') | |
625 | elif not me: | |
626 | pp.text('inf') | |
627 | else: | |
628 | ind = _pp_bgroup(pp, '(') | |
629 | pp.pretty(me.x); pp.text(','); pp.breakable() | |
630 | pp.pretty(me.y) | |
631 | pp.end_group(ind, ')') | |
d7ab1bab | 632 | _augment(ECPtCurve, _tmp) |
633 | ||
00401529 MW |
634 | ###-------------------------------------------------------------------------- |
635 | ### Key sizes. | |
ed8cc62d | 636 | |
d7ab1bab | 637 | class _tmp: |
330e6a74 | 638 | def __repr__(me): return '%s(%d)' % (_clsname(me), me.default) |
d7ab1bab | 639 | def check(me, sz): return True |
640 | def best(me, sz): return sz | |
dfb915d3 | 641 | def pad(me, sz): return sz |
d7ab1bab | 642 | _augment(KeySZAny, _tmp) |
643 | ||
644 | class _tmp: | |
645 | def __repr__(me): | |
330e6a74 MW |
646 | return '%s(%d, %d, %d, %d)' % \ |
647 | (_clsname(me), me.default, me.min, me.max, me.mod) | |
96d7ed6c | 648 | def _repr_pretty_(me, pp, cyclep): |
582568f1 | 649 | ind = _pp_bgroup_tyname(pp, me) |
96d7ed6c | 650 | if cyclep: |
582568f1 | 651 | pp.text('...') |
96d7ed6c | 652 | else: |
96d7ed6c MW |
653 | pp.pretty(me.default); pp.text(','); pp.breakable() |
654 | pp.pretty(me.min); pp.text(','); pp.breakable() | |
655 | pp.pretty(me.max); pp.text(','); pp.breakable() | |
656 | pp.pretty(me.mod) | |
582568f1 | 657 | pp.end_group(ind, ')') |
dfb915d3 | 658 | def check(me, sz): return me.min <= sz <= me.max and sz%me.mod == 0 |
d7ab1bab | 659 | def best(me, sz): |
1c7419c9 | 660 | if sz < me.min: raise ValueError('key too small') |
a9410db7 | 661 | elif me.max is not None and sz > me.max: return me.max |
dfb915d3 MW |
662 | else: return sz - sz%me.mod |
663 | def pad(me, sz): | |
a9410db7 | 664 | if me.max is not None and sz > me.max: raise ValueError('key too large') |
dfb915d3 | 665 | elif sz < me.min: return me.min |
8fc76cc0 | 666 | else: sz += me.mod - 1; return sz - sz%me.mod |
d7ab1bab | 667 | _augment(KeySZRange, _tmp) |
668 | ||
669 | class _tmp: | |
330e6a74 | 670 | def __repr__(me): return '%s(%d, %s)' % (_clsname(me), me.default, me.set) |
96d7ed6c | 671 | def _repr_pretty_(me, pp, cyclep): |
582568f1 | 672 | ind = _pp_bgroup_tyname(pp, me) |
96d7ed6c | 673 | if cyclep: |
582568f1 | 674 | pp.text('...') |
96d7ed6c | 675 | else: |
96d7ed6c | 676 | pp.pretty(me.default); pp.text(','); pp.breakable() |
582568f1 | 677 | ind1 = _pp_bgroup(pp, '{') |
96d7ed6c | 678 | _pp_commas(pp, pp.pretty, me.set) |
582568f1 MW |
679 | pp.end_group(ind1, '}') |
680 | pp.end_group(ind, ')') | |
d7ab1bab | 681 | def check(me, sz): return sz in me.set |
682 | def best(me, sz): | |
683 | found = -1 | |
684 | for i in me.set: | |
685 | if found < i <= sz: found = i | |
1c7419c9 | 686 | if found < 0: raise ValueError('key too small') |
d7ab1bab | 687 | return found |
dfb915d3 MW |
688 | def pad(me, sz): |
689 | found = -1 | |
690 | for i in me.set: | |
691 | if sz <= i and (found == -1 or i < found): found = i | |
1c7419c9 | 692 | if found < 0: raise ValueError('key too large') |
dfb915d3 | 693 | return found |
d7ab1bab | 694 | _augment(KeySZSet, _tmp) |
695 | ||
00401529 | 696 | ###-------------------------------------------------------------------------- |
96d7ed6c MW |
697 | ### Key data objects. |
698 | ||
699 | class _tmp: | |
618cbc92 MW |
700 | def merge(me, file, report = None): |
701 | """KF.merge(FILE, [report = <built-in-reporter>])""" | |
702 | name = file.name | |
703 | lno = 1 | |
704 | for line in file: | |
705 | me.mergeline(name, lno, line, report) | |
706 | lno += 1 | |
707 | return me | |
330e6a74 | 708 | def __repr__(me): return '%s(%r)' % (_clsname(me), me.name) |
96d7ed6c MW |
709 | _augment(KeyFile, _tmp) |
710 | ||
711 | class _tmp: | |
618cbc92 MW |
712 | def extract(me, file, filter = ''): |
713 | """KEY.extract(FILE, [filter = <any>])""" | |
714 | line = me.extractline(filter) | |
715 | file.write(line) | |
716 | return me | |
330e6a74 | 717 | def __repr__(me): return '%s(%r)' % (_clsname(me), me.fulltag) |
96d7ed6c MW |
718 | _augment(Key, _tmp) |
719 | ||
720 | class _tmp: | |
721 | def __repr__(me): | |
330e6a74 | 722 | return '%s({%s})' % (_clsname(me), |
d6542364 | 723 | ', '.join(['%r: %r' % kv for kv in _iteritems(me)()])) |
96d7ed6c | 724 | def _repr_pretty_(me, pp, cyclep): |
582568f1 | 725 | ind = _pp_bgroup_tyname(pp, me) |
96d7ed6c | 726 | if cyclep: pp.text('...') |
d6542364 | 727 | else: _pp_dict(pp, _iteritems(me)) |
582568f1 | 728 | pp.end_group(ind, ')') |
96d7ed6c MW |
729 | _augment(KeyAttributes, _tmp) |
730 | ||
731 | class _tmp: | |
849e8a20 | 732 | def __repr__(me): |
652e16ea MW |
733 | return '%s(%s, %r)' % (_clsname(me), |
734 | _repr_secret(me._guts(), | |
735 | not (me.flags & KF_NONSECRET)), | |
736 | me.writeflags(me.flags)) | |
96d7ed6c | 737 | def _repr_pretty_(me, pp, cyclep): |
582568f1 | 738 | ind = _pp_bgroup_tyname(pp, me) |
96d7ed6c | 739 | if cyclep: |
582568f1 | 740 | pp.text('...') |
96d7ed6c | 741 | else: |
652e16ea MW |
742 | _pp_secret(pp, me._guts(), not (me.flags & KF_NONSECRET)) |
743 | pp.text(','); pp.breakable() | |
96d7ed6c | 744 | pp.pretty(me.writeflags(me.flags)) |
582568f1 | 745 | pp.end_group(ind, ')') |
c567f805 MW |
746 | def __hash__(me): return me._HASHBASE ^ hash(me._guts()) |
747 | def __eq__(me, kd): | |
748 | return type(me) == type(kd) and \ | |
749 | me._guts() == kd._guts() and \ | |
750 | me.flags == kd.flags | |
751 | def __ne__(me, kd): | |
752 | return not me == kd | |
849e8a20 MW |
753 | _augment(KeyData, _tmp) |
754 | ||
755 | class _tmp: | |
756 | def _guts(me): return me.bin | |
c567f805 MW |
757 | def __eq__(me, kd): |
758 | return isinstance(kd, KeyDataBinary) and me.bin == kd.bin | |
96d7ed6c | 759 | _augment(KeyDataBinary, _tmp) |
c567f805 | 760 | KeyDataBinary._HASHBASE = 0x961755c3 |
96d7ed6c MW |
761 | |
762 | class _tmp: | |
849e8a20 | 763 | def _guts(me): return me.ct |
96d7ed6c | 764 | _augment(KeyDataEncrypted, _tmp) |
c567f805 | 765 | KeyDataEncrypted._HASHBASE = 0xffe000d4 |
96d7ed6c MW |
766 | |
767 | class _tmp: | |
849e8a20 | 768 | def _guts(me): return me.mp |
96d7ed6c | 769 | _augment(KeyDataMP, _tmp) |
c567f805 | 770 | KeyDataMP._HASHBASE = 0x1cb64d69 |
96d7ed6c MW |
771 | |
772 | class _tmp: | |
849e8a20 | 773 | def _guts(me): return me.str |
96d7ed6c | 774 | _augment(KeyDataString, _tmp) |
c567f805 | 775 | KeyDataString._HASHBASE = 0x349c33ea |
96d7ed6c MW |
776 | |
777 | class _tmp: | |
849e8a20 | 778 | def _guts(me): return me.ecpt |
96d7ed6c | 779 | _augment(KeyDataECPt, _tmp) |
c567f805 | 780 | KeyDataECPt._HASHBASE = 0x2509718b |
96d7ed6c MW |
781 | |
782 | class _tmp: | |
783 | def __repr__(me): | |
330e6a74 | 784 | return '%s({%s})' % (_clsname(me), |
d6542364 | 785 | ', '.join(['%r: %r' % kv for kv in _iteritems(me)])) |
96d7ed6c | 786 | def _repr_pretty_(me, pp, cyclep): |
582568f1 | 787 | ind = _pp_bgroup_tyname(pp, me, '({ ') |
96d7ed6c | 788 | if cyclep: pp.text('...') |
d6542364 | 789 | else: _pp_dict(pp, _iteritems(me)) |
582568f1 | 790 | pp.end_group(ind, ' })') |
c567f805 MW |
791 | def __hash__(me): |
792 | h = me._HASHBASE | |
793 | for k, v in _iteritems(me): | |
794 | h = ((h << 1) ^ 3*hash(k) ^ 5*hash(v))&0xffffffff | |
795 | return h | |
796 | def __eq__(me, kd): | |
797 | if type(me) != type(kd) or me.flags != kd.flags or len(me) != len(kd): | |
798 | return False | |
799 | for k, v in _iteritems(me): | |
800 | try: vv = kd[k] | |
801 | except KeyError: return False | |
802 | if v != vv: return False | |
803 | return True | |
96d7ed6c | 804 | _augment(KeyDataStructured, _tmp) |
c567f805 | 805 | KeyDataStructured._HASHBASE = 0x85851b21 |
96d7ed6c MW |
806 | |
807 | ###-------------------------------------------------------------------------- | |
00401529 | 808 | ### Abstract groups. |
ed8cc62d | 809 | |
d7ab1bab | 810 | class _tmp: |
811 | def __repr__(me): | |
330e6a74 | 812 | return '%s(p = %s, r = %s, g = %s)' % (_clsname(me), me.p, me.r, me.g) |
96d7ed6c | 813 | def _repr_pretty_(me, pp, cyclep): |
582568f1 | 814 | ind = _pp_bgroup_tyname(pp, me) |
96d7ed6c | 815 | if cyclep: |
582568f1 | 816 | pp.text('...') |
96d7ed6c | 817 | else: |
96d7ed6c MW |
818 | _pp_kv(pp, 'p', me.p); pp.text(','); pp.breakable() |
819 | _pp_kv(pp, 'r', me.r); pp.text(','); pp.breakable() | |
820 | _pp_kv(pp, 'g', me.g) | |
582568f1 | 821 | pp.end_group(ind, ')') |
d7ab1bab | 822 | _augment(FGInfo, _tmp) |
823 | ||
824 | class _tmp: | |
825 | def group(me): return PrimeGroup(me) | |
826 | _augment(DHInfo, _tmp) | |
827 | ||
828 | class _tmp: | |
829 | def group(me): return BinGroup(me) | |
830 | _augment(BinDHInfo, _tmp) | |
831 | ||
832 | class _tmp: | |
833 | def __repr__(me): | |
330e6a74 | 834 | return '%s(%r)' % (_clsname(me), me.info) |
99d932fe MW |
835 | def _repr_pretty_(me, pp, cyclep): |
836 | ind = _pp_bgroup_tyname(pp, me) | |
837 | if cyclep: pp.text('...') | |
838 | else: pp.pretty(me.info) | |
839 | pp.end_group(ind, ')') | |
d7ab1bab | 840 | _augment(Group, _tmp) |
841 | ||
842 | class _tmp: | |
6d481bc6 MW |
843 | def __hash__(me): |
844 | info = me.info | |
845 | h = 0xbce3cfe6 | |
846 | h ^= hash(info.p) | |
847 | h ^= 2*hash(info.r) & 0xffffffff | |
848 | h ^= 5*hash(info.g) & 0xffffffff | |
849 | return h | |
d7012c2b | 850 | def _get_geval(me, x): return MP(x) |
6d481bc6 MW |
851 | _augment(PrimeGroup, _tmp) |
852 | ||
853 | class _tmp: | |
854 | def __hash__(me): | |
855 | info = me.info | |
856 | h = 0x80695949 | |
857 | h ^= hash(info.p) | |
858 | h ^= 2*hash(info.r) & 0xffffffff | |
859 | h ^= 5*hash(info.g) & 0xffffffff | |
860 | return h | |
d7012c2b | 861 | def _get_geval(me, x): return GF(x) |
6d481bc6 MW |
862 | _augment(BinGroup, _tmp) |
863 | ||
864 | class _tmp: | |
865 | def __hash__(me): return 0x0ec23dab ^ hash(me.info) | |
d7012c2b | 866 | def _get_geval(me, x): return x.toec() |
6d481bc6 MW |
867 | _augment(ECGroup, _tmp) |
868 | ||
869 | class _tmp: | |
d7ab1bab | 870 | def __repr__(me): |
871 | return '%r(%r)' % (me.group, str(me)) | |
d7012c2b MW |
872 | def _repr_pretty_(me, pp, cyclep): |
873 | pp.pretty(type(me)._get_geval(me)) | |
d7ab1bab | 874 | _augment(GE, _tmp) |
875 | ||
00401529 MW |
876 | ###-------------------------------------------------------------------------- |
877 | ### RSA encoding techniques. | |
ed8cc62d MW |
878 | |
879 | class PKCS1Crypt (object): | |
467c2619 | 880 | def __init__(me, ep = _bin(''), rng = rand): |
d7ab1bab | 881 | me.ep = ep |
882 | me.rng = rng | |
883 | def encode(me, msg, nbits): | |
884 | return _base._p1crypt_encode(msg, nbits, me.ep, me.rng) | |
885 | def decode(me, ct, nbits): | |
886 | return _base._p1crypt_decode(ct, nbits, me.ep, me.rng) | |
887 | ||
ed8cc62d | 888 | class PKCS1Sig (object): |
467c2619 | 889 | def __init__(me, ep = _bin(''), rng = rand): |
d7ab1bab | 890 | me.ep = ep |
891 | me.rng = rng | |
892 | def encode(me, msg, nbits): | |
893 | return _base._p1sig_encode(msg, nbits, me.ep, me.rng) | |
894 | def decode(me, msg, sig, nbits): | |
895 | return _base._p1sig_decode(msg, sig, nbits, me.ep, me.rng) | |
896 | ||
ed8cc62d | 897 | class OAEP (object): |
467c2619 | 898 | def __init__(me, mgf = sha_mgf, hash = sha, ep = _bin(''), rng = rand): |
d7ab1bab | 899 | me.mgf = mgf |
900 | me.hash = hash | |
901 | me.ep = ep | |
902 | me.rng = rng | |
903 | def encode(me, msg, nbits): | |
904 | return _base._oaep_encode(msg, nbits, me.mgf, me.hash, me.ep, me.rng) | |
905 | def decode(me, ct, nbits): | |
906 | return _base._oaep_decode(ct, nbits, me.mgf, me.hash, me.ep, me.rng) | |
907 | ||
ed8cc62d | 908 | class PSS (object): |
d7ab1bab | 909 | def __init__(me, mgf = sha_mgf, hash = sha, saltsz = None, rng = rand): |
910 | me.mgf = mgf | |
911 | me.hash = hash | |
912 | if saltsz is None: | |
913 | saltsz = hash.hashsz | |
914 | me.saltsz = saltsz | |
915 | me.rng = rng | |
916 | def encode(me, msg, nbits): | |
917 | return _base._pss_encode(msg, nbits, me.mgf, me.hash, me.saltsz, me.rng) | |
918 | def decode(me, msg, sig, nbits): | |
919 | return _base._pss_decode(msg, sig, nbits, | |
00401529 | 920 | me.mgf, me.hash, me.saltsz, me.rng) |
d7ab1bab | 921 | |
922 | class _tmp: | |
923 | def encrypt(me, msg, enc): | |
924 | return me.pubop(enc.encode(msg, me.n.nbits)) | |
925 | def verify(me, msg, sig, enc): | |
926 | if msg is None: return enc.decode(msg, me.pubop(sig), me.n.nbits) | |
927 | try: | |
928 | x = enc.decode(msg, me.pubop(sig), me.n.nbits) | |
929 | return x is None or x == msg | |
930 | except ValueError: | |
b2687a0a | 931 | return False |
bbd94558 MW |
932 | def __repr__(me): |
933 | return '%s(n = %r, e = %r)' % (_clsname(me), me.n, me.e) | |
934 | def _repr_pretty_(me, pp, cyclep): | |
935 | ind = _pp_bgroup_tyname(pp, me) | |
936 | if cyclep: | |
937 | pp.text('...') | |
938 | else: | |
939 | _pp_kv(pp, 'n', me.n); pp.text(','); pp.breakable() | |
940 | _pp_kv(pp, 'e', me.e) | |
941 | pp.end_group(ind, ')') | |
d7ab1bab | 942 | _augment(RSAPub, _tmp) |
943 | ||
944 | class _tmp: | |
945 | def decrypt(me, ct, enc): return enc.decode(me.privop(ct), me.n.nbits) | |
946 | def sign(me, msg, enc): return me.privop(enc.encode(msg, me.n.nbits)) | |
bbd94558 MW |
947 | def __repr__(me): |
948 | return '%s(n = %r, e = %r, d = %s, ' \ | |
949 | 'p = %s, q = %s, dp = %s, dq = %s, q_inv = %s)' % \ | |
950 | (_clsname(me), me.n, me.e, | |
951 | _repr_secret(me.d), _repr_secret(me.p), _repr_secret(me.q), | |
952 | _repr_secret(me.dp), _repr_secret(me.dq), _repr_secret(me.q_inv)) | |
953 | def _repr_pretty_(me, pp, cyclep): | |
954 | ind = _pp_bgroup_tyname(pp, me) | |
955 | if cyclep: | |
956 | pp.text('...') | |
957 | else: | |
958 | _pp_kv(pp, 'n', me.n); pp.text(','); pp.breakable() | |
959 | _pp_kv(pp, 'e', me.e); pp.text(','); pp.breakable() | |
960 | _pp_kv(pp, 'd', me.d, secretp = True); pp.text(','); pp.breakable() | |
961 | _pp_kv(pp, 'p', me.p, secretp = True); pp.text(','); pp.breakable() | |
962 | _pp_kv(pp, 'q', me.q, secretp = True); pp.text(','); pp.breakable() | |
963 | _pp_kv(pp, 'dp', me.dp, secretp = True); pp.text(','); pp.breakable() | |
964 | _pp_kv(pp, 'dq', me.dq, secretp = True); pp.text(','); pp.breakable() | |
965 | _pp_kv(pp, 'q_inv', me.q_inv, secretp = True) | |
966 | pp.end_group(ind, ')') | |
d7ab1bab | 967 | _augment(RSAPriv, _tmp) |
968 | ||
00401529 | 969 | ###-------------------------------------------------------------------------- |
bbd94558 MW |
970 | ### DSA and related schemes. |
971 | ||
972 | class _tmp: | |
1b3b79da MW |
973 | def __repr__(me): return '%s(G = %r, p = %r, hash = %r)' % \ |
974 | (_clsname(me), me.G, me.p, me.hash) | |
bbd94558 MW |
975 | def _repr_pretty_(me, pp, cyclep): |
976 | ind = _pp_bgroup_tyname(pp, me) | |
977 | if cyclep: | |
978 | pp.text('...') | |
979 | else: | |
980 | _pp_kv(pp, 'G', me.G); pp.text(','); pp.breakable() | |
1b3b79da MW |
981 | _pp_kv(pp, 'p', me.p); pp.text(','); pp.breakable() |
982 | _pp_kv(pp, 'hash', me.hash) | |
bbd94558 MW |
983 | pp.end_group(ind, ')') |
984 | _augment(DSAPub, _tmp) | |
985 | _augment(KCDSAPub, _tmp) | |
986 | ||
987 | class _tmp: | |
1b3b79da MW |
988 | def __repr__(me): return '%s(G = %r, u = %s, p = %r, hash = %r)' % \ |
989 | (_clsname(me), me.G, _repr_secret(me.u), me.p, me.hash) | |
bbd94558 MW |
990 | def _repr_pretty_(me, pp, cyclep): |
991 | ind = _pp_bgroup_tyname(pp, me) | |
992 | if cyclep: | |
993 | pp.text('...') | |
994 | else: | |
995 | _pp_kv(pp, 'G', me.G); pp.text(','); pp.breakable() | |
996 | _pp_kv(pp, 'u', me.u, True); pp.text(','); pp.breakable() | |
1b3b79da MW |
997 | _pp_kv(pp, 'p', me.p); pp.text(','); pp.breakable() |
998 | _pp_kv(pp, 'hash', me.hash) | |
bbd94558 MW |
999 | pp.end_group(ind, ')') |
1000 | _augment(DSAPriv, _tmp) | |
1001 | _augment(KCDSAPriv, _tmp) | |
1002 | ||
1003 | ###-------------------------------------------------------------------------- | |
eb8aa4ec | 1004 | ### Bernstein's elliptic curve crypto and related schemes. |
848ba392 | 1005 | |
8e6f45a3 MW |
1006 | X25519_BASE = MP(9).storel(32) |
1007 | X448_BASE = MP(5).storel(56) | |
eb8aa4ec | 1008 | |
5a8b43b3 | 1009 | Z128 = ByteString.zero(16) |
848ba392 | 1010 | |
925aa45b | 1011 | class _BasePub (object): |
f40e338b | 1012 | def __init__(me, pub, *args, **kw): |
1c7419c9 | 1013 | if not me._PUBSZ.check(len(pub)): raise ValueError('bad public key') |
925aa45b | 1014 | super(_BasePub, me).__init__(*args, **kw) |
848ba392 | 1015 | me.pub = pub |
bbd94558 | 1016 | def __repr__(me): return '%s(pub = %r)' % (_clsname(me), me.pub) |
925aa45b | 1017 | def _pp(me, pp): _pp_kv(pp, 'pub', me.pub) |
bbd94558 MW |
1018 | def _repr_pretty_(me, pp, cyclep): |
1019 | ind = _pp_bgroup_tyname(pp, me) | |
925aa45b MW |
1020 | if cyclep: pp.text('...') |
1021 | else: me._pp(pp) | |
bbd94558 | 1022 | pp.end_group(ind, ')') |
848ba392 | 1023 | |
925aa45b | 1024 | class _BasePriv (object): |
f40e338b | 1025 | def __init__(me, priv, pub = None, *args, **kw): |
1c7419c9 | 1026 | if not me._KEYSZ.check(len(priv)): raise ValueError('bad private key') |
925aa45b MW |
1027 | if pub is None: pub = me._pubkey(priv) |
1028 | super(_BasePriv, me).__init__(pub = pub, *args, **kw) | |
848ba392 | 1029 | me.priv = priv |
925aa45b MW |
1030 | @classmethod |
1031 | def generate(cls, rng = rand): | |
1032 | return cls(rng.block(cls._KEYSZ.default)) | |
1033 | def __repr__(me): | |
1034 | return '%s(priv = %d, pub = %r)' % \ | |
1035 | (_clsname(me), _repr_secret(me.priv), me.pub) | |
1036 | def _pp(me, pp): | |
1037 | _pp_kv(pp, 'priv', me.priv, secretp = True); pp.text(','); pp.breakable() | |
1038 | super(_BasePriv, me)._pp(pp) | |
1039 | ||
1040 | class _XDHPub (_BasePub): pass | |
1041 | ||
1042 | class _XDHPriv (_BasePriv): | |
1043 | def _pubkey(me, priv): return me._op(priv, me._BASE) | |
848ba392 | 1044 | def agree(me, you): return me._op(me.priv, you.pub) |
925aa45b MW |
1045 | def boxkey(me, recip): return me._hashkey(me.agree(recip)) |
1046 | def box(me, recip, n, m): return secret_box(me.boxkey(recip), n, m) | |
1047 | def unbox(me, recip, n, c): return secret_unbox(me.boxkey(recip), n, c) | |
848ba392 | 1048 | |
925aa45b MW |
1049 | class X25519Pub (_XDHPub): |
1050 | _PUBSZ = KeySZSet(X25519_PUBSZ) | |
848ba392 MW |
1051 | _BASE = X25519_BASE |
1052 | ||
925aa45b MW |
1053 | class X25519Priv (_XDHPriv, X25519Pub): |
1054 | _KEYSZ = KeySZSet(X25519_KEYSZ) | |
848ba392 MW |
1055 | def _op(me, k, X): return x25519(k, X) |
1056 | def _hashkey(me, z): return hsalsa20_prf(z, Z128) | |
1057 | ||
925aa45b MW |
1058 | class X448Pub (_XDHPub): |
1059 | _PUBSZ = KeySZSet(X448_PUBSZ) | |
eb8aa4ec MW |
1060 | _BASE = X448_BASE |
1061 | ||
925aa45b MW |
1062 | class X448Priv (_XDHPriv, X448Pub): |
1063 | _KEYSZ = KeySZSet(X448_KEYSZ) | |
eb8aa4ec | 1064 | def _op(me, k, X): return x448(k, X) |
f1b0cf0d | 1065 | def _hashkey(me, z): return Shake256().hash(z).done(salsa20.keysz.default) |
eb8aa4ec | 1066 | |
925aa45b | 1067 | class _EdDSAPub (_BasePub): |
058f0a00 MW |
1068 | def beginhash(me): return me._HASH() |
1069 | def endhash(me, h): return h.done() | |
925aa45b MW |
1070 | |
1071 | class _EdDSAPriv (_BasePriv, _EdDSAPub): | |
1072 | pass | |
1073 | ||
1074 | class Ed25519Pub (_EdDSAPub): | |
1075 | _PUBSZ = KeySZSet(ED25519_PUBSZ) | |
058f0a00 | 1076 | _HASH = sha512 |
5c4c0231 MW |
1077 | def verify(me, msg, sig, **kw): |
1078 | return ed25519_verify(me.pub, msg, sig, **kw) | |
dafb2da4 | 1079 | |
925aa45b MW |
1080 | class Ed25519Priv (_EdDSAPriv, Ed25519Pub): |
1081 | _KEYSZ = KeySZAny(ED25519_KEYSZ) | |
1082 | def _pubkey(me, priv): return ed25519_pubkey(priv) | |
5c4c0231 MW |
1083 | def sign(me, msg, **kw): |
1084 | return ed25519_sign(me.priv, msg, pub = me.pub, **kw) | |
dafb2da4 | 1085 | |
eee202c3 MW |
1086 | class Ed448Pub (_EdDSAPub): |
1087 | _PUBSZ = KeySZSet(ED448_PUBSZ) | |
1088 | _HASH = shake256 | |
1089 | def verify(me, msg, sig, **kw): | |
1090 | return ed448_verify(me.pub, msg, sig, **kw) | |
1091 | ||
1092 | class Ed448Priv (_EdDSAPriv, Ed448Pub): | |
1093 | _KEYSZ = KeySZAny(ED448_KEYSZ) | |
1094 | def _pubkey(me, priv): return ed448_pubkey(priv) | |
1095 | def sign(me, msg, **kw): | |
1096 | return ed448_sign(me.priv, msg, pub = me.pub, **kw) | |
1097 | ||
848ba392 | 1098 | ###-------------------------------------------------------------------------- |
a539ffb8 MW |
1099 | ### Built-in algorithm and group tables. |
1100 | ||
1101 | class _tmp: | |
ed8cc62d | 1102 | def __repr__(me): |
d6542364 | 1103 | return '{%s}' % ', '.join(['%r: %r' % kv for kv in _iteritems(me)]) |
96d7ed6c | 1104 | def _repr_pretty_(me, pp, cyclep): |
582568f1 MW |
1105 | ind = _pp_bgroup(pp, '{ ') |
1106 | if cyclep: pp.text('...') | |
d6542364 | 1107 | else: _pp_dict(pp, _iteritems(me)) |
582568f1 | 1108 | pp.end_group(ind, ' }') |
a539ffb8 | 1109 | _augment(_base._MiscTable, _tmp) |
ed8cc62d | 1110 | |
00401529 MW |
1111 | ###-------------------------------------------------------------------------- |
1112 | ### Prime number generation. | |
ed8cc62d MW |
1113 | |
1114 | class PrimeGenEventHandler (object): | |
1115 | def pg_begin(me, ev): | |
1116 | return me.pg_try(ev) | |
1117 | def pg_done(me, ev): | |
1118 | return PGEN_DONE | |
1119 | def pg_abort(me, ev): | |
1120 | return PGEN_TRY | |
1121 | def pg_fail(me, ev): | |
1122 | return PGEN_TRY | |
1123 | def pg_pass(me, ev): | |
1124 | return PGEN_TRY | |
d7ab1bab | 1125 | |
1126 | class SophieGermainStepJump (object): | |
1127 | def pg_begin(me, ev): | |
1128 | me.lf = PrimeFilter(ev.x) | |
1129 | me.hf = me.lf.muladd(2, 1) | |
1130 | return me.cont(ev) | |
1131 | def pg_try(me, ev): | |
1132 | me.step() | |
1133 | return me.cont(ev) | |
1134 | def cont(me, ev): | |
1135 | while me.lf.status == PGEN_FAIL or me.hf.status == PGEN_FAIL: | |
1136 | me.step() | |
1137 | if me.lf.status == PGEN_ABORT or me.hf.status == PGEN_ABORT: | |
1138 | return PGEN_ABORT | |
1139 | ev.x = me.lf.x | |
1140 | if me.lf.status == PGEN_DONE and me.hf.status == PGEN_DONE: | |
1141 | return PGEN_DONE | |
1142 | return PGEN_TRY | |
1143 | def pg_done(me, ev): | |
1144 | del me.lf | |
1145 | del me.hf | |
1146 | ||
1147 | class SophieGermainStepper (SophieGermainStepJump): | |
1148 | def __init__(me, step): | |
1149 | me.lstep = step; | |
1150 | me.hstep = 2 * step | |
1151 | def step(me): | |
1152 | me.lf.step(me.lstep) | |
1153 | me.hf.step(me.hstep) | |
1154 | ||
1155 | class SophieGermainJumper (SophieGermainStepJump): | |
1156 | def __init__(me, jump): | |
1157 | me.ljump = PrimeFilter(jump); | |
1158 | me.hjump = me.ljump.muladd(2, 0) | |
1159 | def step(me): | |
1160 | me.lf.jump(me.ljump) | |
1161 | me.hf.jump(me.hjump) | |
1162 | def pg_done(me, ev): | |
1163 | del me.ljump | |
1164 | del me.hjump | |
1165 | SophieGermainStepJump.pg_done(me, ev) | |
1166 | ||
1167 | class SophieGermainTester (object): | |
1168 | def __init__(me): | |
1169 | pass | |
1170 | def pg_begin(me, ev): | |
1171 | me.lr = RabinMiller(ev.x) | |
1172 | me.hr = RabinMiller(2 * ev.x + 1) | |
1173 | def pg_try(me, ev): | |
1174 | lst = me.lr.test(ev.rng.range(me.lr.x)) | |
1175 | if lst != PGEN_PASS and lst != PGEN_DONE: | |
1176 | return lst | |
1177 | rst = me.hr.test(ev.rng.range(me.hr.x)) | |
1178 | if rst != PGEN_PASS and rst != PGEN_DONE: | |
1179 | return rst | |
1180 | if lst == PGEN_DONE and rst == PGEN_DONE: | |
1181 | return PGEN_DONE | |
1182 | return PGEN_PASS | |
1183 | def pg_done(me, ev): | |
1184 | del me.lr | |
1185 | del me.hr | |
1186 | ||
d7ab1bab | 1187 | class PrimitiveStepper (PrimeGenEventHandler): |
1188 | def __init__(me): | |
1189 | pass | |
1190 | def pg_try(me, ev): | |
1191 | ev.x = me.i.next() | |
1192 | return PGEN_TRY | |
1193 | def pg_begin(me, ev): | |
1194 | me.i = iter(smallprimes) | |
1195 | return me.pg_try(ev) | |
1196 | ||
1197 | class PrimitiveTester (PrimeGenEventHandler): | |
1198 | def __init__(me, mod, hh = [], exp = None): | |
1199 | me.mod = MPMont(mod) | |
1200 | me.exp = exp | |
1201 | me.hh = hh | |
1202 | def pg_try(me, ev): | |
1203 | x = ev.x | |
1204 | if me.exp is not None: | |
1205 | x = me.mod.exp(x, me.exp) | |
1206 | if x == 1: return PGEN_FAIL | |
1207 | for h in me.hh: | |
1208 | if me.mod.exp(x, h) == 1: return PGEN_FAIL | |
1209 | ev.x = x | |
1210 | return PGEN_DONE | |
1211 | ||
1212 | class SimulStepper (PrimeGenEventHandler): | |
1213 | def __init__(me, mul = 2, add = 1, step = 2): | |
1214 | me.step = step | |
1215 | me.mul = mul | |
1216 | me.add = add | |
1217 | def _stepfn(me, step): | |
1218 | if step <= 0: | |
1c7419c9 | 1219 | raise ValueError('step must be positive') |
d7ab1bab | 1220 | if step <= MPW_MAX: |
1221 | return lambda f: f.step(step) | |
1222 | j = PrimeFilter(step) | |
1223 | return lambda f: f.jump(j) | |
1224 | def pg_begin(me, ev): | |
1225 | x = ev.x | |
1226 | me.lf = PrimeFilter(x) | |
1227 | me.hf = PrimeFilter(x * me.mul + me.add) | |
1228 | me.lstep = me._stepfn(me.step) | |
1229 | me.hstep = me._stepfn(me.step * me.mul) | |
1230 | SimulStepper._cont(me, ev) | |
1231 | def pg_try(me, ev): | |
1232 | me._step() | |
1233 | me._cont(ev) | |
1234 | def _step(me): | |
1235 | me.lstep(me.lf) | |
1236 | me.hstep(me.hf) | |
1237 | def _cont(me, ev): | |
1238 | while me.lf.status == PGEN_FAIL or me.hf.status == PGEN_FAIL: | |
1239 | me._step() | |
1240 | if me.lf.status == PGEN_ABORT or me.hf.status == PGEN_ABORT: | |
1241 | return PGEN_ABORT | |
1242 | ev.x = me.lf.x | |
1243 | if me.lf.status == PGEN_DONE and me.hf.status == PGEN_DONE: | |
1244 | return PGEN_DONE | |
1245 | return PGEN_TRY | |
1246 | def pg_done(me, ev): | |
1247 | del me.lf | |
1248 | del me.hf | |
1249 | del me.lstep | |
1250 | del me.hstep | |
1251 | ||
1252 | class SimulTester (PrimeGenEventHandler): | |
1253 | def __init__(me, mul = 2, add = 1): | |
1254 | me.mul = mul | |
1255 | me.add = add | |
1256 | def pg_begin(me, ev): | |
1257 | x = ev.x | |
1258 | me.lr = RabinMiller(x) | |
1259 | me.hr = RabinMiller(x * me.mul + me.add) | |
1260 | def pg_try(me, ev): | |
1261 | lst = me.lr.test(ev.rng.range(me.lr.x)) | |
1262 | if lst != PGEN_PASS and lst != PGEN_DONE: | |
1263 | return lst | |
1264 | rst = me.hr.test(ev.rng.range(me.hr.x)) | |
1265 | if rst != PGEN_PASS and rst != PGEN_DONE: | |
1266 | return rst | |
1267 | if lst == PGEN_DONE and rst == PGEN_DONE: | |
1268 | return PGEN_DONE | |
1269 | return PGEN_PASS | |
1270 | def pg_done(me, ev): | |
1271 | del me.lr | |
1272 | del me.hr | |
1273 | ||
1274 | def sgprime(start, step = 2, name = 'p', event = pgen_nullev, nsteps = 0): | |
1275 | start = MP(start) | |
1276 | return pgen(start, name, SimulStepper(step = step), SimulTester(), event, | |
00401529 | 1277 | nsteps, RabinMiller.iters(start.nbits)) |
d7ab1bab | 1278 | |
1279 | def findprimitive(mod, hh = [], exp = None, name = 'g', event = pgen_nullev): | |
1280 | return pgen(0, name, PrimitiveStepper(), PrimitiveTester(mod, hh, exp), | |
00401529 | 1281 | event, 0, 1) |
d7ab1bab | 1282 | |
1283 | def kcdsaprime(pbits, qbits, rng = rand, | |
00401529 | 1284 | event = pgen_nullev, name = 'p', nsteps = 0): |
d7ab1bab | 1285 | hbits = pbits - qbits |
1286 | h = pgen(rng.mp(hbits, 1), name + ' [h]', | |
00401529 MW |
1287 | PrimeGenStepper(2), PrimeGenTester(), |
1288 | event, nsteps, RabinMiller.iters(hbits)) | |
d7ab1bab | 1289 | q = pgen(rng.mp(qbits, 1), name, SimulStepper(2 * h, 1, 2), |
00401529 | 1290 | SimulTester(2 * h, 1), event, nsteps, RabinMiller.iters(qbits)) |
d7ab1bab | 1291 | p = 2 * q * h + 1 |
1292 | return p, q, h | |
1293 | ||
1294 | #----- That's all, folks ---------------------------------------------------- |