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 def _repr_pretty_(me
, pp
, cyclep
):
578 ind
= _pp_bgroup_tyname(pp
, me
)
579 if cyclep
: pp
.text('...')
580 else: pp
.pretty(me
.info
)
581 pp
.end_group(ind
, ')')
582 _augment(Group
, _tmp
)
589 h ^
= 2*hash(info
.r
) & 0xffffffff
590 h ^
= 5*hash(info
.g
) & 0xffffffff
592 _augment(PrimeGroup
, _tmp
)
599 h ^
= 2*hash(info
.r
) & 0xffffffff
600 h ^
= 5*hash(info
.g
) & 0xffffffff
602 _augment(BinGroup
, _tmp
)
605 def __hash__(me
): return 0x0ec23dab ^
hash(me
.info
)
606 _augment(ECGroup
, _tmp
)
610 return '%r(%r)' %
(me
.group
, str(me
))
611 _repr_pretty_
= _pp_str
614 ###--------------------------------------------------------------------------
615 ### RSA encoding techniques.
617 class PKCS1Crypt (object):
618 def __init__(me
, ep
= '', rng
= rand
):
621 def encode(me
, msg
, nbits
):
622 return _base
._p1crypt_encode(msg
, nbits
, me
.ep
, me
.rng
)
623 def decode(me
, ct
, nbits
):
624 return _base
._p1crypt_decode(ct
, nbits
, me
.ep
, me
.rng
)
626 class PKCS1Sig (object):
627 def __init__(me
, ep
= '', rng
= rand
):
630 def encode(me
, msg
, nbits
):
631 return _base
._p1sig_encode(msg
, nbits
, me
.ep
, me
.rng
)
632 def decode(me
, msg
, sig
, nbits
):
633 return _base
._p1sig_decode(msg
, sig
, nbits
, me
.ep
, me
.rng
)
636 def __init__(me
, mgf
= sha_mgf
, hash = sha
, ep
= '', rng
= rand
):
641 def encode(me
, msg
, nbits
):
642 return _base
._oaep_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
643 def decode(me
, ct
, nbits
):
644 return _base
._oaep_decode(ct
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
647 def __init__(me
, mgf
= sha_mgf
, hash = sha
, saltsz
= None, rng
= rand
):
654 def encode(me
, msg
, nbits
):
655 return _base
._pss_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
656 def decode(me
, msg
, sig
, nbits
):
657 return _base
._pss_decode(msg
, sig
, nbits
,
658 me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
661 def encrypt(me
, msg
, enc
):
662 return me
.pubop(enc
.encode(msg
, me
.n
.nbits
))
663 def verify(me
, msg
, sig
, enc
):
664 if msg
is None: return enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
666 x
= enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
667 return x
is None or x
== msg
670 _augment(RSAPub
, _tmp
)
673 def decrypt(me
, ct
, enc
): return enc
.decode(me
.privop(ct
), me
.n
.nbits
)
674 def sign(me
, msg
, enc
): return me
.privop(enc
.encode(msg
, me
.n
.nbits
))
675 _augment(RSAPriv
, _tmp
)
677 ###--------------------------------------------------------------------------
678 ### Bernstein's elliptic curve crypto and related schemes.
681 bytes('0900000000000000000000000000000000000000000000000000000000000000')
684 bytes('05000000000000000000000000000000000000000000000000000000'
685 '00000000000000000000000000000000000000000000000000000000')
687 Z128
= bytes('00000000000000000000000000000000')
689 class _BoxyPub (object):
690 def __init__(me
, pub
, *kw
, **kwargs
):
691 if len(pub
) != me
._PUBSZ
: raise ValueError, 'bad public key'
692 super(_BoxyPub
, me
).__init__(*kw
, **kwargs
)
695 class _BoxyPriv (_BoxyPub
):
696 def __init__(me
, priv
, pub
= None, *kw
, **kwargs
):
697 if len(priv
) != me
._KEYSZ
: raise ValueError, 'bad private key'
698 if pub
is None: pub
= me
._op(priv
, me
._BASE
)
699 super(_BoxyPriv
, me
).__init__(pub
= pub
, *kw
, **kwargs
)
701 def agree(me
, you
): return me
._op(me
.priv
, you
.pub
)
702 def boxkey(me
, recip
):
703 return me
._hashkey(me
.agree(recip
))
704 def box(me
, recip
, n
, m
):
705 return secret_box(me
.boxkey(recip
), n
, m
)
706 def unbox(me
, recip
, n
, c
):
707 return secret_unbox(me
.boxkey(recip
, n
, c
))
709 class X25519Pub (_BoxyPub
):
710 _PUBSZ
= X25519_PUBSZ
713 class X25519Priv (_BoxyPriv
, X25519Pub
):
714 _KEYSZ
= X25519_KEYSZ
715 def _op(me
, k
, X
): return x25519(k
, X
)
716 def _hashkey(me
, z
): return hsalsa20_prf(z
, Z128
)
718 class X448Pub (_BoxyPub
):
722 class X448Priv (_BoxyPriv
, X448Pub
):
724 def _op(me
, k
, X
): return x448(k
, X
)
725 ##def _hashkey(me, z): return ???
727 class Ed25519Pub (object):
728 def __init__(me
, pub
):
730 def verify(me
, msg
, sig
):
731 return ed25519_verify(me
.pub
, msg
, sig
)
733 class Ed25519Priv (Ed25519Pub
):
734 def __init__(me
, priv
):
736 Ed25519Pub
.__init__(me
, ed25519_pubkey(priv
))
738 return ed25519_sign(me
.priv
, msg
, pub
= me
.pub
)
740 def generate(cls
, rng
= rand
):
741 return cls(rng
.block(ED25519_KEYSZ
))
743 ###--------------------------------------------------------------------------
744 ### Built-in named curves and prime groups.
746 class _groupmap (object):
747 def __init__(me
, map, nth
):
750 me
._n
= max(map.values()) + 1
753 return '{%s}' %
', '.join(['%r: %r' % kv
for kv
in me
.iteritems()])
754 def _repr_pretty_(me
, pp
, cyclep
):
755 ind
= _pp_bgroup(pp
, '{ ')
756 if cyclep
: pp
.text('...')
757 else: _pp_dict(pp
, me
.iteritems())
758 pp
.end_group(ind
, ' }')
761 def __contains__(me
, k
):
763 def __getitem__(me
, k
):
768 def __setitem__(me
, k
, v
):
769 raise TypeError, "immutable object"
781 return [k
for k
in me
]
783 return [me
[k
] for k
in me
]
785 return [(k
, me
[k
]) for k
in me
]
786 eccurves
= _groupmap(_base
._eccurves
, ECInfo
._curven
)
787 primegroups
= _groupmap(_base
._pgroups
, DHInfo
._groupn
)
788 bingroups
= _groupmap(_base
._bingroups
, BinDHInfo
._groupn
)
790 ###--------------------------------------------------------------------------
791 ### Prime number generation.
793 class PrimeGenEventHandler (object):
794 def pg_begin(me
, ev
):
798 def pg_abort(me
, ev
):
805 class SophieGermainStepJump (object):
806 def pg_begin(me
, ev
):
807 me
.lf
= PrimeFilter(ev
.x
)
808 me
.hf
= me
.lf
.muladd(2, 1)
814 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
816 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
819 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
826 class SophieGermainStepper (SophieGermainStepJump
):
827 def __init__(me
, step
):
834 class SophieGermainJumper (SophieGermainStepJump
):
835 def __init__(me
, jump
):
836 me
.ljump
= PrimeFilter(jump
);
837 me
.hjump
= me
.ljump
.muladd(2, 0)
844 SophieGermainStepJump
.pg_done(me
, ev
)
846 class SophieGermainTester (object):
849 def pg_begin(me
, ev
):
850 me
.lr
= RabinMiller(ev
.x
)
851 me
.hr
= RabinMiller(2 * ev
.x
+ 1)
853 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
854 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
856 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
857 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
859 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
866 class PrimitiveStepper (PrimeGenEventHandler
):
872 def pg_begin(me
, ev
):
873 me
.i
= iter(smallprimes
)
876 class PrimitiveTester (PrimeGenEventHandler
):
877 def __init__(me
, mod
, hh
= [], exp
= None):
883 if me
.exp
is not None:
884 x
= me
.mod
.exp(x
, me
.exp
)
885 if x
== 1: return PGEN_FAIL
887 if me
.mod
.exp(x
, h
) == 1: return PGEN_FAIL
891 class SimulStepper (PrimeGenEventHandler
):
892 def __init__(me
, mul
= 2, add
= 1, step
= 2):
896 def _stepfn(me
, step
):
898 raise ValueError, 'step must be positive'
900 return lambda f
: f
.step(step
)
901 j
= PrimeFilter(step
)
902 return lambda f
: f
.jump(j
)
903 def pg_begin(me
, ev
):
905 me
.lf
= PrimeFilter(x
)
906 me
.hf
= PrimeFilter(x
* me
.mul
+ me
.add
)
907 me
.lstep
= me
._stepfn(me
.step
)
908 me
.hstep
= me
._stepfn(me
.step
* me
.mul
)
909 SimulStepper
._cont(me
, ev
)
917 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
919 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
922 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
931 class SimulTester (PrimeGenEventHandler
):
932 def __init__(me
, mul
= 2, add
= 1):
935 def pg_begin(me
, ev
):
937 me
.lr
= RabinMiller(x
)
938 me
.hr
= RabinMiller(x
* me
.mul
+ me
.add
)
940 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
941 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
943 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
944 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
946 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
953 def sgprime(start
, step
= 2, name
= 'p', event
= pgen_nullev
, nsteps
= 0):
955 return pgen(start
, name
, SimulStepper(step
= step
), SimulTester(), event
,
956 nsteps
, RabinMiller
.iters(start
.nbits
))
958 def findprimitive(mod
, hh
= [], exp
= None, name
= 'g', event
= pgen_nullev
):
959 return pgen(0, name
, PrimitiveStepper(), PrimitiveTester(mod
, hh
, exp
),
962 def kcdsaprime(pbits
, qbits
, rng
= rand
,
963 event
= pgen_nullev
, name
= 'p', nsteps
= 0):
964 hbits
= pbits
- qbits
965 h
= pgen(rng
.mp(hbits
, 1), name
+ ' [h]',
966 PrimeGenStepper(2), PrimeGenTester(),
967 event
, nsteps
, RabinMiller
.iters(hbits
))
968 q
= pgen(rng
.mp(qbits
, 1), name
, SimulStepper(2 * h
, 1, 2),
969 SimulTester(2 * h
, 1), event
, nsteps
, RabinMiller
.iters(qbits
))
973 #----- That's all, folks ----------------------------------------------------