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