3 ### Setup for Catacomb/Python bindings
5 ### (c) 2004 Straylight/Edgeware
8 ###----- Licensing notice ---------------------------------------------------
10 ### This file is part of the Python interface to Catacomb.
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.
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.
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.
27 import types
as _types
28 from binascii
import hexlify
as _hexify
, unhexlify
as _unhexify
29 from sys
import argv
as _argv
31 ###--------------------------------------------------------------------------
34 ## For the benefit of the default keyreporter, we need the program na,e.
37 ## Initialize the module. Drag in the static methods of the various
38 ## classes; create names for the various known crypto algorithms.
45 for i
in ['MP', 'GF', 'Field',
46 'ECPt', 'ECPtCurve', 'ECCurve', 'ECInfo',
47 'DHInfo', 'BinDHInfo', 'RSAPriv', 'BBSPriv',
48 'PrimeFilter', 'RabinMiller',
56 setattr(c
, j
[plen
:], classmethod(b
[j
]))
57 for i
in [gcciphers
, gchashes
, gcmacs
, gcprps
]:
58 for c
in i
.itervalues():
59 d
[c
.name
.replace('-', '_').translate(None, '/')] = c
60 for c
in gccrands
.itervalues():
61 d
[c
.name
.replace('-', '_').translate(None, '/') + 'rand'] = c
64 ## A handy function for our work: add the methods of a named class to an
65 ## existing class. This is how we write the Python-implemented parts of our
70 if type(a
) is _types
.MethodType
:
72 elif type(a
) not in (_types
.FunctionType
, staticmethod, classmethod):
76 ## Parsing functions tend to return the object parsed and the remainder of
77 ## the input. This checks that the remainder is input and, if so, returns
82 raise SyntaxError, 'junk at end of string'
85 ## Some pretty-printing utilities.
86 def _clsname(me
): return type(me
).__name__
87 def _pp_str(me
, pp
, cyclep
): pp
.text(cyclep
and '...' or str(me
))
88 def _pp_bgroup(pp
, text
):
90 pp
.begin_group(ind
, text
)
92 def _pp_bgroup_tyname(pp
, obj
, open = '('):
93 return _pp_bgroup(pp
, _clsname(obj
) + open)
95 ind
= _pp_bgroup(pp
, k
+ ' = ')
98 def _pp_commas(pp
, printfn
, items
):
101 if firstp
: firstp
= False
102 else: pp
.text(','); pp
.breakable()
104 def _pp_dict(pp
, items
):
114 _pp_commas(pp
, p
, items
)
116 ###--------------------------------------------------------------------------
121 return ByteString(_unhexify(x
))
122 fromhex
= staticmethod(fromhex
)
126 return 'bytes(%r)' %
hex(me
)
127 _augment(ByteString
, _tmp
)
128 ByteString
.__hash__
= str.__hash__
129 bytes
= ByteString
.fromhex
131 ###--------------------------------------------------------------------------
137 return ctstreq(h
, hh
)
138 _augment(GHash
, _tmp
)
139 _augment(Poly1305Hash
, _tmp
)
141 ###--------------------------------------------------------------------------
142 ### NaCl `secretbox'.
144 def secret_box(k
, n
, m
):
145 E
= xsalsa20(k
).setiv(n
)
146 r
= E
.enczero(poly1305
.keysz
.default
)
147 s
= E
.enczero(poly1305
.masksz
)
149 t
= poly1305(r
)(s
).hash(y
).done()
150 return ByteString(t
+ y
)
152 def secret_unbox(k
, n
, c
):
153 E
= xsalsa20(k
).setiv(n
)
154 r
= E
.enczero(poly1305
.keysz
.default
)
155 s
= E
.enczero(poly1305
.masksz
)
156 y
= c
[poly1305
.tagsz
:]
157 if not poly1305(r
)(s
).hash(y
).check(c
[0:poly1305
.tagsz
]):
158 raise ValueError, 'decryption failed'
159 return E
.decrypt(c
[poly1305
.tagsz
:])
161 ###--------------------------------------------------------------------------
162 ### Multiprecision integers and binary polynomials.
165 if isinstance(x
, BaseRat
): return x
._n
, x
._d
167 class BaseRat (object):
168 """Base class implementing fields of fractions over Euclidean domains."""
169 def __new__(cls
, a
, b
):
170 a
, b
= cls
.RING(a
), cls
.RING(b
)
174 me
= super(BaseRat
, cls
).__new__(cls
)
179 def numer(me
): return me
._n
181 def denom(me
): return me
._d
182 def __str__(me
): return '%s/%s' %
(me
._n
, me
._d
)
183 def __repr__(me
): return '%s(%s, %s)' %
(_clsname(me
), me
._n
, me
._d
)
184 _repr_pretty_
= _pp_str
186 def __add__(me
, you
):
187 n
, d
= _split_rat(you
)
188 return type(me
)(me
._n
*d
+ n
*me
._d
, d
*me
._d
)
190 def __sub__(me
, you
):
191 n
, d
= _split_rat(you
)
192 return type(me
)(me
._n
*d
- n
*me
._d
, d
*me
._d
)
193 def __rsub__(me
, you
):
194 n
, d
= _split_rat(you
)
195 return type(me
)(n
*me
._d
- me
._n
*d
, d
*me
._d
)
196 def __mul__(me
, you
):
197 n
, d
= _split_rat(you
)
198 return type(me
)(me
._n
*n
, me
._d
*d
)
199 def __div__(me
, you
):
200 n
, d
= _split_rat(you
)
201 return type(me
)(me
._n
*d
, me
._d
*n
)
202 def __rdiv__(me
, you
):
203 n
, d
= _split_rat(you
)
204 return type(me
)(me
._d
*n
, me
._n
*d
)
205 def __cmp__(me
, you
):
206 n
, d
= _split_rat(you
)
207 return type(me
)(me
._n
*d
, n
*me
._d
)
208 def __rcmp__(me
, you
):
209 n
, d
= _split_rat(you
)
210 return cmp(n
*me
._d
, me
._n
*d
)
212 class IntRat (BaseRat
):
215 class GFRat (BaseRat
):
219 def negp(x
): return x
< 0
220 def posp(x
): return x
> 0
221 def zerop(x
): return x
== 0
222 def oddp(x
): return x
.testbit(0)
223 def evenp(x
): return not x
.testbit(0)
224 def mont(x
): return MPMont(x
)
225 def barrett(x
): return MPBarrett(x
)
226 def reduce(x
): return MPReduce(x
)
227 def __div__(me
, you
): return IntRat(me
, you
)
228 def __rdiv__(me
, you
): return IntRat(you
, me
)
229 _repr_pretty_
= _pp_str
233 def zerop(x
): return x
== 0
234 def reduce(x
): return GFReduce(x
)
235 def trace(x
, y
): return x
.reduce().trace(y
)
236 def halftrace(x
, y
): return x
.reduce().halftrace(y
)
237 def modsqrt(x
, y
): return x
.reduce().sqrt(y
)
238 def quadsolve(x
, y
): return x
.reduce().quadsolve(y
)
239 def __div__(me
, you
): return GFRat(me
, you
)
240 def __rdiv__(me
, you
): return GFRat(you
, me
)
241 _repr_pretty_
= _pp_str
246 'product(ITERABLE) or product(I, ...) -> PRODUCT'
247 return MPMul(*arg
).done()
248 product
= staticmethod(product
)
249 _augment(MPMul
, _tmp
)
251 ###--------------------------------------------------------------------------
255 def fromstring(str): return _checkend(Field
.parse(str))
256 fromstring
= staticmethod(fromstring
)
257 _augment(Field
, _tmp
)
260 def __repr__(me
): return '%s(%sL)' %
(_clsname(me
), me
.p
)
261 def __hash__(me
): return 0x114401de ^
hash(me
.p
)
262 def _repr_pretty_(me
, pp
, cyclep
):
263 ind
= _pp_bgroup_tyname(pp
, me
)
264 if cyclep
: pp
.text('...')
265 else: pp
.pretty(me
.p
)
266 pp
.end_group(ind
, ')')
267 def ec(me
, a
, b
): return ECPrimeProjCurve(me
, a
, b
)
268 _augment(PrimeField
, _tmp
)
271 def __repr__(me
): return '%s(%#xL)' %
(_clsname(me
), me
.p
)
272 def ec(me
, a
, b
): return ECBinProjCurve(me
, a
, b
)
273 def _repr_pretty_(me
, pp
, cyclep
):
274 ind
= _pp_bgroup_tyname(pp
, me
)
275 if cyclep
: pp
.text('...')
276 else: pp
.text('%#x' % me
.p
)
277 pp
.end_group(ind
, ')')
278 _augment(BinField
, _tmp
)
281 def __hash__(me
): return 0x23e4701c ^
hash(me
.p
)
282 _augment(BinPolyField
, _tmp
)
288 h ^
= 2*hash(me
.beta
) & 0xffffffff
290 _augment(BinNormField
, _tmp
)
293 def __str__(me
): return str(me
.value
)
294 def __repr__(me
): return '%s(%s)' %
(repr(me
.field
), repr(me
.value
))
295 _repr_pretty_
= _pp_str
298 ###--------------------------------------------------------------------------
303 return '%s(%r, %s, %s)' %
(_clsname(me
), me
.field
, me
.a
, me
.b
)
304 def _repr_pretty_(me
, pp
, cyclep
):
305 ind
= _pp_bgroup_tyname(pp
, me
)
309 pp
.pretty(me
.field
); pp
.text(','); pp
.breakable()
310 pp
.pretty(me
.a
); pp
.text(','); pp
.breakable()
312 pp
.end_group(ind
, ')')
314 return ecpt
.frombuf(me
, s
)
316 return ecpt
.fromraw(me
, s
)
319 _augment(ECCurve
, _tmp
)
325 h ^
= 2*hash(me
.a
) ^
0xffffffff
326 h ^
= 5*hash(me
.b
) ^
0xffffffff
328 _augment(ECPrimeCurve
, _tmp
)
334 h ^
= 2*hash(me
.a
) ^
0xffffffff
335 h ^
= 5*hash(me
.b
) ^
0xffffffff
337 _augment(ECBinCurve
, _tmp
)
341 if not me
: return '%s()' %
_clsname(me
)
342 return '%s(%s, %s)' %
(_clsname(me
), me
.ix
, me
.iy
)
344 if not me
: return 'inf'
345 return '(%s, %s)' %
(me
.ix
, me
.iy
)
346 def _repr_pretty_(me
, pp
, cyclep
):
352 ind
= _pp_bgroup(pp
, '(')
353 pp
.pretty(me
.ix
); pp
.text(','); pp
.breakable()
355 pp
.end_group(ind
, ')')
360 return '%s(curve = %r, G = %r, r = %s, h = %s)' % \
361 (_clsname(me
), me
.curve
, me
.G
, me
.r
, me
.h
)
362 def _repr_pretty_(me
, pp
, cyclep
):
363 ind
= _pp_bgroup_tyname(pp
, me
)
367 _pp_kv(pp
, 'curve', me
.curve
); pp
.text(','); pp
.breakable()
368 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
369 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
370 _pp_kv(pp
, 'h', me
.h
)
371 pp
.end_group(ind
, ')')
375 h ^
= 2*hash(me
.G
) & 0xffffffff
379 _augment(ECInfo
, _tmp
)
383 if not me
: return '%r()' %
(me
.curve
)
384 return '%r(%s, %s)' %
(me
.curve
, me
.x
, me
.y
)
386 if not me
: return 'inf'
387 return '(%s, %s)' %
(me
.x
, me
.y
)
388 def _repr_pretty_(me
, pp
, cyclep
):
394 ind
= _pp_bgroup(pp
, '(')
395 pp
.pretty(me
.x
); pp
.text(','); pp
.breakable()
397 pp
.end_group(ind
, ')')
398 _augment(ECPtCurve
, _tmp
)
400 ###--------------------------------------------------------------------------
404 def __repr__(me
): return '%s(%d)' %
(_clsname(me
), me
.default
)
405 def check(me
, sz
): return True
406 def best(me
, sz
): return sz
407 _augment(KeySZAny
, _tmp
)
411 return '%s(%d, %d, %d, %d)' % \
412 (_clsname(me
), me
.default
, me
.min, me
.max, me
.mod
)
413 def _repr_pretty_(me
, pp
, cyclep
):
414 ind
= _pp_bgroup_tyname(pp
, me
)
418 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
419 pp
.pretty(me
.min); pp
.text(','); pp
.breakable()
420 pp
.pretty(me
.max); pp
.text(','); pp
.breakable()
422 pp
.end_group(ind
, ')')
423 def check(me
, sz
): return me
.min <= sz
<= me
.max and sz % me
.mod
== 0
425 if sz
< me
.min: raise ValueError, 'key too small'
426 elif sz
> me
.max: return me
.max
427 else: return sz
- (sz % me
.mod
)
428 _augment(KeySZRange
, _tmp
)
431 def __repr__(me
): return '%s(%d, %s)' %
(_clsname(me
), me
.default
, me
.set)
432 def _repr_pretty_(me
, pp
, cyclep
):
433 ind
= _pp_bgroup_tyname(pp
, me
)
437 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
438 ind1
= _pp_bgroup(pp
, '{')
439 _pp_commas(pp
, pp
.pretty
, me
.set)
440 pp
.end_group(ind1
, '}')
441 pp
.end_group(ind
, ')')
442 def check(me
, sz
): return sz
in me
.set
446 if found
< i
<= sz
: found
= i
447 if found
< 0: raise ValueError, 'key too small'
449 _augment(KeySZSet
, _tmp
)
451 ###--------------------------------------------------------------------------
452 ### Key data objects.
455 def __repr__(me
): return '%s(%r)' %
(_clsname(me
), me
.name
)
456 _augment(KeyFile
, _tmp
)
459 def __repr__(me
): return '%s(%r)' %
(_clsname(me
), me
.fulltag
)
464 return '%s({%s})' %
(_clsname(me
),
465 ', '.join(['%r: %r' % kv
for kv
in me
.iteritems()]))
466 def _repr_pretty_(me
, pp
, cyclep
):
467 ind
= _pp_bgroup_tyname(pp
, me
)
468 if cyclep
: pp
.text('...')
469 else: _pp_dict(pp
, me
.iteritems())
470 pp
.end_group(ind
, ')')
471 _augment(KeyAttributes
, _tmp
)
475 return '%s(%s, %r)' % \
476 (_clsname(me
), repr(me
._guts()), me
.writeflags(me
.flags
))
477 def _repr_pretty_(me
, pp
, cyclep
):
478 ind
= _pp_bgroup_tyname(pp
, me
)
482 pp
.pretty(me
.guts()); pp
.text(','); pp
.breakable()
483 pp
.pretty(me
.writeflags(me
.flags
))
484 pp
.end_group(ind
, ')')
485 _augment(KeyData
, _tmp
)
488 def _guts(me
): return me
.bin
489 _augment(KeyDataBinary
, _tmp
)
492 def _guts(me
): return me
.ct
493 _augment(KeyDataEncrypted
, _tmp
)
496 def _guts(me
): return me
.mp
497 _augment(KeyDataMP
, _tmp
)
500 def _guts(me
): return me
.str
501 _augment(KeyDataString
, _tmp
)
504 def _guts(me
): return me
.ecpt
505 _augment(KeyDataECPt
, _tmp
)
509 return '%s({%s})' %
(_clsname(me
),
510 ', '.join(['%r: %r' % kv
for kv
in me
.iteritems()]))
511 def _repr_pretty_(me
, pp
, cyclep
):
512 ind
= _pp_bgroup_tyname(pp
, me
, '({ ')
513 if cyclep
: pp
.text('...')
514 else: _pp_dict(pp
, me
.iteritems())
515 pp
.end_group(ind
, ' })')
516 _augment(KeyDataStructured
, _tmp
)
518 ###--------------------------------------------------------------------------
523 return '%s(p = %s, r = %s, g = %s)' %
(_clsname(me
), me
.p
, me
.r
, me
.g
)
524 def _repr_pretty_(me
, pp
, cyclep
):
525 ind
= _pp_bgroup_tyname(pp
, me
)
529 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
530 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
531 _pp_kv(pp
, 'g', me
.g
)
532 pp
.end_group(ind
, ')')
533 _augment(FGInfo
, _tmp
)
536 def group(me
): return PrimeGroup(me
)
537 _augment(DHInfo
, _tmp
)
540 def group(me
): return BinGroup(me
)
541 _augment(BinDHInfo
, _tmp
)
545 return '%s(%r)' %
(_clsname(me
), me
.info
)
546 def _repr_pretty_(me
, pp
, cyclep
):
547 ind
= _pp_bgroup_tyname(pp
, me
)
548 if cyclep
: pp
.text('...')
549 else: pp
.pretty(me
.info
)
550 pp
.end_group(ind
, ')')
551 _augment(Group
, _tmp
)
558 h ^
= 2*hash(info
.r
) & 0xffffffff
559 h ^
= 5*hash(info
.g
) & 0xffffffff
561 def _get_geval(me
, x
): return MP(x
)
562 _augment(PrimeGroup
, _tmp
)
569 h ^
= 2*hash(info
.r
) & 0xffffffff
570 h ^
= 5*hash(info
.g
) & 0xffffffff
572 def _get_geval(me
, x
): return GF(x
)
573 _augment(BinGroup
, _tmp
)
576 def __hash__(me
): return 0x0ec23dab ^
hash(me
.info
)
577 def _get_geval(me
, x
): return x
.toec()
578 _augment(ECGroup
, _tmp
)
582 return '%r(%r)' %
(me
.group
, str(me
))
583 def _repr_pretty_(me
, pp
, cyclep
):
584 pp
.pretty(type(me
)._get_geval(me
))
587 ###--------------------------------------------------------------------------
588 ### RSA encoding techniques.
590 class PKCS1Crypt (object):
591 def __init__(me
, ep
= '', rng
= rand
):
594 def encode(me
, msg
, nbits
):
595 return _base
._p1crypt_encode(msg
, nbits
, me
.ep
, me
.rng
)
596 def decode(me
, ct
, nbits
):
597 return _base
._p1crypt_decode(ct
, nbits
, me
.ep
, me
.rng
)
599 class PKCS1Sig (object):
600 def __init__(me
, ep
= '', rng
= rand
):
603 def encode(me
, msg
, nbits
):
604 return _base
._p1sig_encode(msg
, nbits
, me
.ep
, me
.rng
)
605 def decode(me
, msg
, sig
, nbits
):
606 return _base
._p1sig_decode(msg
, sig
, nbits
, me
.ep
, me
.rng
)
609 def __init__(me
, mgf
= sha_mgf
, hash = sha
, ep
= '', rng
= rand
):
614 def encode(me
, msg
, nbits
):
615 return _base
._oaep_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
616 def decode(me
, ct
, nbits
):
617 return _base
._oaep_decode(ct
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
620 def __init__(me
, mgf
= sha_mgf
, hash = sha
, saltsz
= None, rng
= rand
):
627 def encode(me
, msg
, nbits
):
628 return _base
._pss_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
629 def decode(me
, msg
, sig
, nbits
):
630 return _base
._pss_decode(msg
, sig
, nbits
,
631 me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
634 def encrypt(me
, msg
, enc
):
635 return me
.pubop(enc
.encode(msg
, me
.n
.nbits
))
636 def verify(me
, msg
, sig
, enc
):
637 if msg
is None: return enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
639 x
= enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
640 return x
is None or x
== msg
643 _augment(RSAPub
, _tmp
)
646 def decrypt(me
, ct
, enc
): return enc
.decode(me
.privop(ct
), me
.n
.nbits
)
647 def sign(me
, msg
, enc
): return me
.privop(enc
.encode(msg
, me
.n
.nbits
))
648 _augment(RSAPriv
, _tmp
)
650 ###--------------------------------------------------------------------------
651 ### Bernstein's elliptic curve crypto and related schemes.
654 bytes('0900000000000000000000000000000000000000000000000000000000000000')
657 bytes('05000000000000000000000000000000000000000000000000000000'
658 '00000000000000000000000000000000000000000000000000000000')
660 Z128
= bytes('00000000000000000000000000000000')
662 class _BoxyPub (object):
663 def __init__(me
, pub
, *kw
, **kwargs
):
664 if len(pub
) != me
._PUBSZ
: raise ValueError, 'bad public key'
665 super(_BoxyPub
, me
).__init__(*kw
, **kwargs
)
668 class _BoxyPriv (_BoxyPub
):
669 def __init__(me
, priv
, pub
= None, *kw
, **kwargs
):
670 if len(priv
) != me
._KEYSZ
: raise ValueError, 'bad private key'
671 if pub
is None: pub
= me
._op(priv
, me
._BASE
)
672 super(_BoxyPriv
, me
).__init__(pub
= pub
, *kw
, **kwargs
)
674 def agree(me
, you
): return me
._op(me
.priv
, you
.pub
)
675 def boxkey(me
, recip
):
676 return me
._hashkey(me
.agree(recip
))
677 def box(me
, recip
, n
, m
):
678 return secret_box(me
.boxkey(recip
), n
, m
)
679 def unbox(me
, recip
, n
, c
):
680 return secret_unbox(me
.boxkey(recip
, n
, c
))
682 class X25519Pub (_BoxyPub
):
683 _PUBSZ
= X25519_PUBSZ
686 class X25519Priv (_BoxyPriv
, X25519Pub
):
687 _KEYSZ
= X25519_KEYSZ
688 def _op(me
, k
, X
): return x25519(k
, X
)
689 def _hashkey(me
, z
): return hsalsa20_prf(z
, Z128
)
691 class X448Pub (_BoxyPub
):
695 class X448Priv (_BoxyPriv
, X448Pub
):
697 def _op(me
, k
, X
): return x448(k
, X
)
698 ##def _hashkey(me, z): return ???
700 class Ed25519Pub (object):
701 def __init__(me
, pub
):
703 def verify(me
, msg
, sig
):
704 return ed25519_verify(me
.pub
, msg
, sig
)
706 class Ed25519Priv (Ed25519Pub
):
707 def __init__(me
, priv
):
709 Ed25519Pub
.__init__(me
, ed25519_pubkey(priv
))
711 return ed25519_sign(me
.priv
, msg
, pub
= me
.pub
)
713 def generate(cls
, rng
= rand
):
714 return cls(rng
.block(ED25519_KEYSZ
))
716 ###--------------------------------------------------------------------------
717 ### Built-in named curves and prime groups.
719 class _groupmap (object):
720 def __init__(me
, map, nth
):
723 me
._n
= max(map.values()) + 1
726 return '{%s}' %
', '.join(['%r: %r' % kv
for kv
in me
.iteritems()])
727 def _repr_pretty_(me
, pp
, cyclep
):
728 ind
= _pp_bgroup(pp
, '{ ')
729 if cyclep
: pp
.text('...')
730 else: _pp_dict(pp
, me
.iteritems())
731 pp
.end_group(ind
, ' }')
734 def __contains__(me
, k
):
736 def __getitem__(me
, k
):
741 def __setitem__(me
, k
, v
):
742 raise TypeError, "immutable object"
754 return [k
for k
in me
]
756 return [me
[k
] for k
in me
]
758 return [(k
, me
[k
]) for k
in me
]
759 eccurves
= _groupmap(_base
._eccurves
, ECInfo
._curven
)
760 primegroups
= _groupmap(_base
._pgroups
, DHInfo
._groupn
)
761 bingroups
= _groupmap(_base
._bingroups
, BinDHInfo
._groupn
)
763 ###--------------------------------------------------------------------------
764 ### Prime number generation.
766 class PrimeGenEventHandler (object):
767 def pg_begin(me
, ev
):
771 def pg_abort(me
, ev
):
778 class SophieGermainStepJump (object):
779 def pg_begin(me
, ev
):
780 me
.lf
= PrimeFilter(ev
.x
)
781 me
.hf
= me
.lf
.muladd(2, 1)
787 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
789 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
792 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
799 class SophieGermainStepper (SophieGermainStepJump
):
800 def __init__(me
, step
):
807 class SophieGermainJumper (SophieGermainStepJump
):
808 def __init__(me
, jump
):
809 me
.ljump
= PrimeFilter(jump
);
810 me
.hjump
= me
.ljump
.muladd(2, 0)
817 SophieGermainStepJump
.pg_done(me
, ev
)
819 class SophieGermainTester (object):
822 def pg_begin(me
, ev
):
823 me
.lr
= RabinMiller(ev
.x
)
824 me
.hr
= RabinMiller(2 * ev
.x
+ 1)
826 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
827 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
829 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
830 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
832 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
839 class PrimitiveStepper (PrimeGenEventHandler
):
845 def pg_begin(me
, ev
):
846 me
.i
= iter(smallprimes
)
849 class PrimitiveTester (PrimeGenEventHandler
):
850 def __init__(me
, mod
, hh
= [], exp
= None):
856 if me
.exp
is not None:
857 x
= me
.mod
.exp(x
, me
.exp
)
858 if x
== 1: return PGEN_FAIL
860 if me
.mod
.exp(x
, h
) == 1: return PGEN_FAIL
864 class SimulStepper (PrimeGenEventHandler
):
865 def __init__(me
, mul
= 2, add
= 1, step
= 2):
869 def _stepfn(me
, step
):
871 raise ValueError, 'step must be positive'
873 return lambda f
: f
.step(step
)
874 j
= PrimeFilter(step
)
875 return lambda f
: f
.jump(j
)
876 def pg_begin(me
, ev
):
878 me
.lf
= PrimeFilter(x
)
879 me
.hf
= PrimeFilter(x
* me
.mul
+ me
.add
)
880 me
.lstep
= me
._stepfn(me
.step
)
881 me
.hstep
= me
._stepfn(me
.step
* me
.mul
)
882 SimulStepper
._cont(me
, ev
)
890 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
892 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
895 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
904 class SimulTester (PrimeGenEventHandler
):
905 def __init__(me
, mul
= 2, add
= 1):
908 def pg_begin(me
, ev
):
910 me
.lr
= RabinMiller(x
)
911 me
.hr
= RabinMiller(x
* me
.mul
+ me
.add
)
913 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
914 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
916 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
917 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
919 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
926 def sgprime(start
, step
= 2, name
= 'p', event
= pgen_nullev
, nsteps
= 0):
928 return pgen(start
, name
, SimulStepper(step
= step
), SimulTester(), event
,
929 nsteps
, RabinMiller
.iters(start
.nbits
))
931 def findprimitive(mod
, hh
= [], exp
= None, name
= 'g', event
= pgen_nullev
):
932 return pgen(0, name
, PrimitiveStepper(), PrimitiveTester(mod
, hh
, exp
),
935 def kcdsaprime(pbits
, qbits
, rng
= rand
,
936 event
= pgen_nullev
, name
= 'p', nsteps
= 0):
937 hbits
= pbits
- qbits
938 h
= pgen(rng
.mp(hbits
, 1), name
+ ' [h]',
939 PrimeGenStepper(2), PrimeGenTester(),
940 event
, nsteps
, RabinMiller
.iters(hbits
))
941 q
= pgen(rng
.mp(qbits
, 1), name
, SimulStepper(2 * h
, 1, 2),
942 SimulTester(2 * h
, 1), event
, nsteps
, RabinMiller
.iters(qbits
))
946 #----- That's all, folks ----------------------------------------------------