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
))
89 pp
.begin_group(ind
, k
+ ' = ')
92 def _pp_commas(pp
, printfn
, items
):
95 if firstp
: firstp
= False
96 else: pp
.text(','); pp
.breakable()
98 def _pp_dict(pp
, items
):
100 pp
.begin_group(0, '')
103 pp
.begin_group(2, '')
108 _pp_commas(pp
, p
, items
)
110 ###--------------------------------------------------------------------------
115 return ByteString(_unhexify(x
))
116 fromhex
= staticmethod(fromhex
)
120 return 'bytes(%r)' %
hex(me
)
121 _augment(ByteString
, _tmp
)
122 ByteString
.__hash__
= str.__hash__
123 bytes
= ByteString
.fromhex
125 ###--------------------------------------------------------------------------
131 return ctstreq(h
, hh
)
132 _augment(GHash
, _tmp
)
133 _augment(Poly1305Hash
, _tmp
)
135 ###--------------------------------------------------------------------------
136 ### NaCl `secretbox'.
138 def secret_box(k
, n
, m
):
139 E
= xsalsa20(k
).setiv(n
)
140 r
= E
.enczero(poly1305
.keysz
.default
)
141 s
= E
.enczero(poly1305
.masksz
)
143 t
= poly1305(r
)(s
).hash(y
).done()
144 return ByteString(t
+ y
)
146 def secret_unbox(k
, n
, c
):
147 E
= xsalsa20(k
).setiv(n
)
148 r
= E
.enczero(poly1305
.keysz
.default
)
149 s
= E
.enczero(poly1305
.masksz
)
150 y
= c
[poly1305
.tagsz
:]
151 if not poly1305(r
)(s
).hash(y
).check(c
[0:poly1305
.tagsz
]):
152 raise ValueError, 'decryption failed'
153 return E
.decrypt(c
[poly1305
.tagsz
:])
155 ###--------------------------------------------------------------------------
156 ### Multiprecision integers and binary polynomials.
159 if isinstance(x
, BaseRat
): return x
._n
, x
._d
161 class BaseRat (object):
162 """Base class implementing fields of fractions over Euclidean domains."""
163 def __new__(cls
, a
, b
):
164 a
, b
= cls
.RING(a
), cls
.RING(b
)
168 me
= super(BaseRat
, cls
).__new__(cls
)
173 def numer(me
): return me
._n
175 def denom(me
): return me
._d
176 def __str__(me
): return '%s/%s' %
(me
._n
, me
._d
)
177 def __repr__(me
): return '%s(%s, %s)' %
(type(me
).__name__
, me
._n
, me
._d
)
178 _repr_pretty_
= _pp_str
180 def __add__(me
, you
):
181 n
, d
= _split_rat(you
)
182 return type(me
)(me
._n
*d
+ n
*me
._d
, d
*me
._d
)
184 def __sub__(me
, you
):
185 n
, d
= _split_rat(you
)
186 return type(me
)(me
._n
*d
- n
*me
._d
, d
*me
._d
)
187 def __rsub__(me
, you
):
188 n
, d
= _split_rat(you
)
189 return type(me
)(n
*me
._d
- me
._n
*d
, d
*me
._d
)
190 def __mul__(me
, you
):
191 n
, d
= _split_rat(you
)
192 return type(me
)(me
._n
*n
, me
._d
*d
)
193 def __div__(me
, you
):
194 n
, d
= _split_rat(you
)
195 return type(me
)(me
._n
*d
, me
._d
*n
)
196 def __rdiv__(me
, you
):
197 n
, d
= _split_rat(you
)
198 return type(me
)(me
._d
*n
, me
._n
*d
)
199 def __cmp__(me
, you
):
200 n
, d
= _split_rat(you
)
201 return type(me
)(me
._n
*d
, n
*me
._d
)
202 def __rcmp__(me
, you
):
203 n
, d
= _split_rat(you
)
204 return cmp(n
*me
._d
, me
._n
*d
)
206 class IntRat (BaseRat
):
209 class GFRat (BaseRat
):
213 def negp(x
): return x
< 0
214 def posp(x
): return x
> 0
215 def zerop(x
): return x
== 0
216 def oddp(x
): return x
.testbit(0)
217 def evenp(x
): return not x
.testbit(0)
218 def mont(x
): return MPMont(x
)
219 def barrett(x
): return MPBarrett(x
)
220 def reduce(x
): return MPReduce(x
)
221 def __div__(me
, you
): return IntRat(me
, you
)
222 def __rdiv__(me
, you
): return IntRat(you
, me
)
223 _repr_pretty_
= _pp_str
227 def zerop(x
): return x
== 0
228 def reduce(x
): return GFReduce(x
)
229 def trace(x
, y
): return x
.reduce().trace(y
)
230 def halftrace(x
, y
): return x
.reduce().halftrace(y
)
231 def modsqrt(x
, y
): return x
.reduce().sqrt(y
)
232 def quadsolve(x
, y
): return x
.reduce().quadsolve(y
)
233 def __div__(me
, you
): return GFRat(me
, you
)
234 def __rdiv__(me
, you
): return GFRat(you
, me
)
235 _repr_pretty_
= _pp_str
240 'product(ITERABLE) or product(I, ...) -> PRODUCT'
241 return MPMul(*arg
).done()
242 product
= staticmethod(product
)
243 _augment(MPMul
, _tmp
)
245 ###--------------------------------------------------------------------------
249 def fromstring(str): return _checkend(Field
.parse(str))
250 fromstring
= staticmethod(fromstring
)
251 _augment(Field
, _tmp
)
254 def __repr__(me
): return '%s(%sL)' %
(type(me
).__name__
, me
.p
)
255 def __hash__(me
): return 0x114401de ^
hash(me
.p
)
256 def _repr_pretty_(me
, pp
, cyclep
):
257 tyname
= type(me
).__name__
259 pp
.text(tyname
+ '(...)')
261 ind
= len(tyname
) + 1
262 pp
.begin_group(ind
, tyname
+ '(')
264 pp
.end_group(ind
, ')')
265 def ec(me
, a
, b
): return ECPrimeProjCurve(me
, a
, b
)
266 _augment(PrimeField
, _tmp
)
269 def __repr__(me
): return '%s(%#xL)' %
(type(me
).__name__
, me
.p
)
270 def ec(me
, a
, b
): return ECBinProjCurve(me
, a
, b
)
271 def _repr_pretty_(me
, pp
, cyclep
):
272 tyname
= type(me
).__name__
274 pp
.text(tyname
+ '(...)')
276 ind
= len(tyname
) + 1
277 pp
.begin_group(ind
, tyname
+ '(')
278 pp
.text('%#x' % me
.p
)
279 pp
.end_group(ind
, ')')
280 _augment(BinField
, _tmp
)
283 def __hash__(me
): return 0x23e4701c ^
hash(me
.p
)
284 _augment(BinPolyField
, _tmp
)
290 h ^
= 2*hash(me
.beta
) & 0xffffffff
292 _augment(BinNormField
, _tmp
)
295 def __str__(me
): return str(me
.value
)
296 def __repr__(me
): return '%s(%s)' %
(repr(me
.field
), repr(me
.value
))
297 _repr_pretty_
= _pp_str
300 ###--------------------------------------------------------------------------
305 return '%s(%r, %s, %s)' %
(type(me
).__name__
, me
.field
, me
.a
, me
.b
)
306 def _repr_pretty_(me
, pp
, cyclep
):
307 tyname
= type(me
).__name__
309 pp
.text(tyname
+ '(...)')
311 ind
= len(tyname
) + 1
312 pp
.begin_group(ind
, tyname
+ '(')
313 pp
.pretty(me
.field
); pp
.text(','); pp
.breakable()
314 pp
.pretty(me
.a
); pp
.text(','); pp
.breakable()
316 pp
.end_group(ind
, ')')
318 return ecpt
.frombuf(me
, s
)
320 return ecpt
.fromraw(me
, s
)
323 _augment(ECCurve
, _tmp
)
329 h ^
= 2*hash(me
.a
) ^
0xffffffff
330 h ^
= 5*hash(me
.b
) ^
0xffffffff
332 _augment(ECPrimeCurve
, _tmp
)
338 h ^
= 2*hash(me
.a
) ^
0xffffffff
339 h ^
= 5*hash(me
.b
) ^
0xffffffff
341 _augment(ECBinCurve
, _tmp
)
345 if not me
: return 'ECPt()'
346 return 'ECPt(%s, %s)' %
(me
.ix
, me
.iy
)
348 if not me
: return 'inf'
349 return '(%s, %s)' %
(me
.ix
, me
.iy
)
350 def _repr_pretty_(me
, pp
, cyclep
):
356 pp
.begin_group(1, '(')
357 pp
.pretty(me
.ix
); pp
.text(','); pp
.breakable()
364 return 'ECInfo(curve = %r, G = %r, r = %s, h = %s)' % \
365 (me
.curve
, me
.G
, me
.r
, me
.h
)
366 def _repr_pretty_(me
, pp
, cyclep
):
368 pp
.text('ECInfo(...)')
370 pp
.begin_group(7, 'ECInfo(')
371 _pp_kv(pp
, 'curve', me
.curve
); pp
.text(','); pp
.breakable()
372 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
373 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
374 _pp_kv(pp
, 'h', me
.h
)
379 h ^
= 2*hash(me
.G
) & 0xffffffff
383 _augment(ECInfo
, _tmp
)
387 if not me
: return '%r()' %
(me
.curve
)
388 return '%r(%s, %s)' %
(me
.curve
, me
.x
, me
.y
)
390 if not me
: return 'inf'
391 return '(%s, %s)' %
(me
.x
, me
.y
)
392 _augment(ECPtCurve
, _tmp
)
394 ###--------------------------------------------------------------------------
398 def __repr__(me
): return 'KeySZAny(%d)' % me
.default
399 def check(me
, sz
): return True
400 def best(me
, sz
): return sz
401 _augment(KeySZAny
, _tmp
)
405 return 'KeySZRange(%d, %d, %d, %d)' % \
406 (me
.default
, me
.min, me
.max, me
.mod
)
407 def _repr_pretty_(me
, pp
, cyclep
):
409 pp
.text('KeySZRange(...)')
411 pp
.begin_group(11, 'KeySZRange(')
412 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
413 pp
.pretty(me
.min); pp
.text(','); pp
.breakable()
414 pp
.pretty(me
.max); pp
.text(','); pp
.breakable()
416 pp
.end_group(11, ')')
417 def check(me
, sz
): return me
.min <= sz
<= me
.max and sz % me
.mod
== 0
419 if sz
< me
.min: raise ValueError, 'key too small'
420 elif sz
> me
.max: return me
.max
421 else: return sz
- (sz % me
.mod
)
422 _augment(KeySZRange
, _tmp
)
425 def __repr__(me
): return 'KeySZSet(%d, %s)' %
(me
.default
, me
.set)
426 def _repr_pretty_(me
, pp
, cyclep
):
428 pp
.text('KeySZSet(...)')
430 pp
.begin_group(9, 'KeySZSet(')
431 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
432 pp
.begin_group(1, '{')
433 _pp_commas(pp
, pp
.pretty
, me
.set)
436 def check(me
, sz
): return sz
in me
.set
440 if found
< i
<= sz
: found
= i
441 if found
< 0: raise ValueError, 'key too small'
443 _augment(KeySZSet
, _tmp
)
445 ###--------------------------------------------------------------------------
446 ### Key data objects.
449 def __repr__(me
): return 'KeyFile(%r)' % me
.name
450 _augment(KeyFile
, _tmp
)
453 def __repr__(me
): return 'Key(%r)' % me
.fulltag
458 return 'KeyAttributes({%s})' % \
459 ', '.join(['%r: %r' % kv
for kv
in me
.iteritems()])
460 def _repr_pretty_(me
, pp
, cyclep
):
461 pp
.begin_group(14, 'KeyAttributes(')
462 if cyclep
: pp
.text('...')
463 else: _pp_dict(pp
, me
.iteritems())
464 pp
.end_group(14, ')')
465 _augment(KeyAttributes
, _tmp
)
468 def __repr__(me
): return 'KeyDataBinary(%r, %r)' % \
469 (me
.bin
, me
.writeflags(me
.flags
))
470 def _repr_pretty_(me
, pp
, cyclep
):
471 pp
.begin_group(14, 'KeyDataBinary(')
473 pp
.text('KeyDataBinary(...)')
475 pp
.pretty(me
.bin
); pp
.text(','); pp
.breakable()
476 pp
.pretty(me
.writeflags(me
.flags
))
477 pp
.end_group(14, ')')
478 _augment(KeyDataBinary
, _tmp
)
481 def __repr__(me
): return 'KeyDataEncrypted(%r, %r)' % \
482 (me
.ct
, me
.writeflags(me
.flags
))
483 def _repr_pretty_(me
, pp
, cyclep
):
484 pp
.begin_group(17, 'KeyDataEncrypted(')
488 pp
.pretty(me
.ct
); pp
.text(','); pp
.breakable()
489 pp
.pretty(me
.writeflags(me
.flags
))
490 pp
.end_group(17, ')')
491 _augment(KeyDataEncrypted
, _tmp
)
494 def __repr__(me
): return 'KeyDataMP(%r, %r)' % \
495 (me
.mp
, me
.writeflags(me
.flags
))
496 def _repr_pretty_(me
, pp
, cyclep
):
497 pp
.begin_group(10, 'KeyDataMP(')
501 pp
.pretty(me
.mp
); pp
.text(','); pp
.breakable()
502 pp
.pretty(me
.writeflags(me
.flags
))
503 pp
.end_group(10, ')')
504 _augment(KeyDataMP
, _tmp
)
507 def __repr__(me
): return 'KeyDataString(%r)' % \
508 (me
.str, me
.writeflags(me
.flags
))
509 def _repr_pretty_(me
, pp
, cyclep
):
510 pp
.begin_group(14, 'KeyDataString(')
514 pp
.pretty(me
.str); pp
.text(','); pp
.breakable()
515 pp
.pretty(me
.writeflags(me
.flags
))
516 pp
.end_group(14, ')')
517 _augment(KeyDataString
, _tmp
)
520 def __repr__(me
): return 'KeyDataECPt(%r)' % \
521 (me
.ecpt
, me
.writeflags(me
.flags
))
522 def _repr_pretty_(me
, pp
, cyclep
):
523 pp
.begin_group(12, 'KeyDataECPt(')
527 pp
.pretty(me
.ecpt
); pp
.text(','); pp
.breakable()
528 pp
.pretty(me
.writeflags(me
.flags
))
529 pp
.end_group(12, ')')
530 _augment(KeyDataECPt
, _tmp
)
534 return 'KeyDataStructured({%s})' % \
535 ', '.join(['%r: %r' % kv
for kv
in me
.iteritems()])
536 def _repr_pretty_(me
, pp
, cyclep
):
537 pp
.begin_group(20, 'KeyDataStructured({ ')
538 if cyclep
: pp
.text('...')
539 else: _pp_dict(pp
, me
.iteritems())
540 pp
.end_group(20, ' })')
541 _augment(KeyDataStructured
, _tmp
)
543 ###--------------------------------------------------------------------------
548 return '%s(p = %s, r = %s, g = %s)' % \
549 (type(me
).__name__
, me
.p
, me
.r
, me
.g
)
550 def _repr_pretty_(me
, pp
, cyclep
):
551 tyname
= type(me
).__name__
553 pp
.text(tyname
+ '(...)')
555 ind
= len(tyname
) + 1
556 pp
.begin_group(ind
, tyname
+ '(')
557 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
558 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
559 _pp_kv(pp
, 'g', me
.g
)
560 pp
.end_group(ind
, ')')
561 _augment(FGInfo
, _tmp
)
564 def group(me
): return PrimeGroup(me
)
565 _augment(DHInfo
, _tmp
)
568 def group(me
): return BinGroup(me
)
569 _augment(BinDHInfo
, _tmp
)
573 return '%s(%r)' %
(type(me
).__name__
, me
.info
)
574 _augment(Group
, _tmp
)
581 h ^
= 2*hash(info
.r
) & 0xffffffff
582 h ^
= 5*hash(info
.g
) & 0xffffffff
584 _augment(PrimeGroup
, _tmp
)
591 h ^
= 2*hash(info
.r
) & 0xffffffff
592 h ^
= 5*hash(info
.g
) & 0xffffffff
594 _augment(BinGroup
, _tmp
)
597 def __hash__(me
): return 0x0ec23dab ^
hash(me
.info
)
598 _augment(ECGroup
, _tmp
)
602 return '%r(%r)' %
(me
.group
, str(me
))
603 _repr_pretty_
= _pp_str
606 ###--------------------------------------------------------------------------
607 ### RSA encoding techniques.
609 class PKCS1Crypt (object):
610 def __init__(me
, ep
= '', rng
= rand
):
613 def encode(me
, msg
, nbits
):
614 return _base
._p1crypt_encode(msg
, nbits
, me
.ep
, me
.rng
)
615 def decode(me
, ct
, nbits
):
616 return _base
._p1crypt_decode(ct
, nbits
, me
.ep
, me
.rng
)
618 class PKCS1Sig (object):
619 def __init__(me
, ep
= '', rng
= rand
):
622 def encode(me
, msg
, nbits
):
623 return _base
._p1sig_encode(msg
, nbits
, me
.ep
, me
.rng
)
624 def decode(me
, msg
, sig
, nbits
):
625 return _base
._p1sig_decode(msg
, sig
, nbits
, me
.ep
, me
.rng
)
628 def __init__(me
, mgf
= sha_mgf
, hash = sha
, ep
= '', rng
= rand
):
633 def encode(me
, msg
, nbits
):
634 return _base
._oaep_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
635 def decode(me
, ct
, nbits
):
636 return _base
._oaep_decode(ct
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
639 def __init__(me
, mgf
= sha_mgf
, hash = sha
, saltsz
= None, rng
= rand
):
646 def encode(me
, msg
, nbits
):
647 return _base
._pss_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
648 def decode(me
, msg
, sig
, nbits
):
649 return _base
._pss_decode(msg
, sig
, nbits
,
650 me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
653 def encrypt(me
, msg
, enc
):
654 return me
.pubop(enc
.encode(msg
, me
.n
.nbits
))
655 def verify(me
, msg
, sig
, enc
):
656 if msg
is None: return enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
658 x
= enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
659 return x
is None or x
== msg
662 _augment(RSAPub
, _tmp
)
665 def decrypt(me
, ct
, enc
): return enc
.decode(me
.privop(ct
), me
.n
.nbits
)
666 def sign(me
, msg
, enc
): return me
.privop(enc
.encode(msg
, me
.n
.nbits
))
667 _augment(RSAPriv
, _tmp
)
669 ###--------------------------------------------------------------------------
670 ### Bernstein's elliptic curve crypto and related schemes.
673 bytes('0900000000000000000000000000000000000000000000000000000000000000')
676 bytes('05000000000000000000000000000000000000000000000000000000'
677 '00000000000000000000000000000000000000000000000000000000')
679 Z128
= bytes('00000000000000000000000000000000')
681 class _BoxyPub (object):
682 def __init__(me
, pub
, *kw
, **kwargs
):
683 if len(pub
) != me
._PUBSZ
: raise ValueError, 'bad public key'
684 super(_BoxyPub
, me
).__init__(*kw
, **kwargs
)
687 class _BoxyPriv (_BoxyPub
):
688 def __init__(me
, priv
, pub
= None, *kw
, **kwargs
):
689 if len(priv
) != me
._KEYSZ
: raise ValueError, 'bad private key'
690 if pub
is None: pub
= me
._op(priv
, me
._BASE
)
691 super(_BoxyPriv
, me
).__init__(pub
= pub
, *kw
, **kwargs
)
693 def agree(me
, you
): return me
._op(me
.priv
, you
.pub
)
694 def boxkey(me
, recip
):
695 return me
._hashkey(me
.agree(recip
))
696 def box(me
, recip
, n
, m
):
697 return secret_box(me
.boxkey(recip
), n
, m
)
698 def unbox(me
, recip
, n
, c
):
699 return secret_unbox(me
.boxkey(recip
, n
, c
))
701 class X25519Pub (_BoxyPub
):
702 _PUBSZ
= X25519_PUBSZ
705 class X25519Priv (_BoxyPriv
, X25519Pub
):
706 _KEYSZ
= X25519_KEYSZ
707 def _op(me
, k
, X
): return x25519(k
, X
)
708 def _hashkey(me
, z
): return hsalsa20_prf(z
, Z128
)
710 class X448Pub (_BoxyPub
):
714 class X448Priv (_BoxyPriv
, X448Pub
):
716 def _op(me
, k
, X
): return x448(k
, X
)
717 ##def _hashkey(me, z): return ???
719 class Ed25519Pub (object):
720 def __init__(me
, pub
):
722 def verify(me
, msg
, sig
):
723 return ed25519_verify(me
.pub
, msg
, sig
)
725 class Ed25519Priv (Ed25519Pub
):
726 def __init__(me
, priv
):
728 Ed25519Pub
.__init__(me
, ed25519_pubkey(priv
))
730 return ed25519_sign(me
.priv
, msg
, pub
= me
.pub
)
732 def generate(cls
, rng
= rand
):
733 return cls(rng
.block(ED25519_KEYSZ
))
735 ###--------------------------------------------------------------------------
736 ### Built-in named curves and prime groups.
738 class _groupmap (object):
739 def __init__(me
, map, nth
):
742 me
._n
= max(map.values()) + 1
745 return '{%s}' %
', '.join(['%r: %r' % kv
for kv
in me
.iteritems()])
746 def _repr_pretty_(me
, pp
, cyclep
):
750 pp
.begin_group(2, '{ ')
751 _pp_dict(pp
, me
.iteritems())
752 pp
.end_group(2, ' }')
755 def __contains__(me
, k
):
757 def __getitem__(me
, k
):
762 def __setitem__(me
, k
, v
):
763 raise TypeError, "immutable object"
775 return [k
for k
in me
]
777 return [me
[k
] for k
in me
]
779 return [(k
, me
[k
]) for k
in me
]
780 eccurves
= _groupmap(_base
._eccurves
, ECInfo
._curven
)
781 primegroups
= _groupmap(_base
._pgroups
, DHInfo
._groupn
)
782 bingroups
= _groupmap(_base
._bingroups
, BinDHInfo
._groupn
)
784 ###--------------------------------------------------------------------------
785 ### Prime number generation.
787 class PrimeGenEventHandler (object):
788 def pg_begin(me
, ev
):
792 def pg_abort(me
, ev
):
799 class SophieGermainStepJump (object):
800 def pg_begin(me
, ev
):
801 me
.lf
= PrimeFilter(ev
.x
)
802 me
.hf
= me
.lf
.muladd(2, 1)
808 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
810 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
813 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
820 class SophieGermainStepper (SophieGermainStepJump
):
821 def __init__(me
, step
):
828 class SophieGermainJumper (SophieGermainStepJump
):
829 def __init__(me
, jump
):
830 me
.ljump
= PrimeFilter(jump
);
831 me
.hjump
= me
.ljump
.muladd(2, 0)
838 SophieGermainStepJump
.pg_done(me
, ev
)
840 class SophieGermainTester (object):
843 def pg_begin(me
, ev
):
844 me
.lr
= RabinMiller(ev
.x
)
845 me
.hr
= RabinMiller(2 * ev
.x
+ 1)
847 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
848 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
850 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
851 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
853 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
860 class PrimitiveStepper (PrimeGenEventHandler
):
866 def pg_begin(me
, ev
):
867 me
.i
= iter(smallprimes
)
870 class PrimitiveTester (PrimeGenEventHandler
):
871 def __init__(me
, mod
, hh
= [], exp
= None):
877 if me
.exp
is not None:
878 x
= me
.mod
.exp(x
, me
.exp
)
879 if x
== 1: return PGEN_FAIL
881 if me
.mod
.exp(x
, h
) == 1: return PGEN_FAIL
885 class SimulStepper (PrimeGenEventHandler
):
886 def __init__(me
, mul
= 2, add
= 1, step
= 2):
890 def _stepfn(me
, step
):
892 raise ValueError, 'step must be positive'
894 return lambda f
: f
.step(step
)
895 j
= PrimeFilter(step
)
896 return lambda f
: f
.jump(j
)
897 def pg_begin(me
, ev
):
899 me
.lf
= PrimeFilter(x
)
900 me
.hf
= PrimeFilter(x
* me
.mul
+ me
.add
)
901 me
.lstep
= me
._stepfn(me
.step
)
902 me
.hstep
= me
._stepfn(me
.step
* me
.mul
)
903 SimulStepper
._cont(me
, ev
)
911 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
913 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
916 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
925 class SimulTester (PrimeGenEventHandler
):
926 def __init__(me
, mul
= 2, add
= 1):
929 def pg_begin(me
, ev
):
931 me
.lr
= RabinMiller(x
)
932 me
.hr
= RabinMiller(x
* me
.mul
+ me
.add
)
934 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
935 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
937 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
938 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
940 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
947 def sgprime(start
, step
= 2, name
= 'p', event
= pgen_nullev
, nsteps
= 0):
949 return pgen(start
, name
, SimulStepper(step
= step
), SimulTester(), event
,
950 nsteps
, RabinMiller
.iters(start
.nbits
))
952 def findprimitive(mod
, hh
= [], exp
= None, name
= 'g', event
= pgen_nullev
):
953 return pgen(0, name
, PrimitiveStepper(), PrimitiveTester(mod
, hh
, exp
),
956 def kcdsaprime(pbits
, qbits
, rng
= rand
,
957 event
= pgen_nullev
, name
= 'p', nsteps
= 0):
958 hbits
= pbits
- qbits
959 h
= pgen(rng
.mp(hbits
, 1), name
+ ' [h]',
960 PrimeGenStepper(2), PrimeGenTester(),
961 event
, nsteps
, RabinMiller
.iters(hbits
))
962 q
= pgen(rng
.mp(qbits
, 1), name
, SimulStepper(2 * h
, 1, 2),
963 SimulTester(2 * h
, 1), event
, nsteps
, RabinMiller
.iters(qbits
))
967 #----- That's all, folks ----------------------------------------------------