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 ## How to fix a name back into the right identifier. Alas, the rules are not
41 ## Hyphens consistently become underscores.
42 name
= name
.replace('-', '_')
44 ## But slashes might become underscores or just vanish.
45 if name
.startswith('salsa20'): name
= name
.translate(None, '/')
46 else: name
= name
.replace('/', '_')
51 ## Initialize the module. Drag in the static methods of the various
52 ## classes; create names for the various known crypto algorithms.
59 for i
in ['ByteString',
61 'ECPt', 'ECPtCurve', 'ECCurve', 'ECInfo',
62 'DHInfo', 'BinDHInfo', 'RSAPriv', 'BBSPriv',
63 'PrimeFilter', 'RabinMiller',
71 setattr(c
, j
[plen
:], classmethod(b
[j
]))
72 for i
in [gcciphers
, gchashes
, gcmacs
, gcprps
]:
73 for c
in i
.itervalues():
74 d
[_fixname(c
.name
)] = c
75 for c
in gccrands
.itervalues():
76 d
[_fixname(c
.name
+ 'rand')] = c
79 ## A handy function for our work: add the methods of a named class to an
80 ## existing class. This is how we write the Python-implemented parts of our
85 if type(a
) is _types
.MethodType
:
87 elif type(a
) not in (_types
.FunctionType
, staticmethod, classmethod):
91 ## Parsing functions tend to return the object parsed and the remainder of
92 ## the input. This checks that the remainder is input and, if so, returns
97 raise SyntaxError, 'junk at end of string'
100 ## Some pretty-printing utilities.
101 PRINT_SECRETS
= False
102 def _clsname(me
): return type(me
).__name__
103 def _repr_secret(thing
, secretp
= True):
104 if not secretp
or PRINT_SECRETS
: return repr(thing
)
105 else: return '#<SECRET>'
106 def _pp_str(me
, pp
, cyclep
): pp
.text(cyclep
and '...' or str(me
))
107 def _pp_secret(pp
, thing
, secretp
= True):
108 if not secretp
or PRINT_SECRETS
: pp
.pretty(thing
)
109 else: pp
.text('#<SECRET>')
110 def _pp_bgroup(pp
, text
):
112 pp
.begin_group(ind
, text
)
114 def _pp_bgroup_tyname(pp
, obj
, open = '('):
115 return _pp_bgroup(pp
, _clsname(obj
) + open)
116 def _pp_kv(pp
, k
, v
, secretp
= False):
117 ind
= _pp_bgroup(pp
, k
+ ' = ')
118 _pp_secret(pp
, v
, secretp
)
119 pp
.end_group(ind
, '')
120 def _pp_commas(pp
, printfn
, items
):
123 if firstp
: firstp
= False
124 else: pp
.text(','); pp
.breakable()
126 def _pp_dict(pp
, items
):
136 _pp_commas(pp
, p
, items
)
138 ###--------------------------------------------------------------------------
143 return ByteString(_unhexify(x
))
144 fromhex
= staticmethod(fromhex
)
148 return 'bytes(%r)' %
hex(me
)
149 _augment(ByteString
, _tmp
)
150 ByteString
.__hash__
= str.__hash__
151 bytes
= ByteString
.fromhex
153 ###--------------------------------------------------------------------------
159 return ctstreq(h
, hh
)
160 _augment(GHash
, _tmp
)
161 _augment(Poly1305Hash
, _tmp
)
163 ###--------------------------------------------------------------------------
164 ### NaCl `secretbox'.
166 def secret_box(k
, n
, m
):
167 E
= xsalsa20(k
).setiv(n
)
168 r
= E
.enczero(poly1305
.keysz
.default
)
169 s
= E
.enczero(poly1305
.masksz
)
171 t
= poly1305(r
)(s
).hash(y
).done()
172 return ByteString(t
+ y
)
174 def secret_unbox(k
, n
, c
):
175 E
= xsalsa20(k
).setiv(n
)
176 r
= E
.enczero(poly1305
.keysz
.default
)
177 s
= E
.enczero(poly1305
.masksz
)
178 y
= c
[poly1305
.tagsz
:]
179 if not poly1305(r
)(s
).hash(y
).check(c
[0:poly1305
.tagsz
]):
180 raise ValueError, 'decryption failed'
181 return E
.decrypt(c
[poly1305
.tagsz
:])
183 ###--------------------------------------------------------------------------
184 ### Multiprecision integers and binary polynomials.
187 if isinstance(x
, BaseRat
): return x
._n
, x
._d
189 class BaseRat (object):
190 """Base class implementing fields of fractions over Euclidean domains."""
191 def __new__(cls
, a
, b
):
192 a
, b
= cls
.RING(a
), cls
.RING(b
)
196 me
= super(BaseRat
, cls
).__new__(cls
)
201 def numer(me
): return me
._n
203 def denom(me
): return me
._d
204 def __str__(me
): return '%s/%s' %
(me
._n
, me
._d
)
205 def __repr__(me
): return '%s(%s, %s)' %
(_clsname(me
), me
._n
, me
._d
)
206 _repr_pretty_
= _pp_str
208 def __add__(me
, you
):
209 n
, d
= _split_rat(you
)
210 return type(me
)(me
._n
*d
+ n
*me
._d
, d
*me
._d
)
212 def __sub__(me
, you
):
213 n
, d
= _split_rat(you
)
214 return type(me
)(me
._n
*d
- n
*me
._d
, d
*me
._d
)
215 def __rsub__(me
, you
):
216 n
, d
= _split_rat(you
)
217 return type(me
)(n
*me
._d
- me
._n
*d
, d
*me
._d
)
218 def __mul__(me
, you
):
219 n
, d
= _split_rat(you
)
220 return type(me
)(me
._n
*n
, me
._d
*d
)
221 def __div__(me
, you
):
222 n
, d
= _split_rat(you
)
223 return type(me
)(me
._n
*d
, me
._d
*n
)
224 def __rdiv__(me
, you
):
225 n
, d
= _split_rat(you
)
226 return type(me
)(me
._d
*n
, me
._n
*d
)
227 def __cmp__(me
, you
):
228 n
, d
= _split_rat(you
)
229 return type(me
)(me
._n
*d
, n
*me
._d
)
230 def __rcmp__(me
, you
):
231 n
, d
= _split_rat(you
)
232 return cmp(n
*me
._d
, me
._n
*d
)
234 class IntRat (BaseRat
):
237 class GFRat (BaseRat
):
241 def negp(x
): return x
< 0
242 def posp(x
): return x
> 0
243 def zerop(x
): return x
== 0
244 def oddp(x
): return x
.testbit(0)
245 def evenp(x
): return not x
.testbit(0)
246 def mont(x
): return MPMont(x
)
247 def barrett(x
): return MPBarrett(x
)
248 def reduce(x
): return MPReduce(x
)
249 def __div__(me
, you
): return IntRat(me
, you
)
250 def __rdiv__(me
, you
): return IntRat(you
, me
)
251 _repr_pretty_
= _pp_str
255 def zerop(x
): return x
== 0
256 def reduce(x
): return GFReduce(x
)
257 def trace(x
, y
): return x
.reduce().trace(y
)
258 def halftrace(x
, y
): return x
.reduce().halftrace(y
)
259 def modsqrt(x
, y
): return x
.reduce().sqrt(y
)
260 def quadsolve(x
, y
): return x
.reduce().quadsolve(y
)
261 def __div__(me
, you
): return GFRat(me
, you
)
262 def __rdiv__(me
, you
): return GFRat(you
, me
)
263 _repr_pretty_
= _pp_str
268 'product(ITERABLE) or product(I, ...) -> PRODUCT'
269 return MPMul(*arg
).done()
270 product
= staticmethod(product
)
271 _augment(MPMul
, _tmp
)
273 ###--------------------------------------------------------------------------
277 def fromstring(str): return _checkend(Field
.parse(str))
278 fromstring
= staticmethod(fromstring
)
279 _augment(Field
, _tmp
)
282 def __repr__(me
): return '%s(%sL)' %
(_clsname(me
), me
.p
)
283 def __hash__(me
): return 0x114401de ^
hash(me
.p
)
284 def _repr_pretty_(me
, pp
, cyclep
):
285 ind
= _pp_bgroup_tyname(pp
, me
)
286 if cyclep
: pp
.text('...')
287 else: pp
.pretty(me
.p
)
288 pp
.end_group(ind
, ')')
289 def ec(me
, a
, b
): return ECPrimeProjCurve(me
, a
, b
)
290 _augment(PrimeField
, _tmp
)
293 def __repr__(me
): return '%s(%#xL)' %
(_clsname(me
), me
.p
)
294 def ec(me
, a
, b
): return ECBinProjCurve(me
, a
, b
)
295 def _repr_pretty_(me
, pp
, cyclep
):
296 ind
= _pp_bgroup_tyname(pp
, me
)
297 if cyclep
: pp
.text('...')
298 else: pp
.text('%#x' % me
.p
)
299 pp
.end_group(ind
, ')')
300 _augment(BinField
, _tmp
)
303 def __hash__(me
): return 0x23e4701c ^
hash(me
.p
)
304 _augment(BinPolyField
, _tmp
)
310 h ^
= 2*hash(me
.beta
) & 0xffffffff
312 _augment(BinNormField
, _tmp
)
315 def __str__(me
): return str(me
.value
)
316 def __repr__(me
): return '%s(%s)' %
(repr(me
.field
), repr(me
.value
))
317 _repr_pretty_
= _pp_str
320 ###--------------------------------------------------------------------------
325 return '%s(%r, %s, %s)' %
(_clsname(me
), me
.field
, me
.a
, me
.b
)
326 def _repr_pretty_(me
, pp
, cyclep
):
327 ind
= _pp_bgroup_tyname(pp
, me
)
331 pp
.pretty(me
.field
); pp
.text(','); pp
.breakable()
332 pp
.pretty(me
.a
); pp
.text(','); pp
.breakable()
334 pp
.end_group(ind
, ')')
336 return ecpt
.frombuf(me
, s
)
338 return ecpt
.fromraw(me
, s
)
341 _augment(ECCurve
, _tmp
)
347 h ^
= 2*hash(me
.a
) ^
0xffffffff
348 h ^
= 5*hash(me
.b
) ^
0xffffffff
350 _augment(ECPrimeCurve
, _tmp
)
356 h ^
= 2*hash(me
.a
) ^
0xffffffff
357 h ^
= 5*hash(me
.b
) ^
0xffffffff
359 _augment(ECBinCurve
, _tmp
)
363 if not me
: return '%s()' %
_clsname(me
)
364 return '%s(%s, %s)' %
(_clsname(me
), me
.ix
, me
.iy
)
366 if not me
: return 'inf'
367 return '(%s, %s)' %
(me
.ix
, me
.iy
)
368 def _repr_pretty_(me
, pp
, cyclep
):
374 ind
= _pp_bgroup(pp
, '(')
375 pp
.pretty(me
.ix
); pp
.text(','); pp
.breakable()
377 pp
.end_group(ind
, ')')
382 return '%s(curve = %r, G = %r, r = %s, h = %s)' % \
383 (_clsname(me
), me
.curve
, me
.G
, me
.r
, me
.h
)
384 def _repr_pretty_(me
, pp
, cyclep
):
385 ind
= _pp_bgroup_tyname(pp
, me
)
389 _pp_kv(pp
, 'curve', me
.curve
); pp
.text(','); pp
.breakable()
390 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
391 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
392 _pp_kv(pp
, 'h', me
.h
)
393 pp
.end_group(ind
, ')')
397 h ^
= 2*hash(me
.G
) & 0xffffffff
401 _augment(ECInfo
, _tmp
)
405 if not me
: return '%r()' %
(me
.curve
)
406 return '%r(%s, %s)' %
(me
.curve
, me
.x
, me
.y
)
408 if not me
: return 'inf'
409 return '(%s, %s)' %
(me
.x
, me
.y
)
410 def _repr_pretty_(me
, pp
, cyclep
):
416 ind
= _pp_bgroup(pp
, '(')
417 pp
.pretty(me
.x
); pp
.text(','); pp
.breakable()
419 pp
.end_group(ind
, ')')
420 _augment(ECPtCurve
, _tmp
)
422 ###--------------------------------------------------------------------------
426 def __repr__(me
): return '%s(%d)' %
(_clsname(me
), me
.default
)
427 def check(me
, sz
): return True
428 def best(me
, sz
): return sz
429 _augment(KeySZAny
, _tmp
)
433 return '%s(%d, %d, %d, %d)' % \
434 (_clsname(me
), me
.default
, me
.min, me
.max, me
.mod
)
435 def _repr_pretty_(me
, pp
, cyclep
):
436 ind
= _pp_bgroup_tyname(pp
, me
)
440 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
441 pp
.pretty(me
.min); pp
.text(','); pp
.breakable()
442 pp
.pretty(me
.max); pp
.text(','); pp
.breakable()
444 pp
.end_group(ind
, ')')
445 def check(me
, sz
): return me
.min <= sz
<= me
.max and sz % me
.mod
== 0
447 if sz
< me
.min: raise ValueError, 'key too small'
448 elif sz
> me
.max: return me
.max
449 else: return sz
- (sz % me
.mod
)
450 _augment(KeySZRange
, _tmp
)
453 def __repr__(me
): return '%s(%d, %s)' %
(_clsname(me
), me
.default
, me
.set)
454 def _repr_pretty_(me
, pp
, cyclep
):
455 ind
= _pp_bgroup_tyname(pp
, me
)
459 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
460 ind1
= _pp_bgroup(pp
, '{')
461 _pp_commas(pp
, pp
.pretty
, me
.set)
462 pp
.end_group(ind1
, '}')
463 pp
.end_group(ind
, ')')
464 def check(me
, sz
): return sz
in me
.set
468 if found
< i
<= sz
: found
= i
469 if found
< 0: raise ValueError, 'key too small'
471 _augment(KeySZSet
, _tmp
)
473 ###--------------------------------------------------------------------------
474 ### Key data objects.
477 def __repr__(me
): return '%s(%r)' %
(_clsname(me
), me
.name
)
478 _augment(KeyFile
, _tmp
)
481 def __repr__(me
): return '%s(%r)' %
(_clsname(me
), me
.fulltag
)
486 return '%s({%s})' %
(_clsname(me
),
487 ', '.join(['%r: %r' % kv
for kv
in me
.iteritems()]))
488 def _repr_pretty_(me
, pp
, cyclep
):
489 ind
= _pp_bgroup_tyname(pp
, me
)
490 if cyclep
: pp
.text('...')
491 else: _pp_dict(pp
, me
.iteritems())
492 pp
.end_group(ind
, ')')
493 _augment(KeyAttributes
, _tmp
)
497 return '%s(%s, %r)' %
(_clsname(me
),
498 _repr_secret(me
._guts(),
499 not (me
.flags
& KF_NONSECRET
)),
500 me
.writeflags(me
.flags
))
501 def _repr_pretty_(me
, pp
, cyclep
):
502 ind
= _pp_bgroup_tyname(pp
, me
)
506 _pp_secret(pp
, me
._guts(), not (me
.flags
& KF_NONSECRET
))
507 pp
.text(','); pp
.breakable()
508 pp
.pretty(me
.writeflags(me
.flags
))
509 pp
.end_group(ind
, ')')
510 _augment(KeyData
, _tmp
)
513 def _guts(me
): return me
.bin
514 _augment(KeyDataBinary
, _tmp
)
517 def _guts(me
): return me
.ct
518 _augment(KeyDataEncrypted
, _tmp
)
521 def _guts(me
): return me
.mp
522 _augment(KeyDataMP
, _tmp
)
525 def _guts(me
): return me
.str
526 _augment(KeyDataString
, _tmp
)
529 def _guts(me
): return me
.ecpt
530 _augment(KeyDataECPt
, _tmp
)
534 return '%s({%s})' %
(_clsname(me
),
535 ', '.join(['%r: %r' % kv
for kv
in me
.iteritems()]))
536 def _repr_pretty_(me
, pp
, cyclep
):
537 ind
= _pp_bgroup_tyname(pp
, me
, '({ ')
538 if cyclep
: pp
.text('...')
539 else: _pp_dict(pp
, me
.iteritems())
540 pp
.end_group(ind
, ' })')
541 _augment(KeyDataStructured
, _tmp
)
543 ###--------------------------------------------------------------------------
548 return '%s(p = %s, r = %s, g = %s)' %
(_clsname(me
), me
.p
, me
.r
, me
.g
)
549 def _repr_pretty_(me
, pp
, cyclep
):
550 ind
= _pp_bgroup_tyname(pp
, me
)
554 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
555 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
556 _pp_kv(pp
, 'g', me
.g
)
557 pp
.end_group(ind
, ')')
558 _augment(FGInfo
, _tmp
)
561 def group(me
): return PrimeGroup(me
)
562 _augment(DHInfo
, _tmp
)
565 def group(me
): return BinGroup(me
)
566 _augment(BinDHInfo
, _tmp
)
570 return '%s(%r)' %
(_clsname(me
), me
.info
)
571 def _repr_pretty_(me
, pp
, cyclep
):
572 ind
= _pp_bgroup_tyname(pp
, me
)
573 if cyclep
: pp
.text('...')
574 else: pp
.pretty(me
.info
)
575 pp
.end_group(ind
, ')')
576 _augment(Group
, _tmp
)
583 h ^
= 2*hash(info
.r
) & 0xffffffff
584 h ^
= 5*hash(info
.g
) & 0xffffffff
586 def _get_geval(me
, x
): return MP(x
)
587 _augment(PrimeGroup
, _tmp
)
594 h ^
= 2*hash(info
.r
) & 0xffffffff
595 h ^
= 5*hash(info
.g
) & 0xffffffff
597 def _get_geval(me
, x
): return GF(x
)
598 _augment(BinGroup
, _tmp
)
601 def __hash__(me
): return 0x0ec23dab ^
hash(me
.info
)
602 def _get_geval(me
, x
): return x
.toec()
603 _augment(ECGroup
, _tmp
)
607 return '%r(%r)' %
(me
.group
, str(me
))
608 def _repr_pretty_(me
, pp
, cyclep
):
609 pp
.pretty(type(me
)._get_geval(me
))
612 ###--------------------------------------------------------------------------
613 ### RSA encoding techniques.
615 class PKCS1Crypt (object):
616 def __init__(me
, ep
= '', rng
= rand
):
619 def encode(me
, msg
, nbits
):
620 return _base
._p1crypt_encode(msg
, nbits
, me
.ep
, me
.rng
)
621 def decode(me
, ct
, nbits
):
622 return _base
._p1crypt_decode(ct
, nbits
, me
.ep
, me
.rng
)
624 class PKCS1Sig (object):
625 def __init__(me
, ep
= '', rng
= rand
):
628 def encode(me
, msg
, nbits
):
629 return _base
._p1sig_encode(msg
, nbits
, me
.ep
, me
.rng
)
630 def decode(me
, msg
, sig
, nbits
):
631 return _base
._p1sig_decode(msg
, sig
, nbits
, me
.ep
, me
.rng
)
634 def __init__(me
, mgf
= sha_mgf
, hash = sha
, ep
= '', rng
= rand
):
639 def encode(me
, msg
, nbits
):
640 return _base
._oaep_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
641 def decode(me
, ct
, nbits
):
642 return _base
._oaep_decode(ct
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
645 def __init__(me
, mgf
= sha_mgf
, hash = sha
, saltsz
= None, rng
= rand
):
652 def encode(me
, msg
, nbits
):
653 return _base
._pss_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
654 def decode(me
, msg
, sig
, nbits
):
655 return _base
._pss_decode(msg
, sig
, nbits
,
656 me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
659 def encrypt(me
, msg
, enc
):
660 return me
.pubop(enc
.encode(msg
, me
.n
.nbits
))
661 def verify(me
, msg
, sig
, enc
):
662 if msg
is None: return enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
664 x
= enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
665 return x
is None or x
== msg
669 return '%s(n = %r, e = %r)' %
(_clsname(me
), me
.n
, me
.e
)
670 def _repr_pretty_(me
, pp
, cyclep
):
671 ind
= _pp_bgroup_tyname(pp
, me
)
675 _pp_kv(pp
, 'n', me
.n
); pp
.text(','); pp
.breakable()
676 _pp_kv(pp
, 'e', me
.e
)
677 pp
.end_group(ind
, ')')
678 _augment(RSAPub
, _tmp
)
681 def decrypt(me
, ct
, enc
): return enc
.decode(me
.privop(ct
), me
.n
.nbits
)
682 def sign(me
, msg
, enc
): return me
.privop(enc
.encode(msg
, me
.n
.nbits
))
684 return '%s(n = %r, e = %r, d = %s, ' \
685 'p = %s, q = %s, dp = %s, dq = %s, q_inv = %s)' % \
686 (_clsname(me
), me
.n
, me
.e
,
687 _repr_secret(me
.d
), _repr_secret(me
.p
), _repr_secret(me
.q
),
688 _repr_secret(me
.dp
), _repr_secret(me
.dq
), _repr_secret(me
.q_inv
))
689 def _repr_pretty_(me
, pp
, cyclep
):
690 ind
= _pp_bgroup_tyname(pp
, me
)
694 _pp_kv(pp
, 'n', me
.n
); pp
.text(','); pp
.breakable()
695 _pp_kv(pp
, 'e', me
.e
); pp
.text(','); pp
.breakable()
696 _pp_kv(pp
, 'd', me
.d
, secretp
= True); pp
.text(','); pp
.breakable()
697 _pp_kv(pp
, 'p', me
.p
, secretp
= True); pp
.text(','); pp
.breakable()
698 _pp_kv(pp
, 'q', me
.q
, secretp
= True); pp
.text(','); pp
.breakable()
699 _pp_kv(pp
, 'dp', me
.dp
, secretp
= True); pp
.text(','); pp
.breakable()
700 _pp_kv(pp
, 'dq', me
.dq
, secretp
= True); pp
.text(','); pp
.breakable()
701 _pp_kv(pp
, 'q_inv', me
.q_inv
, secretp
= True)
702 pp
.end_group(ind
, ')')
703 _augment(RSAPriv
, _tmp
)
705 ###--------------------------------------------------------------------------
706 ### DSA and related schemes.
709 def __repr__(me
): return '%s(G = %r, p = %r)' %
(_clsname(me
), me
.G
, me
.p
)
710 def _repr_pretty_(me
, pp
, cyclep
):
711 ind
= _pp_bgroup_tyname(pp
, me
)
715 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
716 _pp_kv(pp
, 'p', me
.p
)
717 pp
.end_group(ind
, ')')
718 _augment(DSAPub
, _tmp
)
719 _augment(KCDSAPub
, _tmp
)
722 def __repr__(me
): return '%s(G = %r, u = %s, p = %r)' % \
723 (_clsname(me
), me
.G
, _repr_secret(me
.u
), me
.p
)
724 def _repr_pretty_(me
, pp
, cyclep
):
725 ind
= _pp_bgroup_tyname(pp
, me
)
729 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
730 _pp_kv(pp
, 'u', me
.u
, True); pp
.text(','); pp
.breakable()
731 _pp_kv(pp
, 'p', me
.p
)
732 pp
.end_group(ind
, ')')
733 _augment(DSAPriv
, _tmp
)
734 _augment(KCDSAPriv
, _tmp
)
736 ###--------------------------------------------------------------------------
737 ### Bernstein's elliptic curve crypto and related schemes.
739 X25519_BASE
= MP(9).storel(32)
740 X448_BASE
= MP(5).storel(56)
742 Z128
= ByteString
.zero(16)
744 class _BoxyPub (object):
745 def __init__(me
, pub
, *args
, **kw
):
746 if len(pub
) != me
._PUBSZ
: raise ValueError, 'bad public key'
747 super(_BoxyPub
, me
).__init__(*args
, **kw
)
749 def __repr__(me
): return '%s(pub = %r)' %
(_clsname(me
), me
.pub
)
750 def _repr_pretty_(me
, pp
, cyclep
):
751 ind
= _pp_bgroup_tyname(pp
, me
)
755 _pp_kv(pp
, 'pub', me
.pub
)
756 pp
.end_group(ind
, ')')
758 class _BoxyPriv (_BoxyPub
):
759 def __init__(me
, priv
, pub
= None, *args
, **kw
):
760 if len(priv
) != me
._KEYSZ
: raise ValueError, 'bad private key'
761 if pub
is None: pub
= me
._op(priv
, me
._BASE
)
762 super(_BoxyPriv
, me
).__init__(pub
= pub
, *args
, **kw
)
764 def agree(me
, you
): return me
._op(me
.priv
, you
.pub
)
765 def boxkey(me
, recip
):
766 return me
._hashkey(me
.agree(recip
))
767 def box(me
, recip
, n
, m
):
768 return secret_box(me
.boxkey(recip
), n
, m
)
769 def unbox(me
, recip
, n
, c
):
770 return secret_unbox(me
.boxkey(recip
), n
, c
)
771 def __repr__(me
): return '%s(priv = %s, pub = %r)' % \
772 (_clsname(me
), _repr_secret(me
.priv
), me
.pub
)
773 def _repr_pretty_(me
, pp
, cyclep
):
774 ind
= _pp_bgroup_tyname(pp
, me
)
778 _pp_kv(pp
, 'priv', me
.priv
, True); pp
.text(','); pp
.breakable()
779 _pp_kv(pp
, 'pub', me
.pub
)
780 pp
.end_group(ind
, ')')
782 class X25519Pub (_BoxyPub
):
783 _PUBSZ
= X25519_PUBSZ
786 class X25519Priv (_BoxyPriv
, X25519Pub
):
787 _KEYSZ
= X25519_KEYSZ
788 def _op(me
, k
, X
): return x25519(k
, X
)
789 def _hashkey(me
, z
): return hsalsa20_prf(z
, Z128
)
791 class X448Pub (_BoxyPub
):
795 class X448Priv (_BoxyPriv
, X448Pub
):
797 def _op(me
, k
, X
): return x448(k
, X
)
798 ##def _hashkey(me, z): return ???
800 class Ed25519Pub (object):
801 def __init__(me
, pub
):
803 def verify(me
, msg
, sig
):
804 return ed25519_verify(me
.pub
, msg
, sig
)
806 class Ed25519Priv (Ed25519Pub
):
807 def __init__(me
, priv
):
809 Ed25519Pub
.__init__(me
, ed25519_pubkey(priv
))
811 return ed25519_sign(me
.priv
, msg
, pub
= me
.pub
)
813 def generate(cls
, rng
= rand
):
814 return cls(rng
.block(ED25519_KEYSZ
))
816 ###--------------------------------------------------------------------------
817 ### Built-in named curves and prime groups.
819 class _groupmap (object):
820 def __init__(me
, map, nth
):
823 me
._n
= max(map.values()) + 1
826 return '{%s}' %
', '.join(['%r: %r' % kv
for kv
in me
.iteritems()])
827 def _repr_pretty_(me
, pp
, cyclep
):
828 ind
= _pp_bgroup(pp
, '{ ')
829 if cyclep
: pp
.text('...')
830 else: _pp_dict(pp
, me
.iteritems())
831 pp
.end_group(ind
, ' }')
834 def __contains__(me
, k
):
836 def __getitem__(me
, k
):
841 def __setitem__(me
, k
, v
):
842 raise TypeError, "immutable object"
854 return [k
for k
in me
]
856 return [me
[k
] for k
in me
]
858 return [(k
, me
[k
]) for k
in me
]
859 eccurves
= _groupmap(_base
._eccurves
, ECInfo
._curven
)
860 primegroups
= _groupmap(_base
._pgroups
, DHInfo
._groupn
)
861 bingroups
= _groupmap(_base
._bingroups
, BinDHInfo
._groupn
)
863 ###--------------------------------------------------------------------------
864 ### Prime number generation.
866 class PrimeGenEventHandler (object):
867 def pg_begin(me
, ev
):
871 def pg_abort(me
, ev
):
878 class SophieGermainStepJump (object):
879 def pg_begin(me
, ev
):
880 me
.lf
= PrimeFilter(ev
.x
)
881 me
.hf
= me
.lf
.muladd(2, 1)
887 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
889 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
892 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
899 class SophieGermainStepper (SophieGermainStepJump
):
900 def __init__(me
, step
):
907 class SophieGermainJumper (SophieGermainStepJump
):
908 def __init__(me
, jump
):
909 me
.ljump
= PrimeFilter(jump
);
910 me
.hjump
= me
.ljump
.muladd(2, 0)
917 SophieGermainStepJump
.pg_done(me
, ev
)
919 class SophieGermainTester (object):
922 def pg_begin(me
, ev
):
923 me
.lr
= RabinMiller(ev
.x
)
924 me
.hr
= RabinMiller(2 * ev
.x
+ 1)
926 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
927 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
929 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
930 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
932 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
939 class PrimitiveStepper (PrimeGenEventHandler
):
945 def pg_begin(me
, ev
):
946 me
.i
= iter(smallprimes
)
949 class PrimitiveTester (PrimeGenEventHandler
):
950 def __init__(me
, mod
, hh
= [], exp
= None):
956 if me
.exp
is not None:
957 x
= me
.mod
.exp(x
, me
.exp
)
958 if x
== 1: return PGEN_FAIL
960 if me
.mod
.exp(x
, h
) == 1: return PGEN_FAIL
964 class SimulStepper (PrimeGenEventHandler
):
965 def __init__(me
, mul
= 2, add
= 1, step
= 2):
969 def _stepfn(me
, step
):
971 raise ValueError, 'step must be positive'
973 return lambda f
: f
.step(step
)
974 j
= PrimeFilter(step
)
975 return lambda f
: f
.jump(j
)
976 def pg_begin(me
, ev
):
978 me
.lf
= PrimeFilter(x
)
979 me
.hf
= PrimeFilter(x
* me
.mul
+ me
.add
)
980 me
.lstep
= me
._stepfn(me
.step
)
981 me
.hstep
= me
._stepfn(me
.step
* me
.mul
)
982 SimulStepper
._cont(me
, ev
)
990 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
992 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
995 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
1004 class SimulTester (PrimeGenEventHandler
):
1005 def __init__(me
, mul
= 2, add
= 1):
1008 def pg_begin(me
, ev
):
1010 me
.lr
= RabinMiller(x
)
1011 me
.hr
= RabinMiller(x
* me
.mul
+ me
.add
)
1013 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
1014 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
1016 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
1017 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
1019 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
1022 def pg_done(me
, ev
):
1026 def sgprime(start
, step
= 2, name
= 'p', event
= pgen_nullev
, nsteps
= 0):
1028 return pgen(start
, name
, SimulStepper(step
= step
), SimulTester(), event
,
1029 nsteps
, RabinMiller
.iters(start
.nbits
))
1031 def findprimitive(mod
, hh
= [], exp
= None, name
= 'g', event
= pgen_nullev
):
1032 return pgen(0, name
, PrimitiveStepper(), PrimitiveTester(mod
, hh
, exp
),
1035 def kcdsaprime(pbits
, qbits
, rng
= rand
,
1036 event
= pgen_nullev
, name
= 'p', nsteps
= 0):
1037 hbits
= pbits
- qbits
1038 h
= pgen(rng
.mp(hbits
, 1), name
+ ' [h]',
1039 PrimeGenStepper(2), PrimeGenTester(),
1040 event
, nsteps
, RabinMiller
.iters(hbits
))
1041 q
= pgen(rng
.mp(qbits
, 1), name
, SimulStepper(2 * h
, 1, 2),
1042 SimulTester(2 * h
, 1), event
, nsteps
, RabinMiller
.iters(qbits
))
1046 #----- That's all, folks ----------------------------------------------------