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 def _repr_pretty_(me
, pp
, cyclep
):
393 ind
= _pp_bgroup(pp
, '(')
394 pp
.pretty(me
.x
); pp
.text(','); pp
.breakable()
396 pp
.end_group(ind
, ')')
397 _augment(ECPtCurve
, _tmp
)
399 ###--------------------------------------------------------------------------
403 def __repr__(me
): return 'KeySZAny(%d)' % me
.default
404 def check(me
, sz
): return True
405 def best(me
, sz
): return sz
406 _augment(KeySZAny
, _tmp
)
410 return 'KeySZRange(%d, %d, %d, %d)' % \
411 (me
.default
, me
.min, me
.max, me
.mod
)
412 def _repr_pretty_(me
, pp
, cyclep
):
413 ind
= _pp_bgroup_tyname(pp
, me
)
417 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
418 pp
.pretty(me
.min); pp
.text(','); pp
.breakable()
419 pp
.pretty(me
.max); pp
.text(','); pp
.breakable()
421 pp
.end_group(ind
, ')')
422 def check(me
, sz
): return me
.min <= sz
<= me
.max and sz % me
.mod
== 0
424 if sz
< me
.min: raise ValueError, 'key too small'
425 elif sz
> me
.max: return me
.max
426 else: return sz
- (sz % me
.mod
)
427 _augment(KeySZRange
, _tmp
)
430 def __repr__(me
): return 'KeySZSet(%d, %s)' %
(me
.default
, me
.set)
431 def _repr_pretty_(me
, pp
, cyclep
):
432 ind
= _pp_bgroup_tyname(pp
, me
)
436 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
437 ind1
= _pp_bgroup(pp
, '{')
438 _pp_commas(pp
, pp
.pretty
, me
.set)
439 pp
.end_group(ind1
, '}')
440 pp
.end_group(ind
, ')')
441 def check(me
, sz
): return sz
in me
.set
445 if found
< i
<= sz
: found
= i
446 if found
< 0: raise ValueError, 'key too small'
448 _augment(KeySZSet
, _tmp
)
450 ###--------------------------------------------------------------------------
451 ### Key data objects.
454 def __repr__(me
): return 'KeyFile(%r)' % me
.name
455 _augment(KeyFile
, _tmp
)
458 def __repr__(me
): return 'Key(%r)' % me
.fulltag
463 return 'KeyAttributes({%s})' % \
464 ', '.join(['%r: %r' % kv
for kv
in me
.iteritems()])
465 def _repr_pretty_(me
, pp
, cyclep
):
466 ind
= _pp_bgroup_tyname(pp
, me
)
467 if cyclep
: pp
.text('...')
468 else: _pp_dict(pp
, me
.iteritems())
469 pp
.end_group(ind
, ')')
470 _augment(KeyAttributes
, _tmp
)
473 def __repr__(me
): return 'KeyDataBinary(%r, %r)' % \
474 (me
.bin
, me
.writeflags(me
.flags
))
475 def _repr_pretty_(me
, pp
, cyclep
):
476 ind
= _pp_bgroup_tyname(pp
, me
)
480 pp
.pretty(me
.bin
); pp
.text(','); pp
.breakable()
481 pp
.pretty(me
.writeflags(me
.flags
))
482 pp
.end_group(ind
, ')')
483 _augment(KeyDataBinary
, _tmp
)
486 def __repr__(me
): return 'KeyDataEncrypted(%r, %r)' % \
487 (me
.ct
, me
.writeflags(me
.flags
))
488 def _repr_pretty_(me
, pp
, cyclep
):
489 ind
= _pp_bgroup_tyname(pp
, me
)
493 pp
.pretty(me
.ct
); pp
.text(','); pp
.breakable()
494 pp
.pretty(me
.writeflags(me
.flags
))
495 pp
.end_group(ind
, ')')
496 _augment(KeyDataEncrypted
, _tmp
)
499 def __repr__(me
): return 'KeyDataMP(%r, %r)' % \
500 (me
.mp
, me
.writeflags(me
.flags
))
501 def _repr_pretty_(me
, pp
, cyclep
):
502 ind
= _pp_bgroup_tyname(pp
, me
)
506 pp
.pretty(me
.mp
); pp
.text(','); pp
.breakable()
507 pp
.pretty(me
.writeflags(me
.flags
))
508 pp
.end_group(ind
, ')')
509 _augment(KeyDataMP
, _tmp
)
512 def __repr__(me
): return 'KeyDataString(%r)' % \
513 (me
.str, me
.writeflags(me
.flags
))
514 def _repr_pretty_(me
, pp
, cyclep
):
515 ind
= _pp_bgroup_tyname(pp
, me
)
519 pp
.pretty(me
.str); pp
.text(','); pp
.breakable()
520 pp
.pretty(me
.writeflags(me
.flags
))
521 pp
.end_group(ind
, ')')
522 _augment(KeyDataString
, _tmp
)
525 def __repr__(me
): return 'KeyDataECPt(%r)' % \
526 (me
.ecpt
, me
.writeflags(me
.flags
))
527 def _repr_pretty_(me
, pp
, cyclep
):
528 ind
= _pp_bgroup_tyname(pp
, me
)
532 pp
.pretty(me
.ecpt
); pp
.text(','); pp
.breakable()
533 pp
.pretty(me
.writeflags(me
.flags
))
534 pp
.end_group(ind
, ')')
535 _augment(KeyDataECPt
, _tmp
)
539 return 'KeyDataStructured({%s})' % \
540 ', '.join(['%r: %r' % kv
for kv
in me
.iteritems()])
541 def _repr_pretty_(me
, pp
, cyclep
):
542 ind
= _pp_bgroup_tyname(pp
, me
, '({ ')
543 if cyclep
: pp
.text('...')
544 else: _pp_dict(pp
, me
.iteritems())
545 pp
.end_group(ind
, ' })')
546 _augment(KeyDataStructured
, _tmp
)
548 ###--------------------------------------------------------------------------
553 return '%s(p = %s, r = %s, g = %s)' % \
554 (type(me
).__name__
, me
.p
, me
.r
, me
.g
)
555 def _repr_pretty_(me
, pp
, cyclep
):
556 ind
= _pp_bgroup_tyname(pp
, me
)
560 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
561 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
562 _pp_kv(pp
, 'g', me
.g
)
563 pp
.end_group(ind
, ')')
564 _augment(FGInfo
, _tmp
)
567 def group(me
): return PrimeGroup(me
)
568 _augment(DHInfo
, _tmp
)
571 def group(me
): return BinGroup(me
)
572 _augment(BinDHInfo
, _tmp
)
576 return '%s(%r)' %
(type(me
).__name__
, me
.info
)
577 _augment(Group
, _tmp
)
584 h ^
= 2*hash(info
.r
) & 0xffffffff
585 h ^
= 5*hash(info
.g
) & 0xffffffff
587 _augment(PrimeGroup
, _tmp
)
594 h ^
= 2*hash(info
.r
) & 0xffffffff
595 h ^
= 5*hash(info
.g
) & 0xffffffff
597 _augment(BinGroup
, _tmp
)
600 def __hash__(me
): return 0x0ec23dab ^
hash(me
.info
)
601 _augment(ECGroup
, _tmp
)
605 return '%r(%r)' %
(me
.group
, str(me
))
606 _repr_pretty_
= _pp_str
609 ###--------------------------------------------------------------------------
610 ### RSA encoding techniques.
612 class PKCS1Crypt (object):
613 def __init__(me
, ep
= '', rng
= rand
):
616 def encode(me
, msg
, nbits
):
617 return _base
._p1crypt_encode(msg
, nbits
, me
.ep
, me
.rng
)
618 def decode(me
, ct
, nbits
):
619 return _base
._p1crypt_decode(ct
, nbits
, me
.ep
, me
.rng
)
621 class PKCS1Sig (object):
622 def __init__(me
, ep
= '', rng
= rand
):
625 def encode(me
, msg
, nbits
):
626 return _base
._p1sig_encode(msg
, nbits
, me
.ep
, me
.rng
)
627 def decode(me
, msg
, sig
, nbits
):
628 return _base
._p1sig_decode(msg
, sig
, nbits
, me
.ep
, me
.rng
)
631 def __init__(me
, mgf
= sha_mgf
, hash = sha
, ep
= '', rng
= rand
):
636 def encode(me
, msg
, nbits
):
637 return _base
._oaep_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
638 def decode(me
, ct
, nbits
):
639 return _base
._oaep_decode(ct
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
642 def __init__(me
, mgf
= sha_mgf
, hash = sha
, saltsz
= None, rng
= rand
):
649 def encode(me
, msg
, nbits
):
650 return _base
._pss_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
651 def decode(me
, msg
, sig
, nbits
):
652 return _base
._pss_decode(msg
, sig
, nbits
,
653 me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
656 def encrypt(me
, msg
, enc
):
657 return me
.pubop(enc
.encode(msg
, me
.n
.nbits
))
658 def verify(me
, msg
, sig
, enc
):
659 if msg
is None: return enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
661 x
= enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
662 return x
is None or x
== msg
665 _augment(RSAPub
, _tmp
)
668 def decrypt(me
, ct
, enc
): return enc
.decode(me
.privop(ct
), me
.n
.nbits
)
669 def sign(me
, msg
, enc
): return me
.privop(enc
.encode(msg
, me
.n
.nbits
))
670 _augment(RSAPriv
, _tmp
)
672 ###--------------------------------------------------------------------------
673 ### Bernstein's elliptic curve crypto and related schemes.
676 bytes('0900000000000000000000000000000000000000000000000000000000000000')
679 bytes('05000000000000000000000000000000000000000000000000000000'
680 '00000000000000000000000000000000000000000000000000000000')
682 Z128
= bytes('00000000000000000000000000000000')
684 class _BoxyPub (object):
685 def __init__(me
, pub
, *kw
, **kwargs
):
686 if len(pub
) != me
._PUBSZ
: raise ValueError, 'bad public key'
687 super(_BoxyPub
, me
).__init__(*kw
, **kwargs
)
690 class _BoxyPriv (_BoxyPub
):
691 def __init__(me
, priv
, pub
= None, *kw
, **kwargs
):
692 if len(priv
) != me
._KEYSZ
: raise ValueError, 'bad private key'
693 if pub
is None: pub
= me
._op(priv
, me
._BASE
)
694 super(_BoxyPriv
, me
).__init__(pub
= pub
, *kw
, **kwargs
)
696 def agree(me
, you
): return me
._op(me
.priv
, you
.pub
)
697 def boxkey(me
, recip
):
698 return me
._hashkey(me
.agree(recip
))
699 def box(me
, recip
, n
, m
):
700 return secret_box(me
.boxkey(recip
), n
, m
)
701 def unbox(me
, recip
, n
, c
):
702 return secret_unbox(me
.boxkey(recip
, n
, c
))
704 class X25519Pub (_BoxyPub
):
705 _PUBSZ
= X25519_PUBSZ
708 class X25519Priv (_BoxyPriv
, X25519Pub
):
709 _KEYSZ
= X25519_KEYSZ
710 def _op(me
, k
, X
): return x25519(k
, X
)
711 def _hashkey(me
, z
): return hsalsa20_prf(z
, Z128
)
713 class X448Pub (_BoxyPub
):
717 class X448Priv (_BoxyPriv
, X448Pub
):
719 def _op(me
, k
, X
): return x448(k
, X
)
720 ##def _hashkey(me, z): return ???
722 class Ed25519Pub (object):
723 def __init__(me
, pub
):
725 def verify(me
, msg
, sig
):
726 return ed25519_verify(me
.pub
, msg
, sig
)
728 class Ed25519Priv (Ed25519Pub
):
729 def __init__(me
, priv
):
731 Ed25519Pub
.__init__(me
, ed25519_pubkey(priv
))
733 return ed25519_sign(me
.priv
, msg
, pub
= me
.pub
)
735 def generate(cls
, rng
= rand
):
736 return cls(rng
.block(ED25519_KEYSZ
))
738 ###--------------------------------------------------------------------------
739 ### Built-in named curves and prime groups.
741 class _groupmap (object):
742 def __init__(me
, map, nth
):
745 me
._n
= max(map.values()) + 1
748 return '{%s}' %
', '.join(['%r: %r' % kv
for kv
in me
.iteritems()])
749 def _repr_pretty_(me
, pp
, cyclep
):
750 ind
= _pp_bgroup(pp
, '{ ')
751 if cyclep
: pp
.text('...')
752 else: _pp_dict(pp
, me
.iteritems())
753 pp
.end_group(ind
, ' }')
756 def __contains__(me
, k
):
758 def __getitem__(me
, k
):
763 def __setitem__(me
, k
, v
):
764 raise TypeError, "immutable object"
776 return [k
for k
in me
]
778 return [me
[k
] for k
in me
]
780 return [(k
, me
[k
]) for k
in me
]
781 eccurves
= _groupmap(_base
._eccurves
, ECInfo
._curven
)
782 primegroups
= _groupmap(_base
._pgroups
, DHInfo
._groupn
)
783 bingroups
= _groupmap(_base
._bingroups
, BinDHInfo
._groupn
)
785 ###--------------------------------------------------------------------------
786 ### Prime number generation.
788 class PrimeGenEventHandler (object):
789 def pg_begin(me
, ev
):
793 def pg_abort(me
, ev
):
800 class SophieGermainStepJump (object):
801 def pg_begin(me
, ev
):
802 me
.lf
= PrimeFilter(ev
.x
)
803 me
.hf
= me
.lf
.muladd(2, 1)
809 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
811 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
814 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
821 class SophieGermainStepper (SophieGermainStepJump
):
822 def __init__(me
, step
):
829 class SophieGermainJumper (SophieGermainStepJump
):
830 def __init__(me
, jump
):
831 me
.ljump
= PrimeFilter(jump
);
832 me
.hjump
= me
.ljump
.muladd(2, 0)
839 SophieGermainStepJump
.pg_done(me
, ev
)
841 class SophieGermainTester (object):
844 def pg_begin(me
, ev
):
845 me
.lr
= RabinMiller(ev
.x
)
846 me
.hr
= RabinMiller(2 * ev
.x
+ 1)
848 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
849 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
851 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
852 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
854 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
861 class PrimitiveStepper (PrimeGenEventHandler
):
867 def pg_begin(me
, ev
):
868 me
.i
= iter(smallprimes
)
871 class PrimitiveTester (PrimeGenEventHandler
):
872 def __init__(me
, mod
, hh
= [], exp
= None):
878 if me
.exp
is not None:
879 x
= me
.mod
.exp(x
, me
.exp
)
880 if x
== 1: return PGEN_FAIL
882 if me
.mod
.exp(x
, h
) == 1: return PGEN_FAIL
886 class SimulStepper (PrimeGenEventHandler
):
887 def __init__(me
, mul
= 2, add
= 1, step
= 2):
891 def _stepfn(me
, step
):
893 raise ValueError, 'step must be positive'
895 return lambda f
: f
.step(step
)
896 j
= PrimeFilter(step
)
897 return lambda f
: f
.jump(j
)
898 def pg_begin(me
, ev
):
900 me
.lf
= PrimeFilter(x
)
901 me
.hf
= PrimeFilter(x
* me
.mul
+ me
.add
)
902 me
.lstep
= me
._stepfn(me
.step
)
903 me
.hstep
= me
._stepfn(me
.step
* me
.mul
)
904 SimulStepper
._cont(me
, ev
)
912 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
914 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
917 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
926 class SimulTester (PrimeGenEventHandler
):
927 def __init__(me
, mul
= 2, add
= 1):
930 def pg_begin(me
, ev
):
932 me
.lr
= RabinMiller(x
)
933 me
.hr
= RabinMiller(x
* me
.mul
+ me
.add
)
935 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
936 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
938 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
939 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
941 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
948 def sgprime(start
, step
= 2, name
= 'p', event
= pgen_nullev
, nsteps
= 0):
950 return pgen(start
, name
, SimulStepper(step
= step
), SimulTester(), event
,
951 nsteps
, RabinMiller
.iters(start
.nbits
))
953 def findprimitive(mod
, hh
= [], exp
= None, name
= 'g', event
= pgen_nullev
):
954 return pgen(0, name
, PrimitiveStepper(), PrimitiveTester(mod
, hh
, exp
),
957 def kcdsaprime(pbits
, qbits
, rng
= rand
,
958 event
= pgen_nullev
, name
= 'p', nsteps
= 0):
959 hbits
= pbits
- qbits
960 h
= pgen(rng
.mp(hbits
, 1), name
+ ' [h]',
961 PrimeGenStepper(2), PrimeGenTester(),
962 event
, nsteps
, RabinMiller
.iters(hbits
))
963 q
= pgen(rng
.mp(qbits
, 1), name
, SimulStepper(2 * h
, 1, 2),
964 SimulTester(2 * h
, 1), event
, nsteps
, RabinMiller
.iters(qbits
))
968 #----- That's all, folks ----------------------------------------------------