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 _pp_str(me
, pp
, cyclep
): pp
.text(cyclep
and '...' or str(me
))
87 def _pp_bgroup(pp
, text
):
89 pp
.begin_group(ind
, text
)
91 def _pp_bgroup_tyname(pp
, obj
, open = '('):
92 return _pp_bgroup(pp
, type(obj
).__name__
+ open)
94 ind
= _pp_bgroup(pp
, k
+ ' = ')
97 def _pp_commas(pp
, printfn
, items
):
100 if firstp
: firstp
= False
101 else: pp
.text(','); pp
.breakable()
103 def _pp_dict(pp
, items
):
113 _pp_commas(pp
, p
, items
)
115 ###--------------------------------------------------------------------------
120 return ByteString(_unhexify(x
))
121 fromhex
= staticmethod(fromhex
)
125 return 'bytes(%r)' %
hex(me
)
126 _augment(ByteString
, _tmp
)
127 ByteString
.__hash__
= str.__hash__
128 bytes
= ByteString
.fromhex
130 ###--------------------------------------------------------------------------
136 return ctstreq(h
, hh
)
137 _augment(GHash
, _tmp
)
138 _augment(Poly1305Hash
, _tmp
)
140 ###--------------------------------------------------------------------------
141 ### NaCl `secretbox'.
143 def secret_box(k
, n
, m
):
144 E
= xsalsa20(k
).setiv(n
)
145 r
= E
.enczero(poly1305
.keysz
.default
)
146 s
= E
.enczero(poly1305
.masksz
)
148 t
= poly1305(r
)(s
).hash(y
).done()
149 return ByteString(t
+ y
)
151 def secret_unbox(k
, n
, c
):
152 E
= xsalsa20(k
).setiv(n
)
153 r
= E
.enczero(poly1305
.keysz
.default
)
154 s
= E
.enczero(poly1305
.masksz
)
155 y
= c
[poly1305
.tagsz
:]
156 if not poly1305(r
)(s
).hash(y
).check(c
[0:poly1305
.tagsz
]):
157 raise ValueError, 'decryption failed'
158 return E
.decrypt(c
[poly1305
.tagsz
:])
160 ###--------------------------------------------------------------------------
161 ### Multiprecision integers and binary polynomials.
164 if isinstance(x
, BaseRat
): return x
._n
, x
._d
166 class BaseRat (object):
167 """Base class implementing fields of fractions over Euclidean domains."""
168 def __new__(cls
, a
, b
):
169 a
, b
= cls
.RING(a
), cls
.RING(b
)
173 me
= super(BaseRat
, cls
).__new__(cls
)
178 def numer(me
): return me
._n
180 def denom(me
): return me
._d
181 def __str__(me
): return '%s/%s' %
(me
._n
, me
._d
)
182 def __repr__(me
): return '%s(%s, %s)' %
(type(me
).__name__
, me
._n
, me
._d
)
183 _repr_pretty_
= _pp_str
185 def __add__(me
, you
):
186 n
, d
= _split_rat(you
)
187 return type(me
)(me
._n
*d
+ n
*me
._d
, d
*me
._d
)
189 def __sub__(me
, you
):
190 n
, d
= _split_rat(you
)
191 return type(me
)(me
._n
*d
- n
*me
._d
, d
*me
._d
)
192 def __rsub__(me
, you
):
193 n
, d
= _split_rat(you
)
194 return type(me
)(n
*me
._d
- me
._n
*d
, d
*me
._d
)
195 def __mul__(me
, you
):
196 n
, d
= _split_rat(you
)
197 return type(me
)(me
._n
*n
, me
._d
*d
)
198 def __div__(me
, you
):
199 n
, d
= _split_rat(you
)
200 return type(me
)(me
._n
*d
, me
._d
*n
)
201 def __rdiv__(me
, you
):
202 n
, d
= _split_rat(you
)
203 return type(me
)(me
._d
*n
, me
._n
*d
)
204 def __cmp__(me
, you
):
205 n
, d
= _split_rat(you
)
206 return type(me
)(me
._n
*d
, n
*me
._d
)
207 def __rcmp__(me
, you
):
208 n
, d
= _split_rat(you
)
209 return cmp(n
*me
._d
, me
._n
*d
)
211 class IntRat (BaseRat
):
214 class GFRat (BaseRat
):
218 def negp(x
): return x
< 0
219 def posp(x
): return x
> 0
220 def zerop(x
): return x
== 0
221 def oddp(x
): return x
.testbit(0)
222 def evenp(x
): return not x
.testbit(0)
223 def mont(x
): return MPMont(x
)
224 def barrett(x
): return MPBarrett(x
)
225 def reduce(x
): return MPReduce(x
)
226 def __div__(me
, you
): return IntRat(me
, you
)
227 def __rdiv__(me
, you
): return IntRat(you
, me
)
228 _repr_pretty_
= _pp_str
232 def zerop(x
): return x
== 0
233 def reduce(x
): return GFReduce(x
)
234 def trace(x
, y
): return x
.reduce().trace(y
)
235 def halftrace(x
, y
): return x
.reduce().halftrace(y
)
236 def modsqrt(x
, y
): return x
.reduce().sqrt(y
)
237 def quadsolve(x
, y
): return x
.reduce().quadsolve(y
)
238 def __div__(me
, you
): return GFRat(me
, you
)
239 def __rdiv__(me
, you
): return GFRat(you
, me
)
240 _repr_pretty_
= _pp_str
245 'product(ITERABLE) or product(I, ...) -> PRODUCT'
246 return MPMul(*arg
).done()
247 product
= staticmethod(product
)
248 _augment(MPMul
, _tmp
)
250 ###--------------------------------------------------------------------------
254 def fromstring(str): return _checkend(Field
.parse(str))
255 fromstring
= staticmethod(fromstring
)
256 _augment(Field
, _tmp
)
259 def __repr__(me
): return '%s(%sL)' %
(type(me
).__name__
, me
.p
)
260 def __hash__(me
): return 0x114401de ^
hash(me
.p
)
261 def _repr_pretty_(me
, pp
, cyclep
):
262 ind
= _pp_bgroup_tyname(pp
, me
)
263 if cyclep
: pp
.text('...')
264 else: pp
.pretty(me
.p
)
265 pp
.end_group(ind
, ')')
266 def ec(me
, a
, b
): return ECPrimeProjCurve(me
, a
, b
)
267 _augment(PrimeField
, _tmp
)
270 def __repr__(me
): return '%s(%#xL)' %
(type(me
).__name__
, me
.p
)
271 def ec(me
, a
, b
): return ECBinProjCurve(me
, a
, b
)
272 def _repr_pretty_(me
, pp
, cyclep
):
273 ind
= _pp_bgroup_tyname(pp
, me
)
274 if cyclep
: pp
.text('...')
275 else: pp
.text('%#x' % me
.p
)
276 pp
.end_group(ind
, ')')
277 _augment(BinField
, _tmp
)
280 def __hash__(me
): return 0x23e4701c ^
hash(me
.p
)
281 _augment(BinPolyField
, _tmp
)
287 h ^
= 2*hash(me
.beta
) & 0xffffffff
289 _augment(BinNormField
, _tmp
)
292 def __str__(me
): return str(me
.value
)
293 def __repr__(me
): return '%s(%s)' %
(repr(me
.field
), repr(me
.value
))
294 _repr_pretty_
= _pp_str
297 ###--------------------------------------------------------------------------
302 return '%s(%r, %s, %s)' %
(type(me
).__name__
, me
.field
, me
.a
, me
.b
)
303 def _repr_pretty_(me
, pp
, cyclep
):
304 ind
= _pp_bgroup_tyname(pp
, me
)
308 pp
.pretty(me
.field
); pp
.text(','); pp
.breakable()
309 pp
.pretty(me
.a
); pp
.text(','); pp
.breakable()
311 pp
.end_group(ind
, ')')
313 return ecpt
.frombuf(me
, s
)
315 return ecpt
.fromraw(me
, s
)
318 _augment(ECCurve
, _tmp
)
324 h ^
= 2*hash(me
.a
) ^
0xffffffff
325 h ^
= 5*hash(me
.b
) ^
0xffffffff
327 _augment(ECPrimeCurve
, _tmp
)
333 h ^
= 2*hash(me
.a
) ^
0xffffffff
334 h ^
= 5*hash(me
.b
) ^
0xffffffff
336 _augment(ECBinCurve
, _tmp
)
340 if not me
: return 'ECPt()'
341 return 'ECPt(%s, %s)' %
(me
.ix
, me
.iy
)
343 if not me
: return 'inf'
344 return '(%s, %s)' %
(me
.ix
, me
.iy
)
345 def _repr_pretty_(me
, pp
, cyclep
):
351 ind
= _pp_bgroup(pp
, '(')
352 pp
.pretty(me
.ix
); pp
.text(','); pp
.breakable()
354 pp
.end_group(ind
, ')')
359 return 'ECInfo(curve = %r, G = %r, r = %s, h = %s)' % \
360 (me
.curve
, me
.G
, me
.r
, me
.h
)
361 def _repr_pretty_(me
, pp
, cyclep
):
362 ind
= _pp_bgroup_tyname(pp
, me
)
366 _pp_kv(pp
, 'curve', me
.curve
); pp
.text(','); pp
.breakable()
367 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
368 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
369 _pp_kv(pp
, 'h', me
.h
)
370 pp
.end_group(ind
, ')')
374 h ^
= 2*hash(me
.G
) & 0xffffffff
378 _augment(ECInfo
, _tmp
)
382 if not me
: return '%r()' %
(me
.curve
)
383 return '%r(%s, %s)' %
(me
.curve
, me
.x
, me
.y
)
385 if not me
: return 'inf'
386 return '(%s, %s)' %
(me
.x
, me
.y
)
387 _augment(ECPtCurve
, _tmp
)
389 ###--------------------------------------------------------------------------
393 def __repr__(me
): return 'KeySZAny(%d)' % me
.default
394 def check(me
, sz
): return True
395 def best(me
, sz
): return sz
396 _augment(KeySZAny
, _tmp
)
400 return 'KeySZRange(%d, %d, %d, %d)' % \
401 (me
.default
, me
.min, me
.max, me
.mod
)
402 def _repr_pretty_(me
, pp
, cyclep
):
403 ind
= _pp_bgroup_tyname(pp
, me
)
407 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
408 pp
.pretty(me
.min); pp
.text(','); pp
.breakable()
409 pp
.pretty(me
.max); pp
.text(','); pp
.breakable()
411 pp
.end_group(ind
, ')')
412 def check(me
, sz
): return me
.min <= sz
<= me
.max and sz % me
.mod
== 0
414 if sz
< me
.min: raise ValueError, 'key too small'
415 elif sz
> me
.max: return me
.max
416 else: return sz
- (sz % me
.mod
)
417 _augment(KeySZRange
, _tmp
)
420 def __repr__(me
): return 'KeySZSet(%d, %s)' %
(me
.default
, me
.set)
421 def _repr_pretty_(me
, pp
, cyclep
):
422 ind
= _pp_bgroup_tyname(pp
, me
)
426 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
427 ind1
= _pp_bgroup(pp
, '{')
428 _pp_commas(pp
, pp
.pretty
, me
.set)
429 pp
.end_group(ind1
, '}')
430 pp
.end_group(ind
, ')')
431 def check(me
, sz
): return sz
in me
.set
435 if found
< i
<= sz
: found
= i
436 if found
< 0: raise ValueError, 'key too small'
438 _augment(KeySZSet
, _tmp
)
440 ###--------------------------------------------------------------------------
441 ### Key data objects.
444 def __repr__(me
): return 'KeyFile(%r)' % me
.name
445 _augment(KeyFile
, _tmp
)
448 def __repr__(me
): return 'Key(%r)' % me
.fulltag
453 return 'KeyAttributes({%s})' % \
454 ', '.join(['%r: %r' % kv
for kv
in me
.iteritems()])
455 def _repr_pretty_(me
, pp
, cyclep
):
456 ind
= _pp_bgroup_tyname(pp
, me
)
457 if cyclep
: pp
.text('...')
458 else: _pp_dict(pp
, me
.iteritems())
459 pp
.end_group(ind
, ')')
460 _augment(KeyAttributes
, _tmp
)
463 def __repr__(me
): return 'KeyDataBinary(%r, %r)' % \
464 (me
.bin
, me
.writeflags(me
.flags
))
465 def _repr_pretty_(me
, pp
, cyclep
):
466 ind
= _pp_bgroup_tyname(pp
, me
)
470 pp
.pretty(me
.bin
); pp
.text(','); pp
.breakable()
471 pp
.pretty(me
.writeflags(me
.flags
))
472 pp
.end_group(ind
, ')')
473 _augment(KeyDataBinary
, _tmp
)
476 def __repr__(me
): return 'KeyDataEncrypted(%r, %r)' % \
477 (me
.ct
, me
.writeflags(me
.flags
))
478 def _repr_pretty_(me
, pp
, cyclep
):
479 ind
= _pp_bgroup_tyname(pp
, me
)
483 pp
.pretty(me
.ct
); pp
.text(','); pp
.breakable()
484 pp
.pretty(me
.writeflags(me
.flags
))
485 pp
.end_group(ind
, ')')
486 _augment(KeyDataEncrypted
, _tmp
)
489 def __repr__(me
): return 'KeyDataMP(%r, %r)' % \
490 (me
.mp
, me
.writeflags(me
.flags
))
491 def _repr_pretty_(me
, pp
, cyclep
):
492 ind
= _pp_bgroup_tyname(pp
, me
)
496 pp
.pretty(me
.mp
); pp
.text(','); pp
.breakable()
497 pp
.pretty(me
.writeflags(me
.flags
))
498 pp
.end_group(ind
, ')')
499 _augment(KeyDataMP
, _tmp
)
502 def __repr__(me
): return 'KeyDataString(%r)' % \
503 (me
.str, me
.writeflags(me
.flags
))
504 def _repr_pretty_(me
, pp
, cyclep
):
505 ind
= _pp_bgroup_tyname(pp
, me
)
509 pp
.pretty(me
.str); pp
.text(','); pp
.breakable()
510 pp
.pretty(me
.writeflags(me
.flags
))
511 pp
.end_group(ind
, ')')
512 _augment(KeyDataString
, _tmp
)
515 def __repr__(me
): return 'KeyDataECPt(%r)' % \
516 (me
.ecpt
, me
.writeflags(me
.flags
))
517 def _repr_pretty_(me
, pp
, cyclep
):
518 ind
= _pp_bgroup_tyname(pp
, me
)
522 pp
.pretty(me
.ecpt
); pp
.text(','); pp
.breakable()
523 pp
.pretty(me
.writeflags(me
.flags
))
524 pp
.end_group(ind
, ')')
525 _augment(KeyDataECPt
, _tmp
)
529 return 'KeyDataStructured({%s})' % \
530 ', '.join(['%r: %r' % kv
for kv
in me
.iteritems()])
531 def _repr_pretty_(me
, pp
, cyclep
):
532 ind
= _pp_bgroup_tyname(pp
, me
, '({ ')
533 if cyclep
: pp
.text('...')
534 else: _pp_dict(pp
, me
.iteritems())
535 pp
.end_group(ind
, ' })')
536 _augment(KeyDataStructured
, _tmp
)
538 ###--------------------------------------------------------------------------
543 return '%s(p = %s, r = %s, g = %s)' % \
544 (type(me
).__name__
, me
.p
, me
.r
, me
.g
)
545 def _repr_pretty_(me
, pp
, cyclep
):
546 ind
= _pp_bgroup_tyname(pp
, me
)
550 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
551 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
552 _pp_kv(pp
, 'g', me
.g
)
553 pp
.end_group(ind
, ')')
554 _augment(FGInfo
, _tmp
)
557 def group(me
): return PrimeGroup(me
)
558 _augment(DHInfo
, _tmp
)
561 def group(me
): return BinGroup(me
)
562 _augment(BinDHInfo
, _tmp
)
566 return '%s(%r)' %
(type(me
).__name__
, me
.info
)
567 _augment(Group
, _tmp
)
574 h ^
= 2*hash(info
.r
) & 0xffffffff
575 h ^
= 5*hash(info
.g
) & 0xffffffff
577 _augment(PrimeGroup
, _tmp
)
584 h ^
= 2*hash(info
.r
) & 0xffffffff
585 h ^
= 5*hash(info
.g
) & 0xffffffff
587 _augment(BinGroup
, _tmp
)
590 def __hash__(me
): return 0x0ec23dab ^
hash(me
.info
)
591 _augment(ECGroup
, _tmp
)
595 return '%r(%r)' %
(me
.group
, str(me
))
596 _repr_pretty_
= _pp_str
599 ###--------------------------------------------------------------------------
600 ### RSA encoding techniques.
602 class PKCS1Crypt (object):
603 def __init__(me
, ep
= '', rng
= rand
):
606 def encode(me
, msg
, nbits
):
607 return _base
._p1crypt_encode(msg
, nbits
, me
.ep
, me
.rng
)
608 def decode(me
, ct
, nbits
):
609 return _base
._p1crypt_decode(ct
, nbits
, me
.ep
, me
.rng
)
611 class PKCS1Sig (object):
612 def __init__(me
, ep
= '', rng
= rand
):
615 def encode(me
, msg
, nbits
):
616 return _base
._p1sig_encode(msg
, nbits
, me
.ep
, me
.rng
)
617 def decode(me
, msg
, sig
, nbits
):
618 return _base
._p1sig_decode(msg
, sig
, nbits
, me
.ep
, me
.rng
)
621 def __init__(me
, mgf
= sha_mgf
, hash = sha
, ep
= '', rng
= rand
):
626 def encode(me
, msg
, nbits
):
627 return _base
._oaep_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
628 def decode(me
, ct
, nbits
):
629 return _base
._oaep_decode(ct
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
632 def __init__(me
, mgf
= sha_mgf
, hash = sha
, saltsz
= None, rng
= rand
):
639 def encode(me
, msg
, nbits
):
640 return _base
._pss_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
641 def decode(me
, msg
, sig
, nbits
):
642 return _base
._pss_decode(msg
, sig
, nbits
,
643 me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
646 def encrypt(me
, msg
, enc
):
647 return me
.pubop(enc
.encode(msg
, me
.n
.nbits
))
648 def verify(me
, msg
, sig
, enc
):
649 if msg
is None: return enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
651 x
= enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
652 return x
is None or x
== msg
655 _augment(RSAPub
, _tmp
)
658 def decrypt(me
, ct
, enc
): return enc
.decode(me
.privop(ct
), me
.n
.nbits
)
659 def sign(me
, msg
, enc
): return me
.privop(enc
.encode(msg
, me
.n
.nbits
))
660 _augment(RSAPriv
, _tmp
)
662 ###--------------------------------------------------------------------------
663 ### Bernstein's elliptic curve crypto and related schemes.
666 bytes('0900000000000000000000000000000000000000000000000000000000000000')
669 bytes('05000000000000000000000000000000000000000000000000000000'
670 '00000000000000000000000000000000000000000000000000000000')
672 Z128
= bytes('00000000000000000000000000000000')
674 class _BoxyPub (object):
675 def __init__(me
, pub
, *kw
, **kwargs
):
676 if len(pub
) != me
._PUBSZ
: raise ValueError, 'bad public key'
677 super(_BoxyPub
, me
).__init__(*kw
, **kwargs
)
680 class _BoxyPriv (_BoxyPub
):
681 def __init__(me
, priv
, pub
= None, *kw
, **kwargs
):
682 if len(priv
) != me
._KEYSZ
: raise ValueError, 'bad private key'
683 if pub
is None: pub
= me
._op(priv
, me
._BASE
)
684 super(_BoxyPriv
, me
).__init__(pub
= pub
, *kw
, **kwargs
)
686 def agree(me
, you
): return me
._op(me
.priv
, you
.pub
)
687 def boxkey(me
, recip
):
688 return me
._hashkey(me
.agree(recip
))
689 def box(me
, recip
, n
, m
):
690 return secret_box(me
.boxkey(recip
), n
, m
)
691 def unbox(me
, recip
, n
, c
):
692 return secret_unbox(me
.boxkey(recip
, n
, c
))
694 class X25519Pub (_BoxyPub
):
695 _PUBSZ
= X25519_PUBSZ
698 class X25519Priv (_BoxyPriv
, X25519Pub
):
699 _KEYSZ
= X25519_KEYSZ
700 def _op(me
, k
, X
): return x25519(k
, X
)
701 def _hashkey(me
, z
): return hsalsa20_prf(z
, Z128
)
703 class X448Pub (_BoxyPub
):
707 class X448Priv (_BoxyPriv
, X448Pub
):
709 def _op(me
, k
, X
): return x448(k
, X
)
710 ##def _hashkey(me, z): return ???
712 class Ed25519Pub (object):
713 def __init__(me
, pub
):
715 def verify(me
, msg
, sig
):
716 return ed25519_verify(me
.pub
, msg
, sig
)
718 class Ed25519Priv (Ed25519Pub
):
719 def __init__(me
, priv
):
721 Ed25519Pub
.__init__(me
, ed25519_pubkey(priv
))
723 return ed25519_sign(me
.priv
, msg
, pub
= me
.pub
)
725 def generate(cls
, rng
= rand
):
726 return cls(rng
.block(ED25519_KEYSZ
))
728 ###--------------------------------------------------------------------------
729 ### Built-in named curves and prime groups.
731 class _groupmap (object):
732 def __init__(me
, map, nth
):
735 me
._n
= max(map.values()) + 1
738 return '{%s}' %
', '.join(['%r: %r' % kv
for kv
in me
.iteritems()])
739 def _repr_pretty_(me
, pp
, cyclep
):
740 ind
= _pp_bgroup(pp
, '{ ')
741 if cyclep
: pp
.text('...')
742 else: _pp_dict(pp
, me
.iteritems())
743 pp
.end_group(ind
, ' }')
746 def __contains__(me
, k
):
748 def __getitem__(me
, k
):
753 def __setitem__(me
, k
, v
):
754 raise TypeError, "immutable object"
766 return [k
for k
in me
]
768 return [me
[k
] for k
in me
]
770 return [(k
, me
[k
]) for k
in me
]
771 eccurves
= _groupmap(_base
._eccurves
, ECInfo
._curven
)
772 primegroups
= _groupmap(_base
._pgroups
, DHInfo
._groupn
)
773 bingroups
= _groupmap(_base
._bingroups
, BinDHInfo
._groupn
)
775 ###--------------------------------------------------------------------------
776 ### Prime number generation.
778 class PrimeGenEventHandler (object):
779 def pg_begin(me
, ev
):
783 def pg_abort(me
, ev
):
790 class SophieGermainStepJump (object):
791 def pg_begin(me
, ev
):
792 me
.lf
= PrimeFilter(ev
.x
)
793 me
.hf
= me
.lf
.muladd(2, 1)
799 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
801 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
804 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
811 class SophieGermainStepper (SophieGermainStepJump
):
812 def __init__(me
, step
):
819 class SophieGermainJumper (SophieGermainStepJump
):
820 def __init__(me
, jump
):
821 me
.ljump
= PrimeFilter(jump
);
822 me
.hjump
= me
.ljump
.muladd(2, 0)
829 SophieGermainStepJump
.pg_done(me
, ev
)
831 class SophieGermainTester (object):
834 def pg_begin(me
, ev
):
835 me
.lr
= RabinMiller(ev
.x
)
836 me
.hr
= RabinMiller(2 * ev
.x
+ 1)
838 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
839 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
841 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
842 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
844 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
851 class PrimitiveStepper (PrimeGenEventHandler
):
857 def pg_begin(me
, ev
):
858 me
.i
= iter(smallprimes
)
861 class PrimitiveTester (PrimeGenEventHandler
):
862 def __init__(me
, mod
, hh
= [], exp
= None):
868 if me
.exp
is not None:
869 x
= me
.mod
.exp(x
, me
.exp
)
870 if x
== 1: return PGEN_FAIL
872 if me
.mod
.exp(x
, h
) == 1: return PGEN_FAIL
876 class SimulStepper (PrimeGenEventHandler
):
877 def __init__(me
, mul
= 2, add
= 1, step
= 2):
881 def _stepfn(me
, step
):
883 raise ValueError, 'step must be positive'
885 return lambda f
: f
.step(step
)
886 j
= PrimeFilter(step
)
887 return lambda f
: f
.jump(j
)
888 def pg_begin(me
, ev
):
890 me
.lf
= PrimeFilter(x
)
891 me
.hf
= PrimeFilter(x
* me
.mul
+ me
.add
)
892 me
.lstep
= me
._stepfn(me
.step
)
893 me
.hstep
= me
._stepfn(me
.step
* me
.mul
)
894 SimulStepper
._cont(me
, ev
)
902 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
904 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
907 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
916 class SimulTester (PrimeGenEventHandler
):
917 def __init__(me
, mul
= 2, add
= 1):
920 def pg_begin(me
, ev
):
922 me
.lr
= RabinMiller(x
)
923 me
.hr
= RabinMiller(x
* me
.mul
+ me
.add
)
925 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
926 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
928 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
929 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
931 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
938 def sgprime(start
, step
= 2, name
= 'p', event
= pgen_nullev
, nsteps
= 0):
940 return pgen(start
, name
, SimulStepper(step
= step
), SimulTester(), event
,
941 nsteps
, RabinMiller
.iters(start
.nbits
))
943 def findprimitive(mod
, hh
= [], exp
= None, name
= 'g', event
= pgen_nullev
):
944 return pgen(0, name
, PrimitiveStepper(), PrimitiveTester(mod
, hh
, exp
),
947 def kcdsaprime(pbits
, qbits
, rng
= rand
,
948 event
= pgen_nullev
, name
= 'p', nsteps
= 0):
949 hbits
= pbits
- qbits
950 h
= pgen(rng
.mp(hbits
, 1), name
+ ' [h]',
951 PrimeGenStepper(2), PrimeGenTester(),
952 event
, nsteps
, RabinMiller
.iters(hbits
))
953 q
= pgen(rng
.mp(qbits
, 1), name
, SimulStepper(2 * h
, 1, 2),
954 SimulTester(2 * h
, 1), event
, nsteps
, RabinMiller
.iters(qbits
))
958 #----- That's all, folks ----------------------------------------------------