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