catacomb/__init__.py: Prepare rational classes for upcoming changes.
[catacomb-python] / catacomb / __init__.py
CommitLineData
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
26from __future__ import with_statement
27
d7ab1bab 28from binascii import hexlify as _hexify, unhexlify as _unhexify
6bd22b53 29from contextlib import contextmanager as _ctxmgr
8854bd74
MW
30try: import DLFCN as _dlfcn
31except ImportError: _dlfcn = None
a3ae4a9f 32import os as _os
6bd22b53 33from struct import pack as _pack
378ceeef
MW
34import sys as _sys
35import types as _types
36
37###--------------------------------------------------------------------------
38### Import the main C extension module.
39
a3ae4a9f
MW
40try:
41 _dlflags = _odlflags = _sys.getdlopenflags()
42except 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.
49if _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
58if _sys.version_info >= (3,): from . import _base
59else: import _base
46e6ad89 60
a3ae4a9f
MW
61if _odlflags >= 0:
62 _sys.setdlopenflags(_odlflags)
63
64del _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__])
74def 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")
79lostexchook = default_lostexchook
80
467c2619 81## Text/binary conversions.
f7623015
MW
82if _sys.version_info >= (3,):
83 def _bin(s): return s.encode('iso8859-1')
84else:
85 def _bin(s): return s
467c2619 86
d6542364 87## Iterating over dictionaries.
f7623015
MW
88if _sys.version_info >= (3,):
89 def _iteritems(dict): return dict.items()
90 def _itervalues(dict): return dict.values()
91else:
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
96try: long
97except NameError: _long = int
98else: _long = long
77535854 99
837fa485
MW
100## How to fix a name back into the right identifier. Alas, the rules are not
101## consistent.
102def _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 116def _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 132def _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.
144def _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 151PRINT_SECRETS = False
330e6a74 152def _clsname(me): return type(me).__name__
652e16ea
MW
153def _repr_secret(thing, secretp = True):
154 if not secretp or PRINT_SECRETS: return repr(thing)
155 else: return '#<SECRET>'
96d7ed6c 156def _pp_str(me, pp, cyclep): pp.text(cyclep and '...' or str(me))
652e16ea
MW
157def _pp_secret(pp, thing, secretp = True):
158 if not secretp or PRINT_SECRETS: pp.pretty(thing)
159 else: pp.text('#<SECRET>')
582568f1
MW
160def _pp_bgroup(pp, text):
161 ind = len(text)
162 pp.begin_group(ind, text)
163 return ind
164def _pp_bgroup_tyname(pp, obj, open = '('):
330e6a74 165 return _pp_bgroup(pp, _clsname(obj) + open)
652e16ea 166def _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, '')
170def _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)
176def _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
192if _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 207class _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 219ByteString.__hash__ = str.__hash__
d7ab1bab 220bytes = ByteString.fromhex
221
00401529 222###--------------------------------------------------------------------------
bebf03ab
MW
223### Symmetric encryption.
224
225class _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
246class _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
253class _tmp:
254 def check(me, h):
255 return ctstreq(h, me.done(len(h)))
6bd22b53 256_augment(Shake, _tmp)
668b5f54
MW
257
258KMAC128.keysz = KeySZAny(16); KMAC128.tagsz = 16
259KMAC256.keysz = KeySZAny(32); KMAC256.tagsz = 32
6bd22b53 260
bfb450cc 261###--------------------------------------------------------------------------
ce0340b6
MW
262### NaCl `secretbox'.
263
264def secret_box(k, n, m):
bebf03ab 265 y, t = salsa20_naclbox(k).encrypt(n, m)
bb5c23a4 266 return t + y
ce0340b6
MW
267
268def secret_unbox(k, n, c):
bebf03ab
MW
269 tsz = poly1305.tagsz
270 return salsa20_naclbox(k).decrypt(n, c[tsz:], c[0:tsz])
ce0340b6
MW
271
272###--------------------------------------------------------------------------
00401529 273### Multiprecision integers and binary polynomials.
ed8cc62d 274
83c77564
MW
275class BaseRat (object):
276 """Base class implementing fields of fractions over Euclidean domains."""
2ef393b5 277 def __new__(cls, a, b):
83c77564 278 a, b = cls.RING(a), cls.RING(b)
2ef393b5 279 q, r = divmod(a, b)
8d299320 280 if r == cls.ZERO: return q
2ef393b5 281 g = b.gcd(r)
83c77564 282 me = super(BaseRat, cls).__new__(cls)
2ef393b5
MW
283 me._n = a//g
284 me._d = b//g
285 return me
286 @property
287 def numer(me): return me._n
288 @property
289 def denom(me): return me._d
290 def __str__(me): return '%s/%s' % (me._n, me._d)
330e6a74 291 def __repr__(me): return '%s(%s, %s)' % (_clsname(me), me._n, me._d)
96d7ed6c 292 _repr_pretty_ = _pp_str
2ef393b5 293
8d299320
MW
294 def _split_rat(me, x):
295 if isinstance(x, me.__class__): return x._n, x._d
296 else: return x, me.ONE
2ef393b5 297 def __add__(me, you):
8d299320 298 n, d = me._split_rat(you)
83c77564 299 return type(me)(me._n*d + n*me._d, d*me._d)
2ef393b5
MW
300 __radd__ = __add__
301 def __sub__(me, you):
8d299320 302 n, d = me._split_rat(you)
83c77564 303 return type(me)(me._n*d - n*me._d, d*me._d)
2ef393b5 304 def __rsub__(me, you):
8d299320 305 n, d = me._split_rat(you)
83c77564 306 return type(me)(n*me._d - me._n*d, d*me._d)
2ef393b5 307 def __mul__(me, you):
8d299320 308 n, d = me._split_rat(you)
83c77564 309 return type(me)(me._n*n, me._d*d)
08041ebb 310 __rmul__ = __mul__
b47818ea 311 def __truediv__(me, you):
8d299320 312 n, d = me._split_rat(you)
83c77564 313 return type(me)(me._n*d, me._d*n)
b47818ea 314 def __rtruediv__(me, you):
8d299320 315 n, d = me._split_rat(you)
83c77564 316 return type(me)(me._d*n, me._n*d)
f7623015
MW
317 if _sys.version_info < (3,):
318 __div__ = __truediv__
319 __rdiv__ = __rtruediv__
54ee272d 320 def _order(me, you, op):
8d299320 321 n, d = me._split_rat(you)
54ee272d
MW
322 return op(me._n*d, n*me._d)
323 def __eq__(me, you): return me._order(you, lambda x, y: x == y)
324 def __ne__(me, you): return me._order(you, lambda x, y: x != y)
325 def __le__(me, you): return me._order(you, lambda x, y: x <= y)
326 def __lt__(me, you): return me._order(you, lambda x, y: x < y)
327 def __gt__(me, you): return me._order(you, lambda x, y: x > y)
328 def __ge__(me, you): return me._order(you, lambda x, y: x >= y)
2ef393b5 329
83c77564
MW
330class IntRat (BaseRat):
331 RING = MP
8d299320 332 ZERO, ONE = MP(0), MP(1)
77535854
MW
333 def __new__(cls, a, b):
334 if isinstance(a, float) or isinstance(b, float): return a/b
335 return super(IntRat, cls).__new__(cls, a, b)
336 def __float__(me): return float(me._n)/float(me._d)
83c77564
MW
337
338class GFRat (BaseRat):
339 RING = GF
8d299320 340 ZERO, ONE = GF(0), GF(1)
83c77564 341
d7ab1bab 342class _tmp:
343 def negp(x): return x < 0
344 def posp(x): return x > 0
345 def zerop(x): return x == 0
346 def oddp(x): return x.testbit(0)
347 def evenp(x): return not x.testbit(0)
348 def mont(x): return MPMont(x)
349 def barrett(x): return MPBarrett(x)
350 def reduce(x): return MPReduce(x)
77535854
MW
351 def __truediv__(me, you):
352 if isinstance(you, float): return _long(me)/you
353 else: return IntRat(me, you)
354 def __rtruediv__(me, you):
355 if isinstance(you, float): return you/_long(me)
356 else: return IntRat(you, me)
f7623015
MW
357 if _sys.version_info < (3,):
358 __div__ = __truediv__
359 __rdiv__ = __rtruediv__
96d7ed6c 360 _repr_pretty_ = _pp_str
d7ab1bab 361_augment(MP, _tmp)
362
d7ab1bab 363class _tmp:
fbc145f3 364 def zerop(x): return x == 0
ed8cc62d 365 def reduce(x): return GFReduce(x)
fbc145f3
MW
366 def trace(x, y): return x.reduce().trace(y)
367 def halftrace(x, y): return x.reduce().halftrace(y)
368 def modsqrt(x, y): return x.reduce().sqrt(y)
369 def quadsolve(x, y): return x.reduce().quadsolve(y)
b47818ea
MW
370 def __truediv__(me, you): return GFRat(me, you)
371 def __rtruediv__(me, you): return GFRat(you, me)
f7623015
MW
372 if _sys.version_info < (3,):
373 __div__ = __truediv__
374 __rdiv__ = __rtruediv__
96d7ed6c 375 _repr_pretty_ = _pp_str
d7ab1bab 376_augment(GF, _tmp)
377
378class _tmp:
ed8cc62d
MW
379 def product(*arg):
380 'product(ITERABLE) or product(I, ...) -> PRODUCT'
381 return MPMul(*arg).done()
382 product = staticmethod(product)
383_augment(MPMul, _tmp)
384
00401529
MW
385###--------------------------------------------------------------------------
386### Abstract fields.
ed8cc62d
MW
387
388class _tmp:
d7ab1bab 389 def fromstring(str): return _checkend(Field.parse(str))
390 fromstring = staticmethod(fromstring)
391_augment(Field, _tmp)
392
393class _tmp:
e38168e2 394 def __repr__(me): return '%s(%s)' % (_clsname(me), me.p)
6d481bc6 395 def __hash__(me): return 0x114401de ^ hash(me.p)
96d7ed6c 396 def _repr_pretty_(me, pp, cyclep):
582568f1
MW
397 ind = _pp_bgroup_tyname(pp, me)
398 if cyclep: pp.text('...')
399 else: pp.pretty(me.p)
400 pp.end_group(ind, ')')
d7ab1bab 401 def ec(me, a, b): return ECPrimeProjCurve(me, a, b)
402_augment(PrimeField, _tmp)
403
404class _tmp:
e38168e2 405 def __repr__(me): return '%s(%#x)' % (_clsname(me), me.p)
d7ab1bab 406 def ec(me, a, b): return ECBinProjCurve(me, a, b)
96d7ed6c 407 def _repr_pretty_(me, pp, cyclep):
582568f1
MW
408 ind = _pp_bgroup_tyname(pp, me)
409 if cyclep: pp.text('...')
410 else: pp.text('%#x' % me.p)
411 pp.end_group(ind, ')')
d7ab1bab 412_augment(BinField, _tmp)
413
414class _tmp:
6d481bc6
MW
415 def __hash__(me): return 0x23e4701c ^ hash(me.p)
416_augment(BinPolyField, _tmp)
417
418class _tmp:
419 def __hash__(me):
420 h = 0x9a7d6240
421 h ^= hash(me.p)
422 h ^= 2*hash(me.beta) & 0xffffffff
423 return h
424_augment(BinNormField, _tmp)
425
426class _tmp:
d7ab1bab 427 def __str__(me): return str(me.value)
428 def __repr__(me): return '%s(%s)' % (repr(me.field), repr(me.value))
96d7ed6c 429 _repr_pretty_ = _pp_str
d7ab1bab 430_augment(FE, _tmp)
431
00401529
MW
432###--------------------------------------------------------------------------
433### Elliptic curves.
d7ab1bab 434
435class _tmp:
436 def __repr__(me):
330e6a74 437 return '%s(%r, %s, %s)' % (_clsname(me), me.field, me.a, me.b)
96d7ed6c 438 def _repr_pretty_(me, pp, cyclep):
582568f1 439 ind = _pp_bgroup_tyname(pp, me)
96d7ed6c 440 if cyclep:
582568f1 441 pp.text('...')
96d7ed6c 442 else:
96d7ed6c
MW
443 pp.pretty(me.field); pp.text(','); pp.breakable()
444 pp.pretty(me.a); pp.text(','); pp.breakable()
445 pp.pretty(me.b)
582568f1 446 pp.end_group(ind, ')')
d7ab1bab 447 def frombuf(me, s):
448 return ecpt.frombuf(me, s)
449 def fromraw(me, s):
450 return ecpt.fromraw(me, s)
451 def pt(me, *args):
5f959e50 452 return me(*args)
d7ab1bab 453_augment(ECCurve, _tmp)
454
455class _tmp:
6d481bc6
MW
456 def __hash__(me):
457 h = 0x6751d341
458 h ^= hash(me.field)
459 h ^= 2*hash(me.a) ^ 0xffffffff
460 h ^= 5*hash(me.b) ^ 0xffffffff
461 return h
462_augment(ECPrimeCurve, _tmp)
463
464class _tmp:
465 def __hash__(me):
466 h = 0x2ac203c5
467 h ^= hash(me.field)
468 h ^= 2*hash(me.a) ^ 0xffffffff
469 h ^= 5*hash(me.b) ^ 0xffffffff
470 return h
471_augment(ECBinCurve, _tmp)
472
473class _tmp:
d7ab1bab 474 def __repr__(me):
330e6a74
MW
475 if not me: return '%s()' % _clsname(me)
476 return '%s(%s, %s)' % (_clsname(me), me.ix, me.iy)
d7ab1bab 477 def __str__(me):
478 if not me: return 'inf'
479 return '(%s, %s)' % (me.ix, me.iy)
96d7ed6c
MW
480 def _repr_pretty_(me, pp, cyclep):
481 if cyclep:
482 pp.text('...')
483 elif not me:
484 pp.text('inf')
485 else:
582568f1 486 ind = _pp_bgroup(pp, '(')
96d7ed6c
MW
487 pp.pretty(me.ix); pp.text(','); pp.breakable()
488 pp.pretty(me.iy)
582568f1 489 pp.end_group(ind, ')')
d7ab1bab 490_augment(ECPt, _tmp)
491
492class _tmp:
493 def __repr__(me):
330e6a74
MW
494 return '%s(curve = %r, G = %r, r = %s, h = %s)' % \
495 (_clsname(me), me.curve, me.G, me.r, me.h)
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_kv(pp, 'curve', me.curve); pp.text(','); pp.breakable()
502 _pp_kv(pp, 'G', me.G); pp.text(','); pp.breakable()
503 _pp_kv(pp, 'r', me.r); pp.text(','); pp.breakable()
504 _pp_kv(pp, 'h', me.h)
582568f1 505 pp.end_group(ind, ')')
6d481bc6
MW
506 def __hash__(me):
507 h = 0x9bedb8de
508 h ^= hash(me.curve)
509 h ^= 2*hash(me.G) & 0xffffffff
510 return h
d7ab1bab 511 def group(me):
512 return ECGroup(me)
513_augment(ECInfo, _tmp)
514
515class _tmp:
516 def __repr__(me):
517 if not me: return '%r()' % (me.curve)
518 return '%r(%s, %s)' % (me.curve, me.x, me.y)
519 def __str__(me):
520 if not me: return 'inf'
521 return '(%s, %s)' % (me.x, me.y)
7a7aa30e
MW
522 def _repr_pretty_(me, pp, cyclep):
523 if cyclep:
524 pp.text('...')
525 elif not me:
526 pp.text('inf')
527 else:
528 ind = _pp_bgroup(pp, '(')
529 pp.pretty(me.x); pp.text(','); pp.breakable()
530 pp.pretty(me.y)
531 pp.end_group(ind, ')')
d7ab1bab 532_augment(ECPtCurve, _tmp)
533
00401529
MW
534###--------------------------------------------------------------------------
535### Key sizes.
ed8cc62d 536
d7ab1bab 537class _tmp:
330e6a74 538 def __repr__(me): return '%s(%d)' % (_clsname(me), me.default)
d7ab1bab 539 def check(me, sz): return True
540 def best(me, sz): return sz
dfb915d3 541 def pad(me, sz): return sz
d7ab1bab 542_augment(KeySZAny, _tmp)
543
544class _tmp:
545 def __repr__(me):
330e6a74
MW
546 return '%s(%d, %d, %d, %d)' % \
547 (_clsname(me), me.default, me.min, me.max, me.mod)
96d7ed6c 548 def _repr_pretty_(me, pp, cyclep):
582568f1 549 ind = _pp_bgroup_tyname(pp, me)
96d7ed6c 550 if cyclep:
582568f1 551 pp.text('...')
96d7ed6c 552 else:
96d7ed6c
MW
553 pp.pretty(me.default); pp.text(','); pp.breakable()
554 pp.pretty(me.min); pp.text(','); pp.breakable()
555 pp.pretty(me.max); pp.text(','); pp.breakable()
556 pp.pretty(me.mod)
582568f1 557 pp.end_group(ind, ')')
dfb915d3 558 def check(me, sz): return me.min <= sz <= me.max and sz%me.mod == 0
d7ab1bab 559 def best(me, sz):
1c7419c9 560 if sz < me.min: raise ValueError('key too small')
a9410db7 561 elif me.max is not None and sz > me.max: return me.max
dfb915d3
MW
562 else: return sz - sz%me.mod
563 def pad(me, sz):
a9410db7 564 if me.max is not None and sz > me.max: raise ValueError('key too large')
dfb915d3 565 elif sz < me.min: return me.min
8fc76cc0 566 else: sz += me.mod - 1; return sz - sz%me.mod
d7ab1bab 567_augment(KeySZRange, _tmp)
568
569class _tmp:
330e6a74 570 def __repr__(me): return '%s(%d, %s)' % (_clsname(me), me.default, me.set)
96d7ed6c 571 def _repr_pretty_(me, pp, cyclep):
582568f1 572 ind = _pp_bgroup_tyname(pp, me)
96d7ed6c 573 if cyclep:
582568f1 574 pp.text('...')
96d7ed6c 575 else:
96d7ed6c 576 pp.pretty(me.default); pp.text(','); pp.breakable()
582568f1 577 ind1 = _pp_bgroup(pp, '{')
96d7ed6c 578 _pp_commas(pp, pp.pretty, me.set)
582568f1
MW
579 pp.end_group(ind1, '}')
580 pp.end_group(ind, ')')
d7ab1bab 581 def check(me, sz): return sz in me.set
582 def best(me, sz):
583 found = -1
584 for i in me.set:
585 if found < i <= sz: found = i
1c7419c9 586 if found < 0: raise ValueError('key too small')
d7ab1bab 587 return found
dfb915d3
MW
588 def pad(me, sz):
589 found = -1
590 for i in me.set:
591 if sz <= i and (found == -1 or i < found): found = i
1c7419c9 592 if found < 0: raise ValueError('key too large')
dfb915d3 593 return found
d7ab1bab 594_augment(KeySZSet, _tmp)
595
00401529 596###--------------------------------------------------------------------------
96d7ed6c
MW
597### Key data objects.
598
599class _tmp:
618cbc92
MW
600 def merge(me, file, report = None):
601 """KF.merge(FILE, [report = <built-in-reporter>])"""
602 name = file.name
603 lno = 1
604 for line in file:
605 me.mergeline(name, lno, line, report)
606 lno += 1
607 return me
330e6a74 608 def __repr__(me): return '%s(%r)' % (_clsname(me), me.name)
96d7ed6c
MW
609_augment(KeyFile, _tmp)
610
611class _tmp:
618cbc92
MW
612 def extract(me, file, filter = ''):
613 """KEY.extract(FILE, [filter = <any>])"""
614 line = me.extractline(filter)
615 file.write(line)
616 return me
330e6a74 617 def __repr__(me): return '%s(%r)' % (_clsname(me), me.fulltag)
96d7ed6c
MW
618_augment(Key, _tmp)
619
620class _tmp:
621 def __repr__(me):
330e6a74 622 return '%s({%s})' % (_clsname(me),
d6542364 623 ', '.join(['%r: %r' % kv for kv in _iteritems(me)()]))
96d7ed6c 624 def _repr_pretty_(me, pp, cyclep):
582568f1 625 ind = _pp_bgroup_tyname(pp, me)
96d7ed6c 626 if cyclep: pp.text('...')
d6542364 627 else: _pp_dict(pp, _iteritems(me))
582568f1 628 pp.end_group(ind, ')')
96d7ed6c
MW
629_augment(KeyAttributes, _tmp)
630
631class _tmp:
849e8a20 632 def __repr__(me):
652e16ea
MW
633 return '%s(%s, %r)' % (_clsname(me),
634 _repr_secret(me._guts(),
635 not (me.flags & KF_NONSECRET)),
636 me.writeflags(me.flags))
96d7ed6c 637 def _repr_pretty_(me, pp, cyclep):
582568f1 638 ind = _pp_bgroup_tyname(pp, me)
96d7ed6c 639 if cyclep:
582568f1 640 pp.text('...')
96d7ed6c 641 else:
652e16ea
MW
642 _pp_secret(pp, me._guts(), not (me.flags & KF_NONSECRET))
643 pp.text(','); pp.breakable()
96d7ed6c 644 pp.pretty(me.writeflags(me.flags))
582568f1 645 pp.end_group(ind, ')')
c567f805
MW
646 def __hash__(me): return me._HASHBASE ^ hash(me._guts())
647 def __eq__(me, kd):
648 return type(me) == type(kd) and \
649 me._guts() == kd._guts() and \
650 me.flags == kd.flags
651 def __ne__(me, kd):
652 return not me == kd
849e8a20
MW
653_augment(KeyData, _tmp)
654
655class _tmp:
656 def _guts(me): return me.bin
c567f805
MW
657 def __eq__(me, kd):
658 return isinstance(kd, KeyDataBinary) and me.bin == kd.bin
96d7ed6c 659_augment(KeyDataBinary, _tmp)
c567f805 660KeyDataBinary._HASHBASE = 0x961755c3
96d7ed6c
MW
661
662class _tmp:
849e8a20 663 def _guts(me): return me.ct
96d7ed6c 664_augment(KeyDataEncrypted, _tmp)
c567f805 665KeyDataEncrypted._HASHBASE = 0xffe000d4
96d7ed6c
MW
666
667class _tmp:
849e8a20 668 def _guts(me): return me.mp
96d7ed6c 669_augment(KeyDataMP, _tmp)
c567f805 670KeyDataMP._HASHBASE = 0x1cb64d69
96d7ed6c
MW
671
672class _tmp:
849e8a20 673 def _guts(me): return me.str
96d7ed6c 674_augment(KeyDataString, _tmp)
c567f805 675KeyDataString._HASHBASE = 0x349c33ea
96d7ed6c
MW
676
677class _tmp:
849e8a20 678 def _guts(me): return me.ecpt
96d7ed6c 679_augment(KeyDataECPt, _tmp)
c567f805 680KeyDataECPt._HASHBASE = 0x2509718b
96d7ed6c
MW
681
682class _tmp:
683 def __repr__(me):
330e6a74 684 return '%s({%s})' % (_clsname(me),
d6542364 685 ', '.join(['%r: %r' % kv for kv in _iteritems(me)]))
96d7ed6c 686 def _repr_pretty_(me, pp, cyclep):
582568f1 687 ind = _pp_bgroup_tyname(pp, me, '({ ')
96d7ed6c 688 if cyclep: pp.text('...')
d6542364 689 else: _pp_dict(pp, _iteritems(me))
582568f1 690 pp.end_group(ind, ' })')
c567f805
MW
691 def __hash__(me):
692 h = me._HASHBASE
693 for k, v in _iteritems(me):
694 h = ((h << 1) ^ 3*hash(k) ^ 5*hash(v))&0xffffffff
695 return h
696 def __eq__(me, kd):
697 if type(me) != type(kd) or me.flags != kd.flags or len(me) != len(kd):
698 return False
699 for k, v in _iteritems(me):
700 try: vv = kd[k]
701 except KeyError: return False
702 if v != vv: return False
703 return True
96d7ed6c 704_augment(KeyDataStructured, _tmp)
c567f805 705KeyDataStructured._HASHBASE = 0x85851b21
96d7ed6c
MW
706
707###--------------------------------------------------------------------------
00401529 708### Abstract groups.
ed8cc62d 709
d7ab1bab 710class _tmp:
711 def __repr__(me):
330e6a74 712 return '%s(p = %s, r = %s, g = %s)' % (_clsname(me), me.p, me.r, me.g)
96d7ed6c 713 def _repr_pretty_(me, pp, cyclep):
582568f1 714 ind = _pp_bgroup_tyname(pp, me)
96d7ed6c 715 if cyclep:
582568f1 716 pp.text('...')
96d7ed6c 717 else:
96d7ed6c
MW
718 _pp_kv(pp, 'p', me.p); pp.text(','); pp.breakable()
719 _pp_kv(pp, 'r', me.r); pp.text(','); pp.breakable()
720 _pp_kv(pp, 'g', me.g)
582568f1 721 pp.end_group(ind, ')')
d7ab1bab 722_augment(FGInfo, _tmp)
723
724class _tmp:
725 def group(me): return PrimeGroup(me)
726_augment(DHInfo, _tmp)
727
728class _tmp:
729 def group(me): return BinGroup(me)
730_augment(BinDHInfo, _tmp)
731
732class _tmp:
733 def __repr__(me):
330e6a74 734 return '%s(%r)' % (_clsname(me), me.info)
99d932fe
MW
735 def _repr_pretty_(me, pp, cyclep):
736 ind = _pp_bgroup_tyname(pp, me)
737 if cyclep: pp.text('...')
738 else: pp.pretty(me.info)
739 pp.end_group(ind, ')')
d7ab1bab 740_augment(Group, _tmp)
741
742class _tmp:
6d481bc6
MW
743 def __hash__(me):
744 info = me.info
745 h = 0xbce3cfe6
746 h ^= hash(info.p)
747 h ^= 2*hash(info.r) & 0xffffffff
748 h ^= 5*hash(info.g) & 0xffffffff
749 return h
d7012c2b 750 def _get_geval(me, x): return MP(x)
6d481bc6
MW
751_augment(PrimeGroup, _tmp)
752
753class _tmp:
754 def __hash__(me):
755 info = me.info
756 h = 0x80695949
757 h ^= hash(info.p)
758 h ^= 2*hash(info.r) & 0xffffffff
759 h ^= 5*hash(info.g) & 0xffffffff
760 return h
d7012c2b 761 def _get_geval(me, x): return GF(x)
6d481bc6
MW
762_augment(BinGroup, _tmp)
763
764class _tmp:
765 def __hash__(me): return 0x0ec23dab ^ hash(me.info)
d7012c2b 766 def _get_geval(me, x): return x.toec()
6d481bc6
MW
767_augment(ECGroup, _tmp)
768
769class _tmp:
d7ab1bab 770 def __repr__(me):
771 return '%r(%r)' % (me.group, str(me))
d7012c2b
MW
772 def _repr_pretty_(me, pp, cyclep):
773 pp.pretty(type(me)._get_geval(me))
d7ab1bab 774_augment(GE, _tmp)
775
00401529
MW
776###--------------------------------------------------------------------------
777### RSA encoding techniques.
ed8cc62d
MW
778
779class PKCS1Crypt (object):
467c2619 780 def __init__(me, ep = _bin(''), rng = rand):
d7ab1bab 781 me.ep = ep
782 me.rng = rng
783 def encode(me, msg, nbits):
784 return _base._p1crypt_encode(msg, nbits, me.ep, me.rng)
785 def decode(me, ct, nbits):
786 return _base._p1crypt_decode(ct, nbits, me.ep, me.rng)
787
ed8cc62d 788class PKCS1Sig (object):
467c2619 789 def __init__(me, ep = _bin(''), rng = rand):
d7ab1bab 790 me.ep = ep
791 me.rng = rng
792 def encode(me, msg, nbits):
793 return _base._p1sig_encode(msg, nbits, me.ep, me.rng)
794 def decode(me, msg, sig, nbits):
795 return _base._p1sig_decode(msg, sig, nbits, me.ep, me.rng)
796
ed8cc62d 797class OAEP (object):
467c2619 798 def __init__(me, mgf = sha_mgf, hash = sha, ep = _bin(''), rng = rand):
d7ab1bab 799 me.mgf = mgf
800 me.hash = hash
801 me.ep = ep
802 me.rng = rng
803 def encode(me, msg, nbits):
804 return _base._oaep_encode(msg, nbits, me.mgf, me.hash, me.ep, me.rng)
805 def decode(me, ct, nbits):
806 return _base._oaep_decode(ct, nbits, me.mgf, me.hash, me.ep, me.rng)
807
ed8cc62d 808class PSS (object):
d7ab1bab 809 def __init__(me, mgf = sha_mgf, hash = sha, saltsz = None, rng = rand):
810 me.mgf = mgf
811 me.hash = hash
812 if saltsz is None:
813 saltsz = hash.hashsz
814 me.saltsz = saltsz
815 me.rng = rng
816 def encode(me, msg, nbits):
817 return _base._pss_encode(msg, nbits, me.mgf, me.hash, me.saltsz, me.rng)
818 def decode(me, msg, sig, nbits):
819 return _base._pss_decode(msg, sig, nbits,
00401529 820 me.mgf, me.hash, me.saltsz, me.rng)
d7ab1bab 821
822class _tmp:
823 def encrypt(me, msg, enc):
824 return me.pubop(enc.encode(msg, me.n.nbits))
825 def verify(me, msg, sig, enc):
826 if msg is None: return enc.decode(msg, me.pubop(sig), me.n.nbits)
827 try:
828 x = enc.decode(msg, me.pubop(sig), me.n.nbits)
829 return x is None or x == msg
830 except ValueError:
b2687a0a 831 return False
bbd94558
MW
832 def __repr__(me):
833 return '%s(n = %r, e = %r)' % (_clsname(me), me.n, me.e)
834 def _repr_pretty_(me, pp, cyclep):
835 ind = _pp_bgroup_tyname(pp, me)
836 if cyclep:
837 pp.text('...')
838 else:
839 _pp_kv(pp, 'n', me.n); pp.text(','); pp.breakable()
840 _pp_kv(pp, 'e', me.e)
841 pp.end_group(ind, ')')
d7ab1bab 842_augment(RSAPub, _tmp)
843
844class _tmp:
845 def decrypt(me, ct, enc): return enc.decode(me.privop(ct), me.n.nbits)
846 def sign(me, msg, enc): return me.privop(enc.encode(msg, me.n.nbits))
bbd94558
MW
847 def __repr__(me):
848 return '%s(n = %r, e = %r, d = %s, ' \
849 'p = %s, q = %s, dp = %s, dq = %s, q_inv = %s)' % \
850 (_clsname(me), me.n, me.e,
851 _repr_secret(me.d), _repr_secret(me.p), _repr_secret(me.q),
852 _repr_secret(me.dp), _repr_secret(me.dq), _repr_secret(me.q_inv))
853 def _repr_pretty_(me, pp, cyclep):
854 ind = _pp_bgroup_tyname(pp, me)
855 if cyclep:
856 pp.text('...')
857 else:
858 _pp_kv(pp, 'n', me.n); pp.text(','); pp.breakable()
859 _pp_kv(pp, 'e', me.e); pp.text(','); pp.breakable()
860 _pp_kv(pp, 'd', me.d, secretp = True); pp.text(','); pp.breakable()
861 _pp_kv(pp, 'p', me.p, secretp = True); pp.text(','); pp.breakable()
862 _pp_kv(pp, 'q', me.q, secretp = True); pp.text(','); pp.breakable()
863 _pp_kv(pp, 'dp', me.dp, secretp = True); pp.text(','); pp.breakable()
864 _pp_kv(pp, 'dq', me.dq, secretp = True); pp.text(','); pp.breakable()
865 _pp_kv(pp, 'q_inv', me.q_inv, secretp = True)
866 pp.end_group(ind, ')')
d7ab1bab 867_augment(RSAPriv, _tmp)
868
00401529 869###--------------------------------------------------------------------------
bbd94558
MW
870### DSA and related schemes.
871
872class _tmp:
1b3b79da
MW
873 def __repr__(me): return '%s(G = %r, p = %r, hash = %r)' % \
874 (_clsname(me), me.G, me.p, me.hash)
bbd94558
MW
875 def _repr_pretty_(me, pp, cyclep):
876 ind = _pp_bgroup_tyname(pp, me)
877 if cyclep:
878 pp.text('...')
879 else:
880 _pp_kv(pp, 'G', me.G); pp.text(','); pp.breakable()
1b3b79da
MW
881 _pp_kv(pp, 'p', me.p); pp.text(','); pp.breakable()
882 _pp_kv(pp, 'hash', me.hash)
bbd94558
MW
883 pp.end_group(ind, ')')
884_augment(DSAPub, _tmp)
885_augment(KCDSAPub, _tmp)
886
887class _tmp:
1b3b79da
MW
888 def __repr__(me): return '%s(G = %r, u = %s, p = %r, hash = %r)' % \
889 (_clsname(me), me.G, _repr_secret(me.u), me.p, me.hash)
bbd94558
MW
890 def _repr_pretty_(me, pp, cyclep):
891 ind = _pp_bgroup_tyname(pp, me)
892 if cyclep:
893 pp.text('...')
894 else:
895 _pp_kv(pp, 'G', me.G); pp.text(','); pp.breakable()
896 _pp_kv(pp, 'u', me.u, True); pp.text(','); pp.breakable()
1b3b79da
MW
897 _pp_kv(pp, 'p', me.p); pp.text(','); pp.breakable()
898 _pp_kv(pp, 'hash', me.hash)
bbd94558
MW
899 pp.end_group(ind, ')')
900_augment(DSAPriv, _tmp)
901_augment(KCDSAPriv, _tmp)
902
903###--------------------------------------------------------------------------
eb8aa4ec 904### Bernstein's elliptic curve crypto and related schemes.
848ba392 905
8e6f45a3
MW
906X25519_BASE = MP(9).storel(32)
907X448_BASE = MP(5).storel(56)
eb8aa4ec 908
5a8b43b3 909Z128 = ByteString.zero(16)
848ba392 910
925aa45b 911class _BasePub (object):
f40e338b 912 def __init__(me, pub, *args, **kw):
1c7419c9 913 if not me._PUBSZ.check(len(pub)): raise ValueError('bad public key')
925aa45b 914 super(_BasePub, me).__init__(*args, **kw)
848ba392 915 me.pub = pub
bbd94558 916 def __repr__(me): return '%s(pub = %r)' % (_clsname(me), me.pub)
925aa45b 917 def _pp(me, pp): _pp_kv(pp, 'pub', me.pub)
bbd94558
MW
918 def _repr_pretty_(me, pp, cyclep):
919 ind = _pp_bgroup_tyname(pp, me)
925aa45b
MW
920 if cyclep: pp.text('...')
921 else: me._pp(pp)
bbd94558 922 pp.end_group(ind, ')')
848ba392 923
925aa45b 924class _BasePriv (object):
f40e338b 925 def __init__(me, priv, pub = None, *args, **kw):
1c7419c9 926 if not me._KEYSZ.check(len(priv)): raise ValueError('bad private key')
925aa45b
MW
927 if pub is None: pub = me._pubkey(priv)
928 super(_BasePriv, me).__init__(pub = pub, *args, **kw)
848ba392 929 me.priv = priv
925aa45b
MW
930 @classmethod
931 def generate(cls, rng = rand):
932 return cls(rng.block(cls._KEYSZ.default))
933 def __repr__(me):
934 return '%s(priv = %d, pub = %r)' % \
935 (_clsname(me), _repr_secret(me.priv), me.pub)
936 def _pp(me, pp):
937 _pp_kv(pp, 'priv', me.priv, secretp = True); pp.text(','); pp.breakable()
938 super(_BasePriv, me)._pp(pp)
939
940class _XDHPub (_BasePub): pass
941
942class _XDHPriv (_BasePriv):
943 def _pubkey(me, priv): return me._op(priv, me._BASE)
848ba392 944 def agree(me, you): return me._op(me.priv, you.pub)
925aa45b
MW
945 def boxkey(me, recip): return me._hashkey(me.agree(recip))
946 def box(me, recip, n, m): return secret_box(me.boxkey(recip), n, m)
947 def unbox(me, recip, n, c): return secret_unbox(me.boxkey(recip), n, c)
848ba392 948
925aa45b
MW
949class X25519Pub (_XDHPub):
950 _PUBSZ = KeySZSet(X25519_PUBSZ)
848ba392
MW
951 _BASE = X25519_BASE
952
925aa45b
MW
953class X25519Priv (_XDHPriv, X25519Pub):
954 _KEYSZ = KeySZSet(X25519_KEYSZ)
848ba392
MW
955 def _op(me, k, X): return x25519(k, X)
956 def _hashkey(me, z): return hsalsa20_prf(z, Z128)
957
925aa45b
MW
958class X448Pub (_XDHPub):
959 _PUBSZ = KeySZSet(X448_PUBSZ)
eb8aa4ec
MW
960 _BASE = X448_BASE
961
925aa45b
MW
962class X448Priv (_XDHPriv, X448Pub):
963 _KEYSZ = KeySZSet(X448_KEYSZ)
eb8aa4ec 964 def _op(me, k, X): return x448(k, X)
f1b0cf0d 965 def _hashkey(me, z): return Shake256().hash(z).done(salsa20.keysz.default)
eb8aa4ec 966
925aa45b 967class _EdDSAPub (_BasePub):
058f0a00
MW
968 def beginhash(me): return me._HASH()
969 def endhash(me, h): return h.done()
925aa45b
MW
970
971class _EdDSAPriv (_BasePriv, _EdDSAPub):
972 pass
973
974class Ed25519Pub (_EdDSAPub):
975 _PUBSZ = KeySZSet(ED25519_PUBSZ)
058f0a00 976 _HASH = sha512
5c4c0231
MW
977 def verify(me, msg, sig, **kw):
978 return ed25519_verify(me.pub, msg, sig, **kw)
dafb2da4 979
925aa45b
MW
980class Ed25519Priv (_EdDSAPriv, Ed25519Pub):
981 _KEYSZ = KeySZAny(ED25519_KEYSZ)
982 def _pubkey(me, priv): return ed25519_pubkey(priv)
5c4c0231
MW
983 def sign(me, msg, **kw):
984 return ed25519_sign(me.priv, msg, pub = me.pub, **kw)
dafb2da4 985
eee202c3
MW
986class Ed448Pub (_EdDSAPub):
987 _PUBSZ = KeySZSet(ED448_PUBSZ)
988 _HASH = shake256
989 def verify(me, msg, sig, **kw):
990 return ed448_verify(me.pub, msg, sig, **kw)
991
992class Ed448Priv (_EdDSAPriv, Ed448Pub):
993 _KEYSZ = KeySZAny(ED448_KEYSZ)
994 def _pubkey(me, priv): return ed448_pubkey(priv)
995 def sign(me, msg, **kw):
996 return ed448_sign(me.priv, msg, pub = me.pub, **kw)
997
848ba392 998###--------------------------------------------------------------------------
a539ffb8
MW
999### Built-in algorithm and group tables.
1000
1001class _tmp:
ed8cc62d 1002 def __repr__(me):
d6542364 1003 return '{%s}' % ', '.join(['%r: %r' % kv for kv in _iteritems(me)])
96d7ed6c 1004 def _repr_pretty_(me, pp, cyclep):
582568f1
MW
1005 ind = _pp_bgroup(pp, '{ ')
1006 if cyclep: pp.text('...')
d6542364 1007 else: _pp_dict(pp, _iteritems(me))
582568f1 1008 pp.end_group(ind, ' }')
a539ffb8 1009_augment(_base._MiscTable, _tmp)
ed8cc62d 1010
00401529
MW
1011###--------------------------------------------------------------------------
1012### Prime number generation.
ed8cc62d
MW
1013
1014class PrimeGenEventHandler (object):
1015 def pg_begin(me, ev):
1016 return me.pg_try(ev)
1017 def pg_done(me, ev):
1018 return PGEN_DONE
1019 def pg_abort(me, ev):
1020 return PGEN_TRY
1021 def pg_fail(me, ev):
1022 return PGEN_TRY
1023 def pg_pass(me, ev):
1024 return PGEN_TRY
d7ab1bab 1025
1026class SophieGermainStepJump (object):
1027 def pg_begin(me, ev):
1028 me.lf = PrimeFilter(ev.x)
1029 me.hf = me.lf.muladd(2, 1)
1030 return me.cont(ev)
1031 def pg_try(me, ev):
1032 me.step()
1033 return me.cont(ev)
1034 def cont(me, ev):
1035 while me.lf.status == PGEN_FAIL or me.hf.status == PGEN_FAIL:
1036 me.step()
1037 if me.lf.status == PGEN_ABORT or me.hf.status == PGEN_ABORT:
1038 return PGEN_ABORT
1039 ev.x = me.lf.x
1040 if me.lf.status == PGEN_DONE and me.hf.status == PGEN_DONE:
1041 return PGEN_DONE
1042 return PGEN_TRY
1043 def pg_done(me, ev):
1044 del me.lf
1045 del me.hf
1046
1047class SophieGermainStepper (SophieGermainStepJump):
1048 def __init__(me, step):
1049 me.lstep = step;
1050 me.hstep = 2 * step
1051 def step(me):
1052 me.lf.step(me.lstep)
1053 me.hf.step(me.hstep)
1054
1055class SophieGermainJumper (SophieGermainStepJump):
1056 def __init__(me, jump):
1057 me.ljump = PrimeFilter(jump);
1058 me.hjump = me.ljump.muladd(2, 0)
1059 def step(me):
1060 me.lf.jump(me.ljump)
1061 me.hf.jump(me.hjump)
1062 def pg_done(me, ev):
1063 del me.ljump
1064 del me.hjump
1065 SophieGermainStepJump.pg_done(me, ev)
1066
1067class SophieGermainTester (object):
1068 def __init__(me):
1069 pass
1070 def pg_begin(me, ev):
1071 me.lr = RabinMiller(ev.x)
1072 me.hr = RabinMiller(2 * ev.x + 1)
1073 def pg_try(me, ev):
1074 lst = me.lr.test(ev.rng.range(me.lr.x))
1075 if lst != PGEN_PASS and lst != PGEN_DONE:
1076 return lst
1077 rst = me.hr.test(ev.rng.range(me.hr.x))
1078 if rst != PGEN_PASS and rst != PGEN_DONE:
1079 return rst
1080 if lst == PGEN_DONE and rst == PGEN_DONE:
1081 return PGEN_DONE
1082 return PGEN_PASS
1083 def pg_done(me, ev):
1084 del me.lr
1085 del me.hr
1086
d7ab1bab 1087class PrimitiveStepper (PrimeGenEventHandler):
1088 def __init__(me):
1089 pass
1090 def pg_try(me, ev):
1091 ev.x = me.i.next()
1092 return PGEN_TRY
1093 def pg_begin(me, ev):
1094 me.i = iter(smallprimes)
1095 return me.pg_try(ev)
1096
1097class PrimitiveTester (PrimeGenEventHandler):
1098 def __init__(me, mod, hh = [], exp = None):
1099 me.mod = MPMont(mod)
1100 me.exp = exp
1101 me.hh = hh
1102 def pg_try(me, ev):
1103 x = ev.x
1104 if me.exp is not None:
1105 x = me.mod.exp(x, me.exp)
1106 if x == 1: return PGEN_FAIL
1107 for h in me.hh:
1108 if me.mod.exp(x, h) == 1: return PGEN_FAIL
1109 ev.x = x
1110 return PGEN_DONE
1111
1112class SimulStepper (PrimeGenEventHandler):
1113 def __init__(me, mul = 2, add = 1, step = 2):
1114 me.step = step
1115 me.mul = mul
1116 me.add = add
1117 def _stepfn(me, step):
1118 if step <= 0:
1c7419c9 1119 raise ValueError('step must be positive')
d7ab1bab 1120 if step <= MPW_MAX:
1121 return lambda f: f.step(step)
1122 j = PrimeFilter(step)
1123 return lambda f: f.jump(j)
1124 def pg_begin(me, ev):
1125 x = ev.x
1126 me.lf = PrimeFilter(x)
1127 me.hf = PrimeFilter(x * me.mul + me.add)
1128 me.lstep = me._stepfn(me.step)
1129 me.hstep = me._stepfn(me.step * me.mul)
1130 SimulStepper._cont(me, ev)
1131 def pg_try(me, ev):
1132 me._step()
1133 me._cont(ev)
1134 def _step(me):
1135 me.lstep(me.lf)
1136 me.hstep(me.hf)
1137 def _cont(me, ev):
1138 while me.lf.status == PGEN_FAIL or me.hf.status == PGEN_FAIL:
1139 me._step()
1140 if me.lf.status == PGEN_ABORT or me.hf.status == PGEN_ABORT:
1141 return PGEN_ABORT
1142 ev.x = me.lf.x
1143 if me.lf.status == PGEN_DONE and me.hf.status == PGEN_DONE:
1144 return PGEN_DONE
1145 return PGEN_TRY
1146 def pg_done(me, ev):
1147 del me.lf
1148 del me.hf
1149 del me.lstep
1150 del me.hstep
1151
1152class SimulTester (PrimeGenEventHandler):
1153 def __init__(me, mul = 2, add = 1):
1154 me.mul = mul
1155 me.add = add
1156 def pg_begin(me, ev):
1157 x = ev.x
1158 me.lr = RabinMiller(x)
1159 me.hr = RabinMiller(x * me.mul + me.add)
1160 def pg_try(me, ev):
1161 lst = me.lr.test(ev.rng.range(me.lr.x))
1162 if lst != PGEN_PASS and lst != PGEN_DONE:
1163 return lst
1164 rst = me.hr.test(ev.rng.range(me.hr.x))
1165 if rst != PGEN_PASS and rst != PGEN_DONE:
1166 return rst
1167 if lst == PGEN_DONE and rst == PGEN_DONE:
1168 return PGEN_DONE
1169 return PGEN_PASS
1170 def pg_done(me, ev):
1171 del me.lr
1172 del me.hr
1173
1174def sgprime(start, step = 2, name = 'p', event = pgen_nullev, nsteps = 0):
1175 start = MP(start)
1176 return pgen(start, name, SimulStepper(step = step), SimulTester(), event,
00401529 1177 nsteps, RabinMiller.iters(start.nbits))
d7ab1bab 1178
1179def findprimitive(mod, hh = [], exp = None, name = 'g', event = pgen_nullev):
1180 return pgen(0, name, PrimitiveStepper(), PrimitiveTester(mod, hh, exp),
00401529 1181 event, 0, 1)
d7ab1bab 1182
1183def kcdsaprime(pbits, qbits, rng = rand,
00401529 1184 event = pgen_nullev, name = 'p', nsteps = 0):
d7ab1bab 1185 hbits = pbits - qbits
1186 h = pgen(rng.mp(hbits, 1), name + ' [h]',
00401529
MW
1187 PrimeGenStepper(2), PrimeGenTester(),
1188 event, nsteps, RabinMiller.iters(hbits))
d7ab1bab 1189 q = pgen(rng.mp(qbits, 1), name, SimulStepper(2 * h, 1, 2),
00401529 1190 SimulTester(2 * h, 1), event, nsteps, RabinMiller.iters(qbits))
d7ab1bab 1191 p = 2 * q * h + 1
1192 return p, q, h
1193
1194#----- That's all, folks ----------------------------------------------------