@@@ py_buffer/freebin wip
[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):
ad52b46f 278 a, b = cls.RING._implicit(a), cls.RING._implicit(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, ')')
96f89e4d
MW
447 def fromstring(str): return _checkend(ECCurve.parse(str))
448 fromstring = staticmethod(fromstring)
d7ab1bab 449 def frombuf(me, s):
450 return ecpt.frombuf(me, s)
451 def fromraw(me, s):
452 return ecpt.fromraw(me, s)
453 def pt(me, *args):
5f959e50 454 return me(*args)
d7ab1bab 455_augment(ECCurve, _tmp)
456
457class _tmp:
6d481bc6
MW
458 def __hash__(me):
459 h = 0x6751d341
460 h ^= hash(me.field)
461 h ^= 2*hash(me.a) ^ 0xffffffff
462 h ^= 5*hash(me.b) ^ 0xffffffff
463 return h
464_augment(ECPrimeCurve, _tmp)
465
466class _tmp:
467 def __hash__(me):
468 h = 0x2ac203c5
469 h ^= hash(me.field)
470 h ^= 2*hash(me.a) ^ 0xffffffff
471 h ^= 5*hash(me.b) ^ 0xffffffff
472 return h
473_augment(ECBinCurve, _tmp)
474
475class _tmp:
d7ab1bab 476 def __repr__(me):
330e6a74
MW
477 if not me: return '%s()' % _clsname(me)
478 return '%s(%s, %s)' % (_clsname(me), me.ix, me.iy)
d7ab1bab 479 def __str__(me):
480 if not me: return 'inf'
481 return '(%s, %s)' % (me.ix, me.iy)
96d7ed6c
MW
482 def _repr_pretty_(me, pp, cyclep):
483 if cyclep:
484 pp.text('...')
485 elif not me:
486 pp.text('inf')
487 else:
582568f1 488 ind = _pp_bgroup(pp, '(')
96d7ed6c
MW
489 pp.pretty(me.ix); pp.text(','); pp.breakable()
490 pp.pretty(me.iy)
582568f1 491 pp.end_group(ind, ')')
d7ab1bab 492_augment(ECPt, _tmp)
493
494class _tmp:
495 def __repr__(me):
330e6a74
MW
496 return '%s(curve = %r, G = %r, r = %s, h = %s)' % \
497 (_clsname(me), me.curve, me.G, me.r, me.h)
96d7ed6c 498 def _repr_pretty_(me, pp, cyclep):
582568f1 499 ind = _pp_bgroup_tyname(pp, me)
96d7ed6c 500 if cyclep:
582568f1 501 pp.text('...')
96d7ed6c 502 else:
96d7ed6c
MW
503 _pp_kv(pp, 'curve', me.curve); pp.text(','); pp.breakable()
504 _pp_kv(pp, 'G', me.G); pp.text(','); pp.breakable()
505 _pp_kv(pp, 'r', me.r); pp.text(','); pp.breakable()
506 _pp_kv(pp, 'h', me.h)
582568f1 507 pp.end_group(ind, ')')
6d481bc6
MW
508 def __hash__(me):
509 h = 0x9bedb8de
510 h ^= hash(me.curve)
511 h ^= 2*hash(me.G) & 0xffffffff
512 return h
96f89e4d
MW
513 def fromstring(str): return _checkend(ECInfo.parse(str))
514 fromstring = staticmethod(fromstring)
d7ab1bab 515 def group(me):
516 return ECGroup(me)
517_augment(ECInfo, _tmp)
518
519class _tmp:
520 def __repr__(me):
521 if not me: return '%r()' % (me.curve)
522 return '%r(%s, %s)' % (me.curve, me.x, me.y)
523 def __str__(me):
524 if not me: return 'inf'
525 return '(%s, %s)' % (me.x, me.y)
7a7aa30e
MW
526 def _repr_pretty_(me, pp, cyclep):
527 if cyclep:
528 pp.text('...')
529 elif not me:
530 pp.text('inf')
531 else:
532 ind = _pp_bgroup(pp, '(')
533 pp.pretty(me.x); pp.text(','); pp.breakable()
534 pp.pretty(me.y)
535 pp.end_group(ind, ')')
d7ab1bab 536_augment(ECPtCurve, _tmp)
537
00401529
MW
538###--------------------------------------------------------------------------
539### Key sizes.
ed8cc62d 540
d7ab1bab 541class _tmp:
330e6a74 542 def __repr__(me): return '%s(%d)' % (_clsname(me), me.default)
d7ab1bab 543 def check(me, sz): return True
544 def best(me, sz): return sz
dfb915d3 545 def pad(me, sz): return sz
d7ab1bab 546_augment(KeySZAny, _tmp)
547
548class _tmp:
549 def __repr__(me):
330e6a74
MW
550 return '%s(%d, %d, %d, %d)' % \
551 (_clsname(me), me.default, me.min, me.max, me.mod)
96d7ed6c 552 def _repr_pretty_(me, pp, cyclep):
582568f1 553 ind = _pp_bgroup_tyname(pp, me)
96d7ed6c 554 if cyclep:
582568f1 555 pp.text('...')
96d7ed6c 556 else:
96d7ed6c
MW
557 pp.pretty(me.default); pp.text(','); pp.breakable()
558 pp.pretty(me.min); pp.text(','); pp.breakable()
559 pp.pretty(me.max); pp.text(','); pp.breakable()
560 pp.pretty(me.mod)
582568f1 561 pp.end_group(ind, ')')
dfb915d3 562 def check(me, sz): return me.min <= sz <= me.max and sz%me.mod == 0
d7ab1bab 563 def best(me, sz):
1c7419c9 564 if sz < me.min: raise ValueError('key too small')
a9410db7 565 elif me.max is not None and sz > me.max: return me.max
dfb915d3
MW
566 else: return sz - sz%me.mod
567 def pad(me, sz):
a9410db7 568 if me.max is not None and sz > me.max: raise ValueError('key too large')
dfb915d3 569 elif sz < me.min: return me.min
8fc76cc0 570 else: sz += me.mod - 1; return sz - sz%me.mod
d7ab1bab 571_augment(KeySZRange, _tmp)
572
573class _tmp:
330e6a74 574 def __repr__(me): return '%s(%d, %s)' % (_clsname(me), me.default, me.set)
96d7ed6c 575 def _repr_pretty_(me, pp, cyclep):
582568f1 576 ind = _pp_bgroup_tyname(pp, me)
96d7ed6c 577 if cyclep:
582568f1 578 pp.text('...')
96d7ed6c 579 else:
96d7ed6c 580 pp.pretty(me.default); pp.text(','); pp.breakable()
582568f1 581 ind1 = _pp_bgroup(pp, '{')
96d7ed6c 582 _pp_commas(pp, pp.pretty, me.set)
582568f1
MW
583 pp.end_group(ind1, '}')
584 pp.end_group(ind, ')')
d7ab1bab 585 def check(me, sz): return sz in me.set
586 def best(me, sz):
587 found = -1
588 for i in me.set:
589 if found < i <= sz: found = i
1c7419c9 590 if found < 0: raise ValueError('key too small')
d7ab1bab 591 return found
dfb915d3
MW
592 def pad(me, sz):
593 found = -1
594 for i in me.set:
595 if sz <= i and (found == -1 or i < found): found = i
1c7419c9 596 if found < 0: raise ValueError('key too large')
dfb915d3 597 return found
d7ab1bab 598_augment(KeySZSet, _tmp)
599
00401529 600###--------------------------------------------------------------------------
96d7ed6c
MW
601### Key data objects.
602
603class _tmp:
618cbc92
MW
604 def merge(me, file, report = None):
605 """KF.merge(FILE, [report = <built-in-reporter>])"""
606 name = file.name
607 lno = 1
608 for line in file:
609 me.mergeline(name, lno, line, report)
610 lno += 1
611 return me
330e6a74 612 def __repr__(me): return '%s(%r)' % (_clsname(me), me.name)
96d7ed6c
MW
613_augment(KeyFile, _tmp)
614
615class _tmp:
618cbc92
MW
616 def extract(me, file, filter = ''):
617 """KEY.extract(FILE, [filter = <any>])"""
618 line = me.extractline(filter)
619 file.write(line)
620 return me
330e6a74 621 def __repr__(me): return '%s(%r)' % (_clsname(me), me.fulltag)
96d7ed6c
MW
622_augment(Key, _tmp)
623
624class _tmp:
625 def __repr__(me):
330e6a74 626 return '%s({%s})' % (_clsname(me),
d6542364 627 ', '.join(['%r: %r' % kv for kv in _iteritems(me)()]))
96d7ed6c 628 def _repr_pretty_(me, pp, cyclep):
582568f1 629 ind = _pp_bgroup_tyname(pp, me)
96d7ed6c 630 if cyclep: pp.text('...')
d6542364 631 else: _pp_dict(pp, _iteritems(me))
582568f1 632 pp.end_group(ind, ')')
96d7ed6c
MW
633_augment(KeyAttributes, _tmp)
634
635class _tmp:
849e8a20 636 def __repr__(me):
652e16ea
MW
637 return '%s(%s, %r)' % (_clsname(me),
638 _repr_secret(me._guts(),
639 not (me.flags & KF_NONSECRET)),
640 me.writeflags(me.flags))
96d7ed6c 641 def _repr_pretty_(me, pp, cyclep):
582568f1 642 ind = _pp_bgroup_tyname(pp, me)
96d7ed6c 643 if cyclep:
582568f1 644 pp.text('...')
96d7ed6c 645 else:
652e16ea
MW
646 _pp_secret(pp, me._guts(), not (me.flags & KF_NONSECRET))
647 pp.text(','); pp.breakable()
96d7ed6c 648 pp.pretty(me.writeflags(me.flags))
582568f1 649 pp.end_group(ind, ')')
c567f805
MW
650 def __hash__(me): return me._HASHBASE ^ hash(me._guts())
651 def __eq__(me, kd):
652 return type(me) == type(kd) and \
653 me._guts() == kd._guts() and \
654 me.flags == kd.flags
655 def __ne__(me, kd):
656 return not me == kd
849e8a20
MW
657_augment(KeyData, _tmp)
658
659class _tmp:
660 def _guts(me): return me.bin
c567f805
MW
661 def __eq__(me, kd):
662 return isinstance(kd, KeyDataBinary) and me.bin == kd.bin
96d7ed6c 663_augment(KeyDataBinary, _tmp)
c567f805 664KeyDataBinary._HASHBASE = 0x961755c3
96d7ed6c
MW
665
666class _tmp:
849e8a20 667 def _guts(me): return me.ct
96d7ed6c 668_augment(KeyDataEncrypted, _tmp)
c567f805 669KeyDataEncrypted._HASHBASE = 0xffe000d4
96d7ed6c
MW
670
671class _tmp:
849e8a20 672 def _guts(me): return me.mp
96d7ed6c 673_augment(KeyDataMP, _tmp)
c567f805 674KeyDataMP._HASHBASE = 0x1cb64d69
96d7ed6c
MW
675
676class _tmp:
849e8a20 677 def _guts(me): return me.str
96d7ed6c 678_augment(KeyDataString, _tmp)
c567f805 679KeyDataString._HASHBASE = 0x349c33ea
96d7ed6c
MW
680
681class _tmp:
849e8a20 682 def _guts(me): return me.ecpt
96d7ed6c 683_augment(KeyDataECPt, _tmp)
c567f805 684KeyDataECPt._HASHBASE = 0x2509718b
96d7ed6c
MW
685
686class _tmp:
687 def __repr__(me):
330e6a74 688 return '%s({%s})' % (_clsname(me),
d6542364 689 ', '.join(['%r: %r' % kv for kv in _iteritems(me)]))
96d7ed6c 690 def _repr_pretty_(me, pp, cyclep):
582568f1 691 ind = _pp_bgroup_tyname(pp, me, '({ ')
96d7ed6c 692 if cyclep: pp.text('...')
d6542364 693 else: _pp_dict(pp, _iteritems(me))
582568f1 694 pp.end_group(ind, ' })')
c567f805
MW
695 def __hash__(me):
696 h = me._HASHBASE
697 for k, v in _iteritems(me):
698 h = ((h << 1) ^ 3*hash(k) ^ 5*hash(v))&0xffffffff
699 return h
700 def __eq__(me, kd):
701 if type(me) != type(kd) or me.flags != kd.flags or len(me) != len(kd):
702 return False
703 for k, v in _iteritems(me):
704 try: vv = kd[k]
705 except KeyError: return False
706 if v != vv: return False
707 return True
96d7ed6c 708_augment(KeyDataStructured, _tmp)
c567f805 709KeyDataStructured._HASHBASE = 0x85851b21
96d7ed6c
MW
710
711###--------------------------------------------------------------------------
00401529 712### Abstract groups.
ed8cc62d 713
d7ab1bab 714class _tmp:
715 def __repr__(me):
330e6a74 716 return '%s(p = %s, r = %s, g = %s)' % (_clsname(me), me.p, me.r, me.g)
96d7ed6c 717 def _repr_pretty_(me, pp, cyclep):
582568f1 718 ind = _pp_bgroup_tyname(pp, me)
96d7ed6c 719 if cyclep:
582568f1 720 pp.text('...')
96d7ed6c 721 else:
96d7ed6c
MW
722 _pp_kv(pp, 'p', me.p); pp.text(','); pp.breakable()
723 _pp_kv(pp, 'r', me.r); pp.text(','); pp.breakable()
724 _pp_kv(pp, 'g', me.g)
582568f1 725 pp.end_group(ind, ')')
d7ab1bab 726_augment(FGInfo, _tmp)
727
728class _tmp:
729 def group(me): return PrimeGroup(me)
730_augment(DHInfo, _tmp)
731
732class _tmp:
733 def group(me): return BinGroup(me)
734_augment(BinDHInfo, _tmp)
735
736class _tmp:
737 def __repr__(me):
330e6a74 738 return '%s(%r)' % (_clsname(me), me.info)
99d932fe
MW
739 def _repr_pretty_(me, pp, cyclep):
740 ind = _pp_bgroup_tyname(pp, me)
741 if cyclep: pp.text('...')
742 else: pp.pretty(me.info)
743 pp.end_group(ind, ')')
d7ab1bab 744_augment(Group, _tmp)
745
746class _tmp:
6d481bc6
MW
747 def __hash__(me):
748 info = me.info
749 h = 0xbce3cfe6
750 h ^= hash(info.p)
751 h ^= 2*hash(info.r) & 0xffffffff
752 h ^= 5*hash(info.g) & 0xffffffff
753 return h
d7012c2b 754 def _get_geval(me, x): return MP(x)
6d481bc6
MW
755_augment(PrimeGroup, _tmp)
756
757class _tmp:
758 def __hash__(me):
759 info = me.info
760 h = 0x80695949
761 h ^= hash(info.p)
762 h ^= 2*hash(info.r) & 0xffffffff
763 h ^= 5*hash(info.g) & 0xffffffff
764 return h
d7012c2b 765 def _get_geval(me, x): return GF(x)
6d481bc6
MW
766_augment(BinGroup, _tmp)
767
768class _tmp:
769 def __hash__(me): return 0x0ec23dab ^ hash(me.info)
d7012c2b 770 def _get_geval(me, x): return x.toec()
6d481bc6
MW
771_augment(ECGroup, _tmp)
772
773class _tmp:
d7ab1bab 774 def __repr__(me):
775 return '%r(%r)' % (me.group, str(me))
d7012c2b
MW
776 def _repr_pretty_(me, pp, cyclep):
777 pp.pretty(type(me)._get_geval(me))
d7ab1bab 778_augment(GE, _tmp)
779
00401529
MW
780###--------------------------------------------------------------------------
781### RSA encoding techniques.
ed8cc62d
MW
782
783class PKCS1Crypt (object):
467c2619 784 def __init__(me, ep = _bin(''), rng = rand):
d7ab1bab 785 me.ep = ep
786 me.rng = rng
787 def encode(me, msg, nbits):
788 return _base._p1crypt_encode(msg, nbits, me.ep, me.rng)
789 def decode(me, ct, nbits):
790 return _base._p1crypt_decode(ct, nbits, me.ep, me.rng)
791
ed8cc62d 792class PKCS1Sig (object):
467c2619 793 def __init__(me, ep = _bin(''), rng = rand):
d7ab1bab 794 me.ep = ep
795 me.rng = rng
796 def encode(me, msg, nbits):
797 return _base._p1sig_encode(msg, nbits, me.ep, me.rng)
798 def decode(me, msg, sig, nbits):
799 return _base._p1sig_decode(msg, sig, nbits, me.ep, me.rng)
800
ed8cc62d 801class OAEP (object):
467c2619 802 def __init__(me, mgf = sha_mgf, hash = sha, ep = _bin(''), rng = rand):
d7ab1bab 803 me.mgf = mgf
804 me.hash = hash
805 me.ep = ep
806 me.rng = rng
807 def encode(me, msg, nbits):
808 return _base._oaep_encode(msg, nbits, me.mgf, me.hash, me.ep, me.rng)
809 def decode(me, ct, nbits):
810 return _base._oaep_decode(ct, nbits, me.mgf, me.hash, me.ep, me.rng)
811
ed8cc62d 812class PSS (object):
d7ab1bab 813 def __init__(me, mgf = sha_mgf, hash = sha, saltsz = None, rng = rand):
814 me.mgf = mgf
815 me.hash = hash
816 if saltsz is None:
817 saltsz = hash.hashsz
818 me.saltsz = saltsz
819 me.rng = rng
820 def encode(me, msg, nbits):
821 return _base._pss_encode(msg, nbits, me.mgf, me.hash, me.saltsz, me.rng)
822 def decode(me, msg, sig, nbits):
823 return _base._pss_decode(msg, sig, nbits,
00401529 824 me.mgf, me.hash, me.saltsz, me.rng)
d7ab1bab 825
826class _tmp:
827 def encrypt(me, msg, enc):
828 return me.pubop(enc.encode(msg, me.n.nbits))
829 def verify(me, msg, sig, enc):
830 if msg is None: return enc.decode(msg, me.pubop(sig), me.n.nbits)
831 try:
832 x = enc.decode(msg, me.pubop(sig), me.n.nbits)
833 return x is None or x == msg
834 except ValueError:
b2687a0a 835 return False
bbd94558
MW
836 def __repr__(me):
837 return '%s(n = %r, e = %r)' % (_clsname(me), me.n, me.e)
838 def _repr_pretty_(me, pp, cyclep):
839 ind = _pp_bgroup_tyname(pp, me)
840 if cyclep:
841 pp.text('...')
842 else:
843 _pp_kv(pp, 'n', me.n); pp.text(','); pp.breakable()
844 _pp_kv(pp, 'e', me.e)
845 pp.end_group(ind, ')')
d7ab1bab 846_augment(RSAPub, _tmp)
847
848class _tmp:
849 def decrypt(me, ct, enc): return enc.decode(me.privop(ct), me.n.nbits)
850 def sign(me, msg, enc): return me.privop(enc.encode(msg, me.n.nbits))
bbd94558
MW
851 def __repr__(me):
852 return '%s(n = %r, e = %r, d = %s, ' \
853 'p = %s, q = %s, dp = %s, dq = %s, q_inv = %s)' % \
854 (_clsname(me), me.n, me.e,
855 _repr_secret(me.d), _repr_secret(me.p), _repr_secret(me.q),
856 _repr_secret(me.dp), _repr_secret(me.dq), _repr_secret(me.q_inv))
857 def _repr_pretty_(me, pp, cyclep):
858 ind = _pp_bgroup_tyname(pp, me)
859 if cyclep:
860 pp.text('...')
861 else:
862 _pp_kv(pp, 'n', me.n); pp.text(','); pp.breakable()
863 _pp_kv(pp, 'e', me.e); pp.text(','); pp.breakable()
864 _pp_kv(pp, 'd', me.d, secretp = True); pp.text(','); pp.breakable()
865 _pp_kv(pp, 'p', me.p, secretp = True); pp.text(','); pp.breakable()
866 _pp_kv(pp, 'q', me.q, secretp = True); pp.text(','); pp.breakable()
867 _pp_kv(pp, 'dp', me.dp, secretp = True); pp.text(','); pp.breakable()
868 _pp_kv(pp, 'dq', me.dq, secretp = True); pp.text(','); pp.breakable()
869 _pp_kv(pp, 'q_inv', me.q_inv, secretp = True)
870 pp.end_group(ind, ')')
d7ab1bab 871_augment(RSAPriv, _tmp)
872
00401529 873###--------------------------------------------------------------------------
bbd94558
MW
874### DSA and related schemes.
875
876class _tmp:
1b3b79da
MW
877 def __repr__(me): return '%s(G = %r, p = %r, hash = %r)' % \
878 (_clsname(me), me.G, me.p, me.hash)
bbd94558
MW
879 def _repr_pretty_(me, pp, cyclep):
880 ind = _pp_bgroup_tyname(pp, me)
881 if cyclep:
882 pp.text('...')
883 else:
884 _pp_kv(pp, 'G', me.G); pp.text(','); pp.breakable()
1b3b79da
MW
885 _pp_kv(pp, 'p', me.p); pp.text(','); pp.breakable()
886 _pp_kv(pp, 'hash', me.hash)
bbd94558
MW
887 pp.end_group(ind, ')')
888_augment(DSAPub, _tmp)
889_augment(KCDSAPub, _tmp)
890
891class _tmp:
1b3b79da
MW
892 def __repr__(me): return '%s(G = %r, u = %s, p = %r, hash = %r)' % \
893 (_clsname(me), me.G, _repr_secret(me.u), me.p, me.hash)
bbd94558
MW
894 def _repr_pretty_(me, pp, cyclep):
895 ind = _pp_bgroup_tyname(pp, me)
896 if cyclep:
897 pp.text('...')
898 else:
899 _pp_kv(pp, 'G', me.G); pp.text(','); pp.breakable()
900 _pp_kv(pp, 'u', me.u, True); pp.text(','); pp.breakable()
1b3b79da
MW
901 _pp_kv(pp, 'p', me.p); pp.text(','); pp.breakable()
902 _pp_kv(pp, 'hash', me.hash)
bbd94558
MW
903 pp.end_group(ind, ')')
904_augment(DSAPriv, _tmp)
905_augment(KCDSAPriv, _tmp)
906
907###--------------------------------------------------------------------------
eb8aa4ec 908### Bernstein's elliptic curve crypto and related schemes.
848ba392 909
8e6f45a3
MW
910X25519_BASE = MP(9).storel(32)
911X448_BASE = MP(5).storel(56)
eb8aa4ec 912
5a8b43b3 913Z128 = ByteString.zero(16)
848ba392 914
925aa45b 915class _BasePub (object):
f40e338b 916 def __init__(me, pub, *args, **kw):
1c7419c9 917 if not me._PUBSZ.check(len(pub)): raise ValueError('bad public key')
925aa45b 918 super(_BasePub, me).__init__(*args, **kw)
848ba392 919 me.pub = pub
bbd94558 920 def __repr__(me): return '%s(pub = %r)' % (_clsname(me), me.pub)
925aa45b 921 def _pp(me, pp): _pp_kv(pp, 'pub', me.pub)
bbd94558
MW
922 def _repr_pretty_(me, pp, cyclep):
923 ind = _pp_bgroup_tyname(pp, me)
925aa45b
MW
924 if cyclep: pp.text('...')
925 else: me._pp(pp)
bbd94558 926 pp.end_group(ind, ')')
848ba392 927
925aa45b 928class _BasePriv (object):
f40e338b 929 def __init__(me, priv, pub = None, *args, **kw):
1c7419c9 930 if not me._KEYSZ.check(len(priv)): raise ValueError('bad private key')
925aa45b
MW
931 if pub is None: pub = me._pubkey(priv)
932 super(_BasePriv, me).__init__(pub = pub, *args, **kw)
848ba392 933 me.priv = priv
925aa45b
MW
934 @classmethod
935 def generate(cls, rng = rand):
936 return cls(rng.block(cls._KEYSZ.default))
937 def __repr__(me):
938 return '%s(priv = %d, pub = %r)' % \
939 (_clsname(me), _repr_secret(me.priv), me.pub)
940 def _pp(me, pp):
941 _pp_kv(pp, 'priv', me.priv, secretp = True); pp.text(','); pp.breakable()
942 super(_BasePriv, me)._pp(pp)
943
944class _XDHPub (_BasePub): pass
945
946class _XDHPriv (_BasePriv):
947 def _pubkey(me, priv): return me._op(priv, me._BASE)
848ba392 948 def agree(me, you): return me._op(me.priv, you.pub)
925aa45b
MW
949 def boxkey(me, recip): return me._hashkey(me.agree(recip))
950 def box(me, recip, n, m): return secret_box(me.boxkey(recip), n, m)
951 def unbox(me, recip, n, c): return secret_unbox(me.boxkey(recip), n, c)
848ba392 952
925aa45b
MW
953class X25519Pub (_XDHPub):
954 _PUBSZ = KeySZSet(X25519_PUBSZ)
848ba392
MW
955 _BASE = X25519_BASE
956
925aa45b
MW
957class X25519Priv (_XDHPriv, X25519Pub):
958 _KEYSZ = KeySZSet(X25519_KEYSZ)
848ba392
MW
959 def _op(me, k, X): return x25519(k, X)
960 def _hashkey(me, z): return hsalsa20_prf(z, Z128)
961
925aa45b
MW
962class X448Pub (_XDHPub):
963 _PUBSZ = KeySZSet(X448_PUBSZ)
eb8aa4ec
MW
964 _BASE = X448_BASE
965
925aa45b
MW
966class X448Priv (_XDHPriv, X448Pub):
967 _KEYSZ = KeySZSet(X448_KEYSZ)
eb8aa4ec 968 def _op(me, k, X): return x448(k, X)
f1b0cf0d 969 def _hashkey(me, z): return Shake256().hash(z).done(salsa20.keysz.default)
eb8aa4ec 970
925aa45b 971class _EdDSAPub (_BasePub):
058f0a00
MW
972 def beginhash(me): return me._HASH()
973 def endhash(me, h): return h.done()
925aa45b
MW
974
975class _EdDSAPriv (_BasePriv, _EdDSAPub):
976 pass
977
978class Ed25519Pub (_EdDSAPub):
979 _PUBSZ = KeySZSet(ED25519_PUBSZ)
058f0a00 980 _HASH = sha512
5c4c0231
MW
981 def verify(me, msg, sig, **kw):
982 return ed25519_verify(me.pub, msg, sig, **kw)
dafb2da4 983
925aa45b
MW
984class Ed25519Priv (_EdDSAPriv, Ed25519Pub):
985 _KEYSZ = KeySZAny(ED25519_KEYSZ)
986 def _pubkey(me, priv): return ed25519_pubkey(priv)
5c4c0231
MW
987 def sign(me, msg, **kw):
988 return ed25519_sign(me.priv, msg, pub = me.pub, **kw)
dafb2da4 989
eee202c3
MW
990class Ed448Pub (_EdDSAPub):
991 _PUBSZ = KeySZSet(ED448_PUBSZ)
992 _HASH = shake256
993 def verify(me, msg, sig, **kw):
994 return ed448_verify(me.pub, msg, sig, **kw)
995
996class Ed448Priv (_EdDSAPriv, Ed448Pub):
997 _KEYSZ = KeySZAny(ED448_KEYSZ)
998 def _pubkey(me, priv): return ed448_pubkey(priv)
999 def sign(me, msg, **kw):
1000 return ed448_sign(me.priv, msg, pub = me.pub, **kw)
1001
848ba392 1002###--------------------------------------------------------------------------
a539ffb8
MW
1003### Built-in algorithm and group tables.
1004
1005class _tmp:
ed8cc62d 1006 def __repr__(me):
d6542364 1007 return '{%s}' % ', '.join(['%r: %r' % kv for kv in _iteritems(me)])
96d7ed6c 1008 def _repr_pretty_(me, pp, cyclep):
582568f1
MW
1009 ind = _pp_bgroup(pp, '{ ')
1010 if cyclep: pp.text('...')
d6542364 1011 else: _pp_dict(pp, _iteritems(me))
582568f1 1012 pp.end_group(ind, ' }')
a539ffb8 1013_augment(_base._MiscTable, _tmp)
ed8cc62d 1014
00401529
MW
1015###--------------------------------------------------------------------------
1016### Prime number generation.
ed8cc62d
MW
1017
1018class PrimeGenEventHandler (object):
1019 def pg_begin(me, ev):
1020 return me.pg_try(ev)
1021 def pg_done(me, ev):
1022 return PGEN_DONE
1023 def pg_abort(me, ev):
1024 return PGEN_TRY
1025 def pg_fail(me, ev):
1026 return PGEN_TRY
1027 def pg_pass(me, ev):
1028 return PGEN_TRY
d7ab1bab 1029
1030class SophieGermainStepJump (object):
1031 def pg_begin(me, ev):
1032 me.lf = PrimeFilter(ev.x)
1033 me.hf = me.lf.muladd(2, 1)
1034 return me.cont(ev)
1035 def pg_try(me, ev):
1036 me.step()
1037 return me.cont(ev)
1038 def cont(me, ev):
1039 while me.lf.status == PGEN_FAIL or me.hf.status == PGEN_FAIL:
1040 me.step()
1041 if me.lf.status == PGEN_ABORT or me.hf.status == PGEN_ABORT:
1042 return PGEN_ABORT
1043 ev.x = me.lf.x
1044 if me.lf.status == PGEN_DONE and me.hf.status == PGEN_DONE:
1045 return PGEN_DONE
1046 return PGEN_TRY
1047 def pg_done(me, ev):
1048 del me.lf
1049 del me.hf
1050
1051class SophieGermainStepper (SophieGermainStepJump):
1052 def __init__(me, step):
1053 me.lstep = step;
1054 me.hstep = 2 * step
1055 def step(me):
1056 me.lf.step(me.lstep)
1057 me.hf.step(me.hstep)
1058
1059class SophieGermainJumper (SophieGermainStepJump):
1060 def __init__(me, jump):
1061 me.ljump = PrimeFilter(jump);
1062 me.hjump = me.ljump.muladd(2, 0)
1063 def step(me):
1064 me.lf.jump(me.ljump)
1065 me.hf.jump(me.hjump)
1066 def pg_done(me, ev):
1067 del me.ljump
1068 del me.hjump
1069 SophieGermainStepJump.pg_done(me, ev)
1070
1071class SophieGermainTester (object):
1072 def __init__(me):
1073 pass
1074 def pg_begin(me, ev):
1075 me.lr = RabinMiller(ev.x)
1076 me.hr = RabinMiller(2 * ev.x + 1)
1077 def pg_try(me, ev):
1078 lst = me.lr.test(ev.rng.range(me.lr.x))
1079 if lst != PGEN_PASS and lst != PGEN_DONE:
1080 return lst
1081 rst = me.hr.test(ev.rng.range(me.hr.x))
1082 if rst != PGEN_PASS and rst != PGEN_DONE:
1083 return rst
1084 if lst == PGEN_DONE and rst == PGEN_DONE:
1085 return PGEN_DONE
1086 return PGEN_PASS
1087 def pg_done(me, ev):
1088 del me.lr
1089 del me.hr
1090
d7ab1bab 1091class PrimitiveStepper (PrimeGenEventHandler):
1092 def __init__(me):
1093 pass
1094 def pg_try(me, ev):
1095 ev.x = me.i.next()
1096 return PGEN_TRY
1097 def pg_begin(me, ev):
1098 me.i = iter(smallprimes)
1099 return me.pg_try(ev)
1100
1101class PrimitiveTester (PrimeGenEventHandler):
1102 def __init__(me, mod, hh = [], exp = None):
1103 me.mod = MPMont(mod)
1104 me.exp = exp
1105 me.hh = hh
1106 def pg_try(me, ev):
1107 x = ev.x
1108 if me.exp is not None:
1109 x = me.mod.exp(x, me.exp)
1110 if x == 1: return PGEN_FAIL
1111 for h in me.hh:
1112 if me.mod.exp(x, h) == 1: return PGEN_FAIL
1113 ev.x = x
1114 return PGEN_DONE
1115
1116class SimulStepper (PrimeGenEventHandler):
1117 def __init__(me, mul = 2, add = 1, step = 2):
1118 me.step = step
1119 me.mul = mul
1120 me.add = add
1121 def _stepfn(me, step):
1122 if step <= 0:
1c7419c9 1123 raise ValueError('step must be positive')
d7ab1bab 1124 if step <= MPW_MAX:
1125 return lambda f: f.step(step)
1126 j = PrimeFilter(step)
1127 return lambda f: f.jump(j)
1128 def pg_begin(me, ev):
1129 x = ev.x
1130 me.lf = PrimeFilter(x)
1131 me.hf = PrimeFilter(x * me.mul + me.add)
1132 me.lstep = me._stepfn(me.step)
1133 me.hstep = me._stepfn(me.step * me.mul)
1134 SimulStepper._cont(me, ev)
1135 def pg_try(me, ev):
1136 me._step()
1137 me._cont(ev)
1138 def _step(me):
1139 me.lstep(me.lf)
1140 me.hstep(me.hf)
1141 def _cont(me, ev):
1142 while me.lf.status == PGEN_FAIL or me.hf.status == PGEN_FAIL:
1143 me._step()
1144 if me.lf.status == PGEN_ABORT or me.hf.status == PGEN_ABORT:
1145 return PGEN_ABORT
1146 ev.x = me.lf.x
1147 if me.lf.status == PGEN_DONE and me.hf.status == PGEN_DONE:
1148 return PGEN_DONE
1149 return PGEN_TRY
1150 def pg_done(me, ev):
1151 del me.lf
1152 del me.hf
1153 del me.lstep
1154 del me.hstep
1155
1156class SimulTester (PrimeGenEventHandler):
1157 def __init__(me, mul = 2, add = 1):
1158 me.mul = mul
1159 me.add = add
1160 def pg_begin(me, ev):
1161 x = ev.x
1162 me.lr = RabinMiller(x)
1163 me.hr = RabinMiller(x * me.mul + me.add)
1164 def pg_try(me, ev):
1165 lst = me.lr.test(ev.rng.range(me.lr.x))
1166 if lst != PGEN_PASS and lst != PGEN_DONE:
1167 return lst
1168 rst = me.hr.test(ev.rng.range(me.hr.x))
1169 if rst != PGEN_PASS and rst != PGEN_DONE:
1170 return rst
1171 if lst == PGEN_DONE and rst == PGEN_DONE:
1172 return PGEN_DONE
1173 return PGEN_PASS
1174 def pg_done(me, ev):
1175 del me.lr
1176 del me.hr
1177
1178def sgprime(start, step = 2, name = 'p', event = pgen_nullev, nsteps = 0):
1179 start = MP(start)
1180 return pgen(start, name, SimulStepper(step = step), SimulTester(), event,
00401529 1181 nsteps, RabinMiller.iters(start.nbits))
d7ab1bab 1182
1183def findprimitive(mod, hh = [], exp = None, name = 'g', event = pgen_nullev):
1184 return pgen(0, name, PrimitiveStepper(), PrimitiveTester(mod, hh, exp),
00401529 1185 event, 0, 1)
d7ab1bab 1186
1187def kcdsaprime(pbits, qbits, rng = rand,
00401529 1188 event = pgen_nullev, name = 'p', nsteps = 0):
a5fdb912
MW
1189 hbits = pbits - qbits - 1
1190 while True:
1191 h = pgen(rng.mp(hbits, 1), name + ' [h]',
1192 PrimeGenStepper(2), PrimeGenTester(),
1193 event, nsteps, RabinMiller.iters(hbits))
1194 while True:
1195 q0 = rng.mp(qbits, 1)
1196 p0 = 2*q0*h + 1
1197 if p0.nbits == pbits: break
1198 q = pgen(q0, name, SimulStepper(2*h, 1, 2),
1199 SimulTester(2 * h, 1), event, nsteps, RabinMiller.iters(qbits))
1200 p = 2*q*h + 1
1201 if q.nbits == qbits and p.nbits == pbits: return p, q, h
1202 elif nsteps: raise ValueError("prime generation failed")
d7ab1bab 1203
1204#----- That's all, folks ----------------------------------------------------