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 ['MP', 'GF', 'Field',
60 'ECPt', 'ECPtCurve', 'ECCurve', 'ECInfo',
61 'DHInfo', 'BinDHInfo', 'RSAPriv', 'BBSPriv',
62 'PrimeFilter', 'RabinMiller',
70 setattr(c
, j
[plen
:], classmethod(b
[j
]))
71 for i
in [gcciphers
, gchashes
, gcmacs
, gcprps
]:
72 for c
in i
.itervalues():
73 d
[_fixname(c
.name
)] = c
74 for c
in gccrands
.itervalues():
75 d
[_fixname(c
.name
+ 'rand')] = c
78 ## A handy function for our work: add the methods of a named class to an
79 ## existing class. This is how we write the Python-implemented parts of our
84 if type(a
) is _types
.MethodType
:
86 elif type(a
) not in (_types
.FunctionType
, staticmethod, classmethod):
90 ## Parsing functions tend to return the object parsed and the remainder of
91 ## the input. This checks that the remainder is input and, if so, returns
96 raise SyntaxError, 'junk at end of string'
99 ## Some pretty-printing utilities.
100 PRINT_SECRETS
= False
101 def _clsname(me
): return type(me
).__name__
102 def _repr_secret(thing
, secretp
= True):
103 if not secretp
or PRINT_SECRETS
: return repr(thing
)
104 else: return '#<SECRET>'
105 def _pp_str(me
, pp
, cyclep
): pp
.text(cyclep
and '...' or str(me
))
106 def _pp_secret(pp
, thing
, secretp
= True):
107 if not secretp
or PRINT_SECRETS
: pp
.pretty(thing
)
108 else: pp
.text('#<SECRET>')
109 def _pp_bgroup(pp
, text
):
111 pp
.begin_group(ind
, text
)
113 def _pp_bgroup_tyname(pp
, obj
, open = '('):
114 return _pp_bgroup(pp
, _clsname(obj
) + open)
115 def _pp_kv(pp
, k
, v
, secretp
= False):
116 ind
= _pp_bgroup(pp
, k
+ ' = ')
117 _pp_secret(pp
, v
, secretp
)
118 pp
.end_group(ind
, '')
119 def _pp_commas(pp
, printfn
, items
):
122 if firstp
: firstp
= False
123 else: pp
.text(','); pp
.breakable()
125 def _pp_dict(pp
, items
):
135 _pp_commas(pp
, p
, items
)
137 ###--------------------------------------------------------------------------
142 return ByteString(_unhexify(x
))
143 fromhex
= staticmethod(fromhex
)
147 return 'bytes(%r)' %
hex(me
)
148 _augment(ByteString
, _tmp
)
149 ByteString
.__hash__
= str.__hash__
150 bytes
= ByteString
.fromhex
152 ###--------------------------------------------------------------------------
158 return ctstreq(h
, hh
)
159 _augment(GHash
, _tmp
)
160 _augment(Poly1305Hash
, _tmp
)
162 ###--------------------------------------------------------------------------
163 ### NaCl `secretbox'.
165 def secret_box(k
, n
, m
):
166 E
= xsalsa20(k
).setiv(n
)
167 r
= E
.enczero(poly1305
.keysz
.default
)
168 s
= E
.enczero(poly1305
.masksz
)
170 t
= poly1305(r
)(s
).hash(y
).done()
171 return ByteString(t
+ y
)
173 def secret_unbox(k
, n
, c
):
174 E
= xsalsa20(k
).setiv(n
)
175 r
= E
.enczero(poly1305
.keysz
.default
)
176 s
= E
.enczero(poly1305
.masksz
)
177 y
= c
[poly1305
.tagsz
:]
178 if not poly1305(r
)(s
).hash(y
).check(c
[0:poly1305
.tagsz
]):
179 raise ValueError, 'decryption failed'
180 return E
.decrypt(c
[poly1305
.tagsz
:])
182 ###--------------------------------------------------------------------------
183 ### Multiprecision integers and binary polynomials.
186 if isinstance(x
, BaseRat
): return x
._n
, x
._d
188 class BaseRat (object):
189 """Base class implementing fields of fractions over Euclidean domains."""
190 def __new__(cls
, a
, b
):
191 a
, b
= cls
.RING(a
), cls
.RING(b
)
195 me
= super(BaseRat
, cls
).__new__(cls
)
200 def numer(me
): return me
._n
202 def denom(me
): return me
._d
203 def __str__(me
): return '%s/%s' %
(me
._n
, me
._d
)
204 def __repr__(me
): return '%s(%s, %s)' %
(_clsname(me
), me
._n
, me
._d
)
205 _repr_pretty_
= _pp_str
207 def __add__(me
, you
):
208 n
, d
= _split_rat(you
)
209 return type(me
)(me
._n
*d
+ n
*me
._d
, d
*me
._d
)
211 def __sub__(me
, you
):
212 n
, d
= _split_rat(you
)
213 return type(me
)(me
._n
*d
- n
*me
._d
, d
*me
._d
)
214 def __rsub__(me
, you
):
215 n
, d
= _split_rat(you
)
216 return type(me
)(n
*me
._d
- me
._n
*d
, d
*me
._d
)
217 def __mul__(me
, you
):
218 n
, d
= _split_rat(you
)
219 return type(me
)(me
._n
*n
, me
._d
*d
)
220 def __div__(me
, you
):
221 n
, d
= _split_rat(you
)
222 return type(me
)(me
._n
*d
, me
._d
*n
)
223 def __rdiv__(me
, you
):
224 n
, d
= _split_rat(you
)
225 return type(me
)(me
._d
*n
, me
._n
*d
)
226 def __cmp__(me
, you
):
227 n
, d
= _split_rat(you
)
228 return type(me
)(me
._n
*d
, n
*me
._d
)
229 def __rcmp__(me
, you
):
230 n
, d
= _split_rat(you
)
231 return cmp(n
*me
._d
, me
._n
*d
)
233 class IntRat (BaseRat
):
236 class GFRat (BaseRat
):
240 def negp(x
): return x
< 0
241 def posp(x
): return x
> 0
242 def zerop(x
): return x
== 0
243 def oddp(x
): return x
.testbit(0)
244 def evenp(x
): return not x
.testbit(0)
245 def mont(x
): return MPMont(x
)
246 def barrett(x
): return MPBarrett(x
)
247 def reduce(x
): return MPReduce(x
)
248 def __div__(me
, you
): return IntRat(me
, you
)
249 def __rdiv__(me
, you
): return IntRat(you
, me
)
250 _repr_pretty_
= _pp_str
254 def zerop(x
): return x
== 0
255 def reduce(x
): return GFReduce(x
)
256 def trace(x
, y
): return x
.reduce().trace(y
)
257 def halftrace(x
, y
): return x
.reduce().halftrace(y
)
258 def modsqrt(x
, y
): return x
.reduce().sqrt(y
)
259 def quadsolve(x
, y
): return x
.reduce().quadsolve(y
)
260 def __div__(me
, you
): return GFRat(me
, you
)
261 def __rdiv__(me
, you
): return GFRat(you
, me
)
262 _repr_pretty_
= _pp_str
267 'product(ITERABLE) or product(I, ...) -> PRODUCT'
268 return MPMul(*arg
).done()
269 product
= staticmethod(product
)
270 _augment(MPMul
, _tmp
)
272 ###--------------------------------------------------------------------------
276 def fromstring(str): return _checkend(Field
.parse(str))
277 fromstring
= staticmethod(fromstring
)
278 _augment(Field
, _tmp
)
281 def __repr__(me
): return '%s(%sL)' %
(_clsname(me
), me
.p
)
282 def __hash__(me
): return 0x114401de ^
hash(me
.p
)
283 def _repr_pretty_(me
, pp
, cyclep
):
284 ind
= _pp_bgroup_tyname(pp
, me
)
285 if cyclep
: pp
.text('...')
286 else: pp
.pretty(me
.p
)
287 pp
.end_group(ind
, ')')
288 def ec(me
, a
, b
): return ECPrimeProjCurve(me
, a
, b
)
289 _augment(PrimeField
, _tmp
)
292 def __repr__(me
): return '%s(%#xL)' %
(_clsname(me
), me
.p
)
293 def ec(me
, a
, b
): return ECBinProjCurve(me
, a
, b
)
294 def _repr_pretty_(me
, pp
, cyclep
):
295 ind
= _pp_bgroup_tyname(pp
, me
)
296 if cyclep
: pp
.text('...')
297 else: pp
.text('%#x' % me
.p
)
298 pp
.end_group(ind
, ')')
299 _augment(BinField
, _tmp
)
302 def __hash__(me
): return 0x23e4701c ^
hash(me
.p
)
303 _augment(BinPolyField
, _tmp
)
309 h ^
= 2*hash(me
.beta
) & 0xffffffff
311 _augment(BinNormField
, _tmp
)
314 def __str__(me
): return str(me
.value
)
315 def __repr__(me
): return '%s(%s)' %
(repr(me
.field
), repr(me
.value
))
316 _repr_pretty_
= _pp_str
319 ###--------------------------------------------------------------------------
324 return '%s(%r, %s, %s)' %
(_clsname(me
), me
.field
, me
.a
, me
.b
)
325 def _repr_pretty_(me
, pp
, cyclep
):
326 ind
= _pp_bgroup_tyname(pp
, me
)
330 pp
.pretty(me
.field
); pp
.text(','); pp
.breakable()
331 pp
.pretty(me
.a
); pp
.text(','); pp
.breakable()
333 pp
.end_group(ind
, ')')
335 return ecpt
.frombuf(me
, s
)
337 return ecpt
.fromraw(me
, s
)
340 _augment(ECCurve
, _tmp
)
346 h ^
= 2*hash(me
.a
) ^
0xffffffff
347 h ^
= 5*hash(me
.b
) ^
0xffffffff
349 _augment(ECPrimeCurve
, _tmp
)
355 h ^
= 2*hash(me
.a
) ^
0xffffffff
356 h ^
= 5*hash(me
.b
) ^
0xffffffff
358 _augment(ECBinCurve
, _tmp
)
362 if not me
: return '%s()' %
_clsname(me
)
363 return '%s(%s, %s)' %
(_clsname(me
), me
.ix
, me
.iy
)
365 if not me
: return 'inf'
366 return '(%s, %s)' %
(me
.ix
, me
.iy
)
367 def _repr_pretty_(me
, pp
, cyclep
):
373 ind
= _pp_bgroup(pp
, '(')
374 pp
.pretty(me
.ix
); pp
.text(','); pp
.breakable()
376 pp
.end_group(ind
, ')')
381 return '%s(curve = %r, G = %r, r = %s, h = %s)' % \
382 (_clsname(me
), me
.curve
, me
.G
, me
.r
, me
.h
)
383 def _repr_pretty_(me
, pp
, cyclep
):
384 ind
= _pp_bgroup_tyname(pp
, me
)
388 _pp_kv(pp
, 'curve', me
.curve
); pp
.text(','); pp
.breakable()
389 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
390 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
391 _pp_kv(pp
, 'h', me
.h
)
392 pp
.end_group(ind
, ')')
396 h ^
= 2*hash(me
.G
) & 0xffffffff
400 _augment(ECInfo
, _tmp
)
404 if not me
: return '%r()' %
(me
.curve
)
405 return '%r(%s, %s)' %
(me
.curve
, me
.x
, me
.y
)
407 if not me
: return 'inf'
408 return '(%s, %s)' %
(me
.x
, me
.y
)
409 def _repr_pretty_(me
, pp
, cyclep
):
415 ind
= _pp_bgroup(pp
, '(')
416 pp
.pretty(me
.x
); pp
.text(','); pp
.breakable()
418 pp
.end_group(ind
, ')')
419 _augment(ECPtCurve
, _tmp
)
421 ###--------------------------------------------------------------------------
425 def __repr__(me
): return '%s(%d)' %
(_clsname(me
), me
.default
)
426 def check(me
, sz
): return True
427 def best(me
, sz
): return sz
428 _augment(KeySZAny
, _tmp
)
432 return '%s(%d, %d, %d, %d)' % \
433 (_clsname(me
), me
.default
, me
.min, me
.max, me
.mod
)
434 def _repr_pretty_(me
, pp
, cyclep
):
435 ind
= _pp_bgroup_tyname(pp
, me
)
439 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
440 pp
.pretty(me
.min); pp
.text(','); pp
.breakable()
441 pp
.pretty(me
.max); pp
.text(','); pp
.breakable()
443 pp
.end_group(ind
, ')')
444 def check(me
, sz
): return me
.min <= sz
<= me
.max and sz % me
.mod
== 0
446 if sz
< me
.min: raise ValueError, 'key too small'
447 elif sz
> me
.max: return me
.max
448 else: return sz
- (sz % me
.mod
)
449 _augment(KeySZRange
, _tmp
)
452 def __repr__(me
): return '%s(%d, %s)' %
(_clsname(me
), me
.default
, me
.set)
453 def _repr_pretty_(me
, pp
, cyclep
):
454 ind
= _pp_bgroup_tyname(pp
, me
)
458 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
459 ind1
= _pp_bgroup(pp
, '{')
460 _pp_commas(pp
, pp
.pretty
, me
.set)
461 pp
.end_group(ind1
, '}')
462 pp
.end_group(ind
, ')')
463 def check(me
, sz
): return sz
in me
.set
467 if found
< i
<= sz
: found
= i
468 if found
< 0: raise ValueError, 'key too small'
470 _augment(KeySZSet
, _tmp
)
472 ###--------------------------------------------------------------------------
473 ### Key data objects.
476 def __repr__(me
): return '%s(%r)' %
(_clsname(me
), me
.name
)
477 _augment(KeyFile
, _tmp
)
480 def __repr__(me
): return '%s(%r)' %
(_clsname(me
), me
.fulltag
)
485 return '%s({%s})' %
(_clsname(me
),
486 ', '.join(['%r: %r' % kv
for kv
in me
.iteritems()]))
487 def _repr_pretty_(me
, pp
, cyclep
):
488 ind
= _pp_bgroup_tyname(pp
, me
)
489 if cyclep
: pp
.text('...')
490 else: _pp_dict(pp
, me
.iteritems())
491 pp
.end_group(ind
, ')')
492 _augment(KeyAttributes
, _tmp
)
496 return '%s(%s, %r)' %
(_clsname(me
),
497 _repr_secret(me
._guts(),
498 not (me
.flags
& KF_NONSECRET
)),
499 me
.writeflags(me
.flags
))
500 def _repr_pretty_(me
, pp
, cyclep
):
501 ind
= _pp_bgroup_tyname(pp
, me
)
505 _pp_secret(pp
, me
._guts(), not (me
.flags
& KF_NONSECRET
))
506 pp
.text(','); pp
.breakable()
507 pp
.pretty(me
.writeflags(me
.flags
))
508 pp
.end_group(ind
, ')')
509 _augment(KeyData
, _tmp
)
512 def _guts(me
): return me
.bin
513 _augment(KeyDataBinary
, _tmp
)
516 def _guts(me
): return me
.ct
517 _augment(KeyDataEncrypted
, _tmp
)
520 def _guts(me
): return me
.mp
521 _augment(KeyDataMP
, _tmp
)
524 def _guts(me
): return me
.str
525 _augment(KeyDataString
, _tmp
)
528 def _guts(me
): return me
.ecpt
529 _augment(KeyDataECPt
, _tmp
)
533 return '%s({%s})' %
(_clsname(me
),
534 ', '.join(['%r: %r' % kv
for kv
in me
.iteritems()]))
535 def _repr_pretty_(me
, pp
, cyclep
):
536 ind
= _pp_bgroup_tyname(pp
, me
, '({ ')
537 if cyclep
: pp
.text('...')
538 else: _pp_dict(pp
, me
.iteritems())
539 pp
.end_group(ind
, ' })')
540 _augment(KeyDataStructured
, _tmp
)
542 ###--------------------------------------------------------------------------
547 return '%s(p = %s, r = %s, g = %s)' %
(_clsname(me
), me
.p
, me
.r
, me
.g
)
548 def _repr_pretty_(me
, pp
, cyclep
):
549 ind
= _pp_bgroup_tyname(pp
, me
)
553 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
554 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
555 _pp_kv(pp
, 'g', me
.g
)
556 pp
.end_group(ind
, ')')
557 _augment(FGInfo
, _tmp
)
560 def group(me
): return PrimeGroup(me
)
561 _augment(DHInfo
, _tmp
)
564 def group(me
): return BinGroup(me
)
565 _augment(BinDHInfo
, _tmp
)
569 return '%s(%r)' %
(_clsname(me
), me
.info
)
570 def _repr_pretty_(me
, pp
, cyclep
):
571 ind
= _pp_bgroup_tyname(pp
, me
)
572 if cyclep
: pp
.text('...')
573 else: pp
.pretty(me
.info
)
574 pp
.end_group(ind
, ')')
575 _augment(Group
, _tmp
)
582 h ^
= 2*hash(info
.r
) & 0xffffffff
583 h ^
= 5*hash(info
.g
) & 0xffffffff
585 def _get_geval(me
, x
): return MP(x
)
586 _augment(PrimeGroup
, _tmp
)
593 h ^
= 2*hash(info
.r
) & 0xffffffff
594 h ^
= 5*hash(info
.g
) & 0xffffffff
596 def _get_geval(me
, x
): return GF(x
)
597 _augment(BinGroup
, _tmp
)
600 def __hash__(me
): return 0x0ec23dab ^
hash(me
.info
)
601 def _get_geval(me
, x
): return x
.toec()
602 _augment(ECGroup
, _tmp
)
606 return '%r(%r)' %
(me
.group
, str(me
))
607 def _repr_pretty_(me
, pp
, cyclep
):
608 pp
.pretty(type(me
)._get_geval(me
))
611 ###--------------------------------------------------------------------------
612 ### RSA encoding techniques.
614 class PKCS1Crypt (object):
615 def __init__(me
, ep
= '', rng
= rand
):
618 def encode(me
, msg
, nbits
):
619 return _base
._p1crypt_encode(msg
, nbits
, me
.ep
, me
.rng
)
620 def decode(me
, ct
, nbits
):
621 return _base
._p1crypt_decode(ct
, nbits
, me
.ep
, me
.rng
)
623 class PKCS1Sig (object):
624 def __init__(me
, ep
= '', rng
= rand
):
627 def encode(me
, msg
, nbits
):
628 return _base
._p1sig_encode(msg
, nbits
, me
.ep
, me
.rng
)
629 def decode(me
, msg
, sig
, nbits
):
630 return _base
._p1sig_decode(msg
, sig
, nbits
, me
.ep
, me
.rng
)
633 def __init__(me
, mgf
= sha_mgf
, hash = sha
, ep
= '', rng
= rand
):
638 def encode(me
, msg
, nbits
):
639 return _base
._oaep_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
640 def decode(me
, ct
, nbits
):
641 return _base
._oaep_decode(ct
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
644 def __init__(me
, mgf
= sha_mgf
, hash = sha
, saltsz
= None, rng
= rand
):
651 def encode(me
, msg
, nbits
):
652 return _base
._pss_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
653 def decode(me
, msg
, sig
, nbits
):
654 return _base
._pss_decode(msg
, sig
, nbits
,
655 me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
658 def encrypt(me
, msg
, enc
):
659 return me
.pubop(enc
.encode(msg
, me
.n
.nbits
))
660 def verify(me
, msg
, sig
, enc
):
661 if msg
is None: return enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
663 x
= enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
664 return x
is None or x
== msg
668 return '%s(n = %r, e = %r)' %
(_clsname(me
), me
.n
, me
.e
)
669 def _repr_pretty_(me
, pp
, cyclep
):
670 ind
= _pp_bgroup_tyname(pp
, me
)
674 _pp_kv(pp
, 'n', me
.n
); pp
.text(','); pp
.breakable()
675 _pp_kv(pp
, 'e', me
.e
)
676 pp
.end_group(ind
, ')')
677 _augment(RSAPub
, _tmp
)
680 def decrypt(me
, ct
, enc
): return enc
.decode(me
.privop(ct
), me
.n
.nbits
)
681 def sign(me
, msg
, enc
): return me
.privop(enc
.encode(msg
, me
.n
.nbits
))
683 return '%s(n = %r, e = %r, d = %s, ' \
684 'p = %s, q = %s, dp = %s, dq = %s, q_inv = %s)' % \
685 (_clsname(me
), me
.n
, me
.e
,
686 _repr_secret(me
.d
), _repr_secret(me
.p
), _repr_secret(me
.q
),
687 _repr_secret(me
.dp
), _repr_secret(me
.dq
), _repr_secret(me
.q_inv
))
688 def _repr_pretty_(me
, pp
, cyclep
):
689 ind
= _pp_bgroup_tyname(pp
, me
)
693 _pp_kv(pp
, 'n', me
.n
); pp
.text(','); pp
.breakable()
694 _pp_kv(pp
, 'e', me
.e
); pp
.text(','); pp
.breakable()
695 _pp_kv(pp
, 'd', me
.d
, secretp
= True); pp
.text(','); pp
.breakable()
696 _pp_kv(pp
, 'p', me
.p
, secretp
= True); pp
.text(','); pp
.breakable()
697 _pp_kv(pp
, 'q', me
.q
, secretp
= True); pp
.text(','); pp
.breakable()
698 _pp_kv(pp
, 'dp', me
.dp
, secretp
= True); pp
.text(','); pp
.breakable()
699 _pp_kv(pp
, 'dq', me
.dq
, secretp
= True); pp
.text(','); pp
.breakable()
700 _pp_kv(pp
, 'q_inv', me
.q_inv
, secretp
= True)
701 pp
.end_group(ind
, ')')
702 _augment(RSAPriv
, _tmp
)
704 ###--------------------------------------------------------------------------
705 ### DSA and related schemes.
708 def __repr__(me
): return '%s(G = %r, p = %r)' %
(_clsname(me
), me
.G
, me
.p
)
709 def _repr_pretty_(me
, pp
, cyclep
):
710 ind
= _pp_bgroup_tyname(pp
, me
)
714 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
715 _pp_kv(pp
, 'p', me
.p
)
716 pp
.end_group(ind
, ')')
717 _augment(DSAPub
, _tmp
)
718 _augment(KCDSAPub
, _tmp
)
721 def __repr__(me
): return '%s(G = %r, u = %s, p = %r)' % \
722 (_clsname(me
), me
.G
, _repr_secret(me
.u
), me
.p
)
723 def _repr_pretty_(me
, pp
, cyclep
):
724 ind
= _pp_bgroup_tyname(pp
, me
)
728 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
729 _pp_kv(pp
, 'u', me
.u
, True); pp
.text(','); pp
.breakable()
730 _pp_kv(pp
, 'p', me
.p
)
731 pp
.end_group(ind
, ')')
732 _augment(DSAPriv
, _tmp
)
733 _augment(KCDSAPriv
, _tmp
)
735 ###--------------------------------------------------------------------------
736 ### Bernstein's elliptic curve crypto and related schemes.
739 bytes('0900000000000000000000000000000000000000000000000000000000000000')
742 bytes('05000000000000000000000000000000000000000000000000000000'
743 '00000000000000000000000000000000000000000000000000000000')
745 Z128
= bytes('00000000000000000000000000000000')
747 class _BoxyPub (object):
748 def __init__(me
, pub
, *args
, **kw
):
749 if len(pub
) != me
._PUBSZ
: raise ValueError, 'bad public key'
750 super(_BoxyPub
, me
).__init__(*args
, **kw
)
752 def __repr__(me
): return '%s(pub = %r)' %
(_clsname(me
), me
.pub
)
753 def _repr_pretty_(me
, pp
, cyclep
):
754 ind
= _pp_bgroup_tyname(pp
, me
)
758 _pp_kv(pp
, 'pub', me
.pub
)
759 pp
.end_group(ind
, ')')
761 class _BoxyPriv (_BoxyPub
):
762 def __init__(me
, priv
, pub
= None, *args
, **kw
):
763 if len(priv
) != me
._KEYSZ
: raise ValueError, 'bad private key'
764 if pub
is None: pub
= me
._op(priv
, me
._BASE
)
765 super(_BoxyPriv
, me
).__init__(pub
= pub
, *args
, **kw
)
767 def agree(me
, you
): return me
._op(me
.priv
, you
.pub
)
768 def boxkey(me
, recip
):
769 return me
._hashkey(me
.agree(recip
))
770 def box(me
, recip
, n
, m
):
771 return secret_box(me
.boxkey(recip
), n
, m
)
772 def unbox(me
, recip
, n
, c
):
773 return secret_unbox(me
.boxkey(recip
), n
, c
)
774 def __repr__(me
): return '%s(priv = %s, pub = %r)' % \
775 (_clsname(me
), _repr_secret(me
.priv
), me
.pub
)
776 def _repr_pretty_(me
, pp
, cyclep
):
777 ind
= _pp_bgroup_tyname(pp
, me
)
781 _pp_kv(pp
, 'priv', me
.priv
, True); pp
.text(','); pp
.breakable()
782 _pp_kv(pp
, 'pub', me
.pub
)
783 pp
.end_group(ind
, ')')
785 class X25519Pub (_BoxyPub
):
786 _PUBSZ
= X25519_PUBSZ
789 class X25519Priv (_BoxyPriv
, X25519Pub
):
790 _KEYSZ
= X25519_KEYSZ
791 def _op(me
, k
, X
): return x25519(k
, X
)
792 def _hashkey(me
, z
): return hsalsa20_prf(z
, Z128
)
794 class X448Pub (_BoxyPub
):
798 class X448Priv (_BoxyPriv
, X448Pub
):
800 def _op(me
, k
, X
): return x448(k
, X
)
801 ##def _hashkey(me, z): return ???
803 class Ed25519Pub (object):
804 def __init__(me
, pub
):
806 def verify(me
, msg
, sig
):
807 return ed25519_verify(me
.pub
, msg
, sig
)
809 class Ed25519Priv (Ed25519Pub
):
810 def __init__(me
, priv
):
812 Ed25519Pub
.__init__(me
, ed25519_pubkey(priv
))
814 return ed25519_sign(me
.priv
, msg
, pub
= me
.pub
)
816 def generate(cls
, rng
= rand
):
817 return cls(rng
.block(ED25519_KEYSZ
))
819 ###--------------------------------------------------------------------------
820 ### Built-in named curves and prime groups.
822 class _groupmap (object):
823 def __init__(me
, map, nth
):
826 me
._n
= max(map.values()) + 1
829 return '{%s}' %
', '.join(['%r: %r' % kv
for kv
in me
.iteritems()])
830 def _repr_pretty_(me
, pp
, cyclep
):
831 ind
= _pp_bgroup(pp
, '{ ')
832 if cyclep
: pp
.text('...')
833 else: _pp_dict(pp
, me
.iteritems())
834 pp
.end_group(ind
, ' }')
837 def __contains__(me
, k
):
839 def __getitem__(me
, k
):
844 def __setitem__(me
, k
, v
):
845 raise TypeError, "immutable object"
857 return [k
for k
in me
]
859 return [me
[k
] for k
in me
]
861 return [(k
, me
[k
]) for k
in me
]
862 eccurves
= _groupmap(_base
._eccurves
, ECInfo
._curven
)
863 primegroups
= _groupmap(_base
._pgroups
, DHInfo
._groupn
)
864 bingroups
= _groupmap(_base
._bingroups
, BinDHInfo
._groupn
)
866 ###--------------------------------------------------------------------------
867 ### Prime number generation.
869 class PrimeGenEventHandler (object):
870 def pg_begin(me
, ev
):
874 def pg_abort(me
, ev
):
881 class SophieGermainStepJump (object):
882 def pg_begin(me
, ev
):
883 me
.lf
= PrimeFilter(ev
.x
)
884 me
.hf
= me
.lf
.muladd(2, 1)
890 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
892 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
895 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
902 class SophieGermainStepper (SophieGermainStepJump
):
903 def __init__(me
, step
):
910 class SophieGermainJumper (SophieGermainStepJump
):
911 def __init__(me
, jump
):
912 me
.ljump
= PrimeFilter(jump
);
913 me
.hjump
= me
.ljump
.muladd(2, 0)
920 SophieGermainStepJump
.pg_done(me
, ev
)
922 class SophieGermainTester (object):
925 def pg_begin(me
, ev
):
926 me
.lr
= RabinMiller(ev
.x
)
927 me
.hr
= RabinMiller(2 * ev
.x
+ 1)
929 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
930 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
932 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
933 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
935 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
942 class PrimitiveStepper (PrimeGenEventHandler
):
948 def pg_begin(me
, ev
):
949 me
.i
= iter(smallprimes
)
952 class PrimitiveTester (PrimeGenEventHandler
):
953 def __init__(me
, mod
, hh
= [], exp
= None):
959 if me
.exp
is not None:
960 x
= me
.mod
.exp(x
, me
.exp
)
961 if x
== 1: return PGEN_FAIL
963 if me
.mod
.exp(x
, h
) == 1: return PGEN_FAIL
967 class SimulStepper (PrimeGenEventHandler
):
968 def __init__(me
, mul
= 2, add
= 1, step
= 2):
972 def _stepfn(me
, step
):
974 raise ValueError, 'step must be positive'
976 return lambda f
: f
.step(step
)
977 j
= PrimeFilter(step
)
978 return lambda f
: f
.jump(j
)
979 def pg_begin(me
, ev
):
981 me
.lf
= PrimeFilter(x
)
982 me
.hf
= PrimeFilter(x
* me
.mul
+ me
.add
)
983 me
.lstep
= me
._stepfn(me
.step
)
984 me
.hstep
= me
._stepfn(me
.step
* me
.mul
)
985 SimulStepper
._cont(me
, ev
)
993 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
995 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
998 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
1001 def pg_done(me
, ev
):
1007 class SimulTester (PrimeGenEventHandler
):
1008 def __init__(me
, mul
= 2, add
= 1):
1011 def pg_begin(me
, ev
):
1013 me
.lr
= RabinMiller(x
)
1014 me
.hr
= RabinMiller(x
* me
.mul
+ me
.add
)
1016 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
1017 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
1019 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
1020 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
1022 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
1025 def pg_done(me
, ev
):
1029 def sgprime(start
, step
= 2, name
= 'p', event
= pgen_nullev
, nsteps
= 0):
1031 return pgen(start
, name
, SimulStepper(step
= step
), SimulTester(), event
,
1032 nsteps
, RabinMiller
.iters(start
.nbits
))
1034 def findprimitive(mod
, hh
= [], exp
= None, name
= 'g', event
= pgen_nullev
):
1035 return pgen(0, name
, PrimitiveStepper(), PrimitiveTester(mod
, hh
, exp
),
1038 def kcdsaprime(pbits
, qbits
, rng
= rand
,
1039 event
= pgen_nullev
, name
= 'p', nsteps
= 0):
1040 hbits
= pbits
- qbits
1041 h
= pgen(rng
.mp(hbits
, 1), name
+ ' [h]',
1042 PrimeGenStepper(2), PrimeGenTester(),
1043 event
, nsteps
, RabinMiller
.iters(hbits
))
1044 q
= pgen(rng
.mp(qbits
, 1), name
, SimulStepper(2 * h
, 1, 2),
1045 SimulTester(2 * h
, 1), event
, nsteps
, RabinMiller
.iters(qbits
))
1049 #----- That's all, folks ----------------------------------------------------