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.
87 def _clsname(me
): return type(me
).__name__
88 def _repr_secret(thing
, secretp
= True):
89 if not secretp
or PRINT_SECRETS
: return repr(thing
)
90 else: return '#<SECRET>'
91 def _pp_str(me
, pp
, cyclep
): pp
.text(cyclep
and '...' or str(me
))
92 def _pp_secret(pp
, thing
, secretp
= True):
93 if not secretp
or PRINT_SECRETS
: pp
.pretty(thing
)
94 else: pp
.text('#<SECRET>')
95 def _pp_bgroup(pp
, text
):
97 pp
.begin_group(ind
, text
)
99 def _pp_bgroup_tyname(pp
, obj
, open = '('):
100 return _pp_bgroup(pp
, _clsname(obj
) + open)
101 def _pp_kv(pp
, k
, v
, secretp
= False):
102 ind
= _pp_bgroup(pp
, k
+ ' = ')
103 _pp_secret(pp
, v
, secretp
)
104 pp
.end_group(ind
, '')
105 def _pp_commas(pp
, printfn
, items
):
108 if firstp
: firstp
= False
109 else: pp
.text(','); pp
.breakable()
111 def _pp_dict(pp
, items
):
121 _pp_commas(pp
, p
, items
)
123 ###--------------------------------------------------------------------------
128 return ByteString(_unhexify(x
))
129 fromhex
= staticmethod(fromhex
)
133 return 'bytes(%r)' %
hex(me
)
134 _augment(ByteString
, _tmp
)
135 ByteString
.__hash__
= str.__hash__
136 bytes
= ByteString
.fromhex
138 ###--------------------------------------------------------------------------
144 return ctstreq(h
, hh
)
145 _augment(GHash
, _tmp
)
146 _augment(Poly1305Hash
, _tmp
)
148 ###--------------------------------------------------------------------------
149 ### NaCl `secretbox'.
151 def secret_box(k
, n
, m
):
152 E
= xsalsa20(k
).setiv(n
)
153 r
= E
.enczero(poly1305
.keysz
.default
)
154 s
= E
.enczero(poly1305
.masksz
)
156 t
= poly1305(r
)(s
).hash(y
).done()
157 return ByteString(t
+ y
)
159 def secret_unbox(k
, n
, c
):
160 E
= xsalsa20(k
).setiv(n
)
161 r
= E
.enczero(poly1305
.keysz
.default
)
162 s
= E
.enczero(poly1305
.masksz
)
163 y
= c
[poly1305
.tagsz
:]
164 if not poly1305(r
)(s
).hash(y
).check(c
[0:poly1305
.tagsz
]):
165 raise ValueError, 'decryption failed'
166 return E
.decrypt(c
[poly1305
.tagsz
:])
168 ###--------------------------------------------------------------------------
169 ### Multiprecision integers and binary polynomials.
172 if isinstance(x
, BaseRat
): return x
._n
, x
._d
174 class BaseRat (object):
175 """Base class implementing fields of fractions over Euclidean domains."""
176 def __new__(cls
, a
, b
):
177 a
, b
= cls
.RING(a
), cls
.RING(b
)
181 me
= super(BaseRat
, cls
).__new__(cls
)
186 def numer(me
): return me
._n
188 def denom(me
): return me
._d
189 def __str__(me
): return '%s/%s' %
(me
._n
, me
._d
)
190 def __repr__(me
): return '%s(%s, %s)' %
(_clsname(me
), me
._n
, me
._d
)
191 _repr_pretty_
= _pp_str
193 def __add__(me
, you
):
194 n
, d
= _split_rat(you
)
195 return type(me
)(me
._n
*d
+ n
*me
._d
, d
*me
._d
)
197 def __sub__(me
, you
):
198 n
, d
= _split_rat(you
)
199 return type(me
)(me
._n
*d
- n
*me
._d
, d
*me
._d
)
200 def __rsub__(me
, you
):
201 n
, d
= _split_rat(you
)
202 return type(me
)(n
*me
._d
- me
._n
*d
, d
*me
._d
)
203 def __mul__(me
, you
):
204 n
, d
= _split_rat(you
)
205 return type(me
)(me
._n
*n
, me
._d
*d
)
206 def __div__(me
, you
):
207 n
, d
= _split_rat(you
)
208 return type(me
)(me
._n
*d
, me
._d
*n
)
209 def __rdiv__(me
, you
):
210 n
, d
= _split_rat(you
)
211 return type(me
)(me
._d
*n
, me
._n
*d
)
212 def __cmp__(me
, you
):
213 n
, d
= _split_rat(you
)
214 return type(me
)(me
._n
*d
, n
*me
._d
)
215 def __rcmp__(me
, you
):
216 n
, d
= _split_rat(you
)
217 return cmp(n
*me
._d
, me
._n
*d
)
219 class IntRat (BaseRat
):
222 class GFRat (BaseRat
):
226 def negp(x
): return x
< 0
227 def posp(x
): return x
> 0
228 def zerop(x
): return x
== 0
229 def oddp(x
): return x
.testbit(0)
230 def evenp(x
): return not x
.testbit(0)
231 def mont(x
): return MPMont(x
)
232 def barrett(x
): return MPBarrett(x
)
233 def reduce(x
): return MPReduce(x
)
234 def __div__(me
, you
): return IntRat(me
, you
)
235 def __rdiv__(me
, you
): return IntRat(you
, me
)
236 _repr_pretty_
= _pp_str
240 def zerop(x
): return x
== 0
241 def reduce(x
): return GFReduce(x
)
242 def trace(x
, y
): return x
.reduce().trace(y
)
243 def halftrace(x
, y
): return x
.reduce().halftrace(y
)
244 def modsqrt(x
, y
): return x
.reduce().sqrt(y
)
245 def quadsolve(x
, y
): return x
.reduce().quadsolve(y
)
246 def __div__(me
, you
): return GFRat(me
, you
)
247 def __rdiv__(me
, you
): return GFRat(you
, me
)
248 _repr_pretty_
= _pp_str
253 'product(ITERABLE) or product(I, ...) -> PRODUCT'
254 return MPMul(*arg
).done()
255 product
= staticmethod(product
)
256 _augment(MPMul
, _tmp
)
258 ###--------------------------------------------------------------------------
262 def fromstring(str): return _checkend(Field
.parse(str))
263 fromstring
= staticmethod(fromstring
)
264 _augment(Field
, _tmp
)
267 def __repr__(me
): return '%s(%sL)' %
(_clsname(me
), me
.p
)
268 def __hash__(me
): return 0x114401de ^
hash(me
.p
)
269 def _repr_pretty_(me
, pp
, cyclep
):
270 ind
= _pp_bgroup_tyname(pp
, me
)
271 if cyclep
: pp
.text('...')
272 else: pp
.pretty(me
.p
)
273 pp
.end_group(ind
, ')')
274 def ec(me
, a
, b
): return ECPrimeProjCurve(me
, a
, b
)
275 _augment(PrimeField
, _tmp
)
278 def __repr__(me
): return '%s(%#xL)' %
(_clsname(me
), me
.p
)
279 def ec(me
, a
, b
): return ECBinProjCurve(me
, a
, b
)
280 def _repr_pretty_(me
, pp
, cyclep
):
281 ind
= _pp_bgroup_tyname(pp
, me
)
282 if cyclep
: pp
.text('...')
283 else: pp
.text('%#x' % me
.p
)
284 pp
.end_group(ind
, ')')
285 _augment(BinField
, _tmp
)
288 def __hash__(me
): return 0x23e4701c ^
hash(me
.p
)
289 _augment(BinPolyField
, _tmp
)
295 h ^
= 2*hash(me
.beta
) & 0xffffffff
297 _augment(BinNormField
, _tmp
)
300 def __str__(me
): return str(me
.value
)
301 def __repr__(me
): return '%s(%s)' %
(repr(me
.field
), repr(me
.value
))
302 _repr_pretty_
= _pp_str
305 ###--------------------------------------------------------------------------
310 return '%s(%r, %s, %s)' %
(_clsname(me
), me
.field
, me
.a
, me
.b
)
311 def _repr_pretty_(me
, pp
, cyclep
):
312 ind
= _pp_bgroup_tyname(pp
, me
)
316 pp
.pretty(me
.field
); pp
.text(','); pp
.breakable()
317 pp
.pretty(me
.a
); pp
.text(','); pp
.breakable()
319 pp
.end_group(ind
, ')')
321 return ecpt
.frombuf(me
, s
)
323 return ecpt
.fromraw(me
, s
)
326 _augment(ECCurve
, _tmp
)
332 h ^
= 2*hash(me
.a
) ^
0xffffffff
333 h ^
= 5*hash(me
.b
) ^
0xffffffff
335 _augment(ECPrimeCurve
, _tmp
)
341 h ^
= 2*hash(me
.a
) ^
0xffffffff
342 h ^
= 5*hash(me
.b
) ^
0xffffffff
344 _augment(ECBinCurve
, _tmp
)
348 if not me
: return '%s()' %
_clsname(me
)
349 return '%s(%s, %s)' %
(_clsname(me
), me
.ix
, me
.iy
)
351 if not me
: return 'inf'
352 return '(%s, %s)' %
(me
.ix
, me
.iy
)
353 def _repr_pretty_(me
, pp
, cyclep
):
359 ind
= _pp_bgroup(pp
, '(')
360 pp
.pretty(me
.ix
); pp
.text(','); pp
.breakable()
362 pp
.end_group(ind
, ')')
367 return '%s(curve = %r, G = %r, r = %s, h = %s)' % \
368 (_clsname(me
), me
.curve
, me
.G
, me
.r
, me
.h
)
369 def _repr_pretty_(me
, pp
, cyclep
):
370 ind
= _pp_bgroup_tyname(pp
, me
)
374 _pp_kv(pp
, 'curve', me
.curve
); pp
.text(','); pp
.breakable()
375 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
376 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
377 _pp_kv(pp
, 'h', me
.h
)
378 pp
.end_group(ind
, ')')
382 h ^
= 2*hash(me
.G
) & 0xffffffff
386 _augment(ECInfo
, _tmp
)
390 if not me
: return '%r()' %
(me
.curve
)
391 return '%r(%s, %s)' %
(me
.curve
, me
.x
, me
.y
)
393 if not me
: return 'inf'
394 return '(%s, %s)' %
(me
.x
, me
.y
)
395 def _repr_pretty_(me
, pp
, cyclep
):
401 ind
= _pp_bgroup(pp
, '(')
402 pp
.pretty(me
.x
); pp
.text(','); pp
.breakable()
404 pp
.end_group(ind
, ')')
405 _augment(ECPtCurve
, _tmp
)
407 ###--------------------------------------------------------------------------
411 def __repr__(me
): return '%s(%d)' %
(_clsname(me
), me
.default
)
412 def check(me
, sz
): return True
413 def best(me
, sz
): return sz
414 _augment(KeySZAny
, _tmp
)
418 return '%s(%d, %d, %d, %d)' % \
419 (_clsname(me
), me
.default
, me
.min, me
.max, me
.mod
)
420 def _repr_pretty_(me
, pp
, cyclep
):
421 ind
= _pp_bgroup_tyname(pp
, me
)
425 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
426 pp
.pretty(me
.min); pp
.text(','); pp
.breakable()
427 pp
.pretty(me
.max); pp
.text(','); pp
.breakable()
429 pp
.end_group(ind
, ')')
430 def check(me
, sz
): return me
.min <= sz
<= me
.max and sz % me
.mod
== 0
432 if sz
< me
.min: raise ValueError, 'key too small'
433 elif sz
> me
.max: return me
.max
434 else: return sz
- (sz % me
.mod
)
435 _augment(KeySZRange
, _tmp
)
438 def __repr__(me
): return '%s(%d, %s)' %
(_clsname(me
), me
.default
, me
.set)
439 def _repr_pretty_(me
, pp
, cyclep
):
440 ind
= _pp_bgroup_tyname(pp
, me
)
444 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
445 ind1
= _pp_bgroup(pp
, '{')
446 _pp_commas(pp
, pp
.pretty
, me
.set)
447 pp
.end_group(ind1
, '}')
448 pp
.end_group(ind
, ')')
449 def check(me
, sz
): return sz
in me
.set
453 if found
< i
<= sz
: found
= i
454 if found
< 0: raise ValueError, 'key too small'
456 _augment(KeySZSet
, _tmp
)
458 ###--------------------------------------------------------------------------
459 ### Key data objects.
462 def __repr__(me
): return '%s(%r)' %
(_clsname(me
), me
.name
)
463 _augment(KeyFile
, _tmp
)
466 def __repr__(me
): return '%s(%r)' %
(_clsname(me
), me
.fulltag
)
471 return '%s({%s})' %
(_clsname(me
),
472 ', '.join(['%r: %r' % kv
for kv
in me
.iteritems()]))
473 def _repr_pretty_(me
, pp
, cyclep
):
474 ind
= _pp_bgroup_tyname(pp
, me
)
475 if cyclep
: pp
.text('...')
476 else: _pp_dict(pp
, me
.iteritems())
477 pp
.end_group(ind
, ')')
478 _augment(KeyAttributes
, _tmp
)
482 return '%s(%s, %r)' %
(_clsname(me
),
483 _repr_secret(me
._guts(),
484 not (me
.flags
& KF_NONSECRET
)),
485 me
.writeflags(me
.flags
))
486 def _repr_pretty_(me
, pp
, cyclep
):
487 ind
= _pp_bgroup_tyname(pp
, me
)
491 _pp_secret(pp
, me
._guts(), not (me
.flags
& KF_NONSECRET
))
492 pp
.text(','); pp
.breakable()
493 pp
.pretty(me
.writeflags(me
.flags
))
494 pp
.end_group(ind
, ')')
495 _augment(KeyData
, _tmp
)
498 def _guts(me
): return me
.bin
499 _augment(KeyDataBinary
, _tmp
)
502 def _guts(me
): return me
.ct
503 _augment(KeyDataEncrypted
, _tmp
)
506 def _guts(me
): return me
.mp
507 _augment(KeyDataMP
, _tmp
)
510 def _guts(me
): return me
.str
511 _augment(KeyDataString
, _tmp
)
514 def _guts(me
): return me
.ecpt
515 _augment(KeyDataECPt
, _tmp
)
519 return '%s({%s})' %
(_clsname(me
),
520 ', '.join(['%r: %r' % kv
for kv
in me
.iteritems()]))
521 def _repr_pretty_(me
, pp
, cyclep
):
522 ind
= _pp_bgroup_tyname(pp
, me
, '({ ')
523 if cyclep
: pp
.text('...')
524 else: _pp_dict(pp
, me
.iteritems())
525 pp
.end_group(ind
, ' })')
526 _augment(KeyDataStructured
, _tmp
)
528 ###--------------------------------------------------------------------------
533 return '%s(p = %s, r = %s, g = %s)' %
(_clsname(me
), me
.p
, me
.r
, me
.g
)
534 def _repr_pretty_(me
, pp
, cyclep
):
535 ind
= _pp_bgroup_tyname(pp
, me
)
539 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
540 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
541 _pp_kv(pp
, 'g', me
.g
)
542 pp
.end_group(ind
, ')')
543 _augment(FGInfo
, _tmp
)
546 def group(me
): return PrimeGroup(me
)
547 _augment(DHInfo
, _tmp
)
550 def group(me
): return BinGroup(me
)
551 _augment(BinDHInfo
, _tmp
)
555 return '%s(%r)' %
(_clsname(me
), me
.info
)
556 def _repr_pretty_(me
, pp
, cyclep
):
557 ind
= _pp_bgroup_tyname(pp
, me
)
558 if cyclep
: pp
.text('...')
559 else: pp
.pretty(me
.info
)
560 pp
.end_group(ind
, ')')
561 _augment(Group
, _tmp
)
568 h ^
= 2*hash(info
.r
) & 0xffffffff
569 h ^
= 5*hash(info
.g
) & 0xffffffff
571 def _get_geval(me
, x
): return MP(x
)
572 _augment(PrimeGroup
, _tmp
)
579 h ^
= 2*hash(info
.r
) & 0xffffffff
580 h ^
= 5*hash(info
.g
) & 0xffffffff
582 def _get_geval(me
, x
): return GF(x
)
583 _augment(BinGroup
, _tmp
)
586 def __hash__(me
): return 0x0ec23dab ^
hash(me
.info
)
587 def _get_geval(me
, x
): return x
.toec()
588 _augment(ECGroup
, _tmp
)
592 return '%r(%r)' %
(me
.group
, str(me
))
593 def _repr_pretty_(me
, pp
, cyclep
):
594 pp
.pretty(type(me
)._get_geval(me
))
597 ###--------------------------------------------------------------------------
598 ### RSA encoding techniques.
600 class PKCS1Crypt (object):
601 def __init__(me
, ep
= '', rng
= rand
):
604 def encode(me
, msg
, nbits
):
605 return _base
._p1crypt_encode(msg
, nbits
, me
.ep
, me
.rng
)
606 def decode(me
, ct
, nbits
):
607 return _base
._p1crypt_decode(ct
, nbits
, me
.ep
, me
.rng
)
609 class PKCS1Sig (object):
610 def __init__(me
, ep
= '', rng
= rand
):
613 def encode(me
, msg
, nbits
):
614 return _base
._p1sig_encode(msg
, nbits
, me
.ep
, me
.rng
)
615 def decode(me
, msg
, sig
, nbits
):
616 return _base
._p1sig_decode(msg
, sig
, nbits
, me
.ep
, me
.rng
)
619 def __init__(me
, mgf
= sha_mgf
, hash = sha
, ep
= '', rng
= rand
):
624 def encode(me
, msg
, nbits
):
625 return _base
._oaep_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
626 def decode(me
, ct
, nbits
):
627 return _base
._oaep_decode(ct
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
630 def __init__(me
, mgf
= sha_mgf
, hash = sha
, saltsz
= None, rng
= rand
):
637 def encode(me
, msg
, nbits
):
638 return _base
._pss_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
639 def decode(me
, msg
, sig
, nbits
):
640 return _base
._pss_decode(msg
, sig
, nbits
,
641 me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
644 def encrypt(me
, msg
, enc
):
645 return me
.pubop(enc
.encode(msg
, me
.n
.nbits
))
646 def verify(me
, msg
, sig
, enc
):
647 if msg
is None: return enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
649 x
= enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
650 return x
is None or x
== msg
654 return '%s(n = %r, e = %r)' %
(_clsname(me
), me
.n
, me
.e
)
655 def _repr_pretty_(me
, pp
, cyclep
):
656 ind
= _pp_bgroup_tyname(pp
, me
)
660 _pp_kv(pp
, 'n', me
.n
); pp
.text(','); pp
.breakable()
661 _pp_kv(pp
, 'e', me
.e
)
662 pp
.end_group(ind
, ')')
663 _augment(RSAPub
, _tmp
)
666 def decrypt(me
, ct
, enc
): return enc
.decode(me
.privop(ct
), me
.n
.nbits
)
667 def sign(me
, msg
, enc
): return me
.privop(enc
.encode(msg
, me
.n
.nbits
))
669 return '%s(n = %r, e = %r, d = %s, ' \
670 'p = %s, q = %s, dp = %s, dq = %s, q_inv = %s)' % \
671 (_clsname(me
), me
.n
, me
.e
,
672 _repr_secret(me
.d
), _repr_secret(me
.p
), _repr_secret(me
.q
),
673 _repr_secret(me
.dp
), _repr_secret(me
.dq
), _repr_secret(me
.q_inv
))
674 def _repr_pretty_(me
, pp
, cyclep
):
675 ind
= _pp_bgroup_tyname(pp
, me
)
679 _pp_kv(pp
, 'n', me
.n
); pp
.text(','); pp
.breakable()
680 _pp_kv(pp
, 'e', me
.e
); pp
.text(','); pp
.breakable()
681 _pp_kv(pp
, 'd', me
.d
, secretp
= True); pp
.text(','); pp
.breakable()
682 _pp_kv(pp
, 'p', me
.p
, secretp
= True); pp
.text(','); pp
.breakable()
683 _pp_kv(pp
, 'q', me
.q
, secretp
= True); pp
.text(','); pp
.breakable()
684 _pp_kv(pp
, 'dp', me
.dp
, secretp
= True); pp
.text(','); pp
.breakable()
685 _pp_kv(pp
, 'dq', me
.dq
, secretp
= True); pp
.text(','); pp
.breakable()
686 _pp_kv(pp
, 'q_inv', me
.q_inv
, secretp
= True)
687 pp
.end_group(ind
, ')')
688 _augment(RSAPriv
, _tmp
)
690 ###--------------------------------------------------------------------------
691 ### DSA and related schemes.
694 def __repr__(me
): return '%s(G = %r, p = %r)' %
(_clsname(me
), me
.G
, me
.p
)
695 def _repr_pretty_(me
, pp
, cyclep
):
696 ind
= _pp_bgroup_tyname(pp
, me
)
700 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
701 _pp_kv(pp
, 'p', me
.p
)
702 pp
.end_group(ind
, ')')
703 _augment(DSAPub
, _tmp
)
704 _augment(KCDSAPub
, _tmp
)
707 def __repr__(me
): return '%s(G = %r, u = %s, p = %r)' % \
708 (_clsname(me
), me
.G
, _repr_secret(me
.u
), 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
, 'u', me
.u
, True); pp
.text(','); pp
.breakable()
716 _pp_kv(pp
, 'p', me
.p
)
717 pp
.end_group(ind
, ')')
718 _augment(DSAPriv
, _tmp
)
719 _augment(KCDSAPriv
, _tmp
)
721 ###--------------------------------------------------------------------------
722 ### Bernstein's elliptic curve crypto and related schemes.
725 bytes('0900000000000000000000000000000000000000000000000000000000000000')
728 bytes('05000000000000000000000000000000000000000000000000000000'
729 '00000000000000000000000000000000000000000000000000000000')
731 Z128
= bytes('00000000000000000000000000000000')
733 class _BoxyPub (object):
734 def __init__(me
, pub
, *kw
, **kwargs
):
735 if len(pub
) != me
._PUBSZ
: raise ValueError, 'bad public key'
736 super(_BoxyPub
, me
).__init__(*kw
, **kwargs
)
738 def __repr__(me
): return '%s(pub = %r)' %
(_clsname(me
), me
.pub
)
739 def _repr_pretty_(me
, pp
, cyclep
):
740 ind
= _pp_bgroup_tyname(pp
, me
)
744 _pp_kv(pp
, 'pub', me
.pub
)
745 pp
.end_group(ind
, ')')
747 class _BoxyPriv (_BoxyPub
):
748 def __init__(me
, priv
, pub
= None, *kw
, **kwargs
):
749 if len(priv
) != me
._KEYSZ
: raise ValueError, 'bad private key'
750 if pub
is None: pub
= me
._op(priv
, me
._BASE
)
751 super(_BoxyPriv
, me
).__init__(pub
= pub
, *kw
, **kwargs
)
753 def agree(me
, you
): return me
._op(me
.priv
, you
.pub
)
754 def boxkey(me
, recip
):
755 return me
._hashkey(me
.agree(recip
))
756 def box(me
, recip
, n
, m
):
757 return secret_box(me
.boxkey(recip
), n
, m
)
758 def unbox(me
, recip
, n
, c
):
759 return secret_unbox(me
.boxkey(recip
, n
, c
))
760 def __repr__(me
): return '%s(priv = %s, pub = %r)' % \
761 (_clsname(me
), _repr_secret(me
.priv
), me
.pub
)
762 def _repr_pretty_(me
, pp
, cyclep
):
763 ind
= _pp_bgroup_tyname(pp
, me
)
767 _pp_kv(pp
, 'priv', me
.priv
, True); pp
.text(','); pp
.breakable()
768 _pp_kv(pp
, 'pub', me
.pub
)
769 pp
.end_group(ind
, ')')
771 class X25519Pub (_BoxyPub
):
772 _PUBSZ
= X25519_PUBSZ
775 class X25519Priv (_BoxyPriv
, X25519Pub
):
776 _KEYSZ
= X25519_KEYSZ
777 def _op(me
, k
, X
): return x25519(k
, X
)
778 def _hashkey(me
, z
): return hsalsa20_prf(z
, Z128
)
780 class X448Pub (_BoxyPub
):
784 class X448Priv (_BoxyPriv
, X448Pub
):
786 def _op(me
, k
, X
): return x448(k
, X
)
787 ##def _hashkey(me, z): return ???
789 class Ed25519Pub (object):
790 def __init__(me
, pub
):
792 def verify(me
, msg
, sig
):
793 return ed25519_verify(me
.pub
, msg
, sig
)
795 class Ed25519Priv (Ed25519Pub
):
796 def __init__(me
, priv
):
798 Ed25519Pub
.__init__(me
, ed25519_pubkey(priv
))
800 return ed25519_sign(me
.priv
, msg
, pub
= me
.pub
)
802 def generate(cls
, rng
= rand
):
803 return cls(rng
.block(ED25519_KEYSZ
))
805 ###--------------------------------------------------------------------------
806 ### Built-in named curves and prime groups.
808 class _groupmap (object):
809 def __init__(me
, map, nth
):
812 me
._n
= max(map.values()) + 1
815 return '{%s}' %
', '.join(['%r: %r' % kv
for kv
in me
.iteritems()])
816 def _repr_pretty_(me
, pp
, cyclep
):
817 ind
= _pp_bgroup(pp
, '{ ')
818 if cyclep
: pp
.text('...')
819 else: _pp_dict(pp
, me
.iteritems())
820 pp
.end_group(ind
, ' }')
823 def __contains__(me
, k
):
825 def __getitem__(me
, k
):
830 def __setitem__(me
, k
, v
):
831 raise TypeError, "immutable object"
843 return [k
for k
in me
]
845 return [me
[k
] for k
in me
]
847 return [(k
, me
[k
]) for k
in me
]
848 eccurves
= _groupmap(_base
._eccurves
, ECInfo
._curven
)
849 primegroups
= _groupmap(_base
._pgroups
, DHInfo
._groupn
)
850 bingroups
= _groupmap(_base
._bingroups
, BinDHInfo
._groupn
)
852 ###--------------------------------------------------------------------------
853 ### Prime number generation.
855 class PrimeGenEventHandler (object):
856 def pg_begin(me
, ev
):
860 def pg_abort(me
, ev
):
867 class SophieGermainStepJump (object):
868 def pg_begin(me
, ev
):
869 me
.lf
= PrimeFilter(ev
.x
)
870 me
.hf
= me
.lf
.muladd(2, 1)
876 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
878 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
881 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
888 class SophieGermainStepper (SophieGermainStepJump
):
889 def __init__(me
, step
):
896 class SophieGermainJumper (SophieGermainStepJump
):
897 def __init__(me
, jump
):
898 me
.ljump
= PrimeFilter(jump
);
899 me
.hjump
= me
.ljump
.muladd(2, 0)
906 SophieGermainStepJump
.pg_done(me
, ev
)
908 class SophieGermainTester (object):
911 def pg_begin(me
, ev
):
912 me
.lr
= RabinMiller(ev
.x
)
913 me
.hr
= RabinMiller(2 * ev
.x
+ 1)
915 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
916 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
918 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
919 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
921 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
928 class PrimitiveStepper (PrimeGenEventHandler
):
934 def pg_begin(me
, ev
):
935 me
.i
= iter(smallprimes
)
938 class PrimitiveTester (PrimeGenEventHandler
):
939 def __init__(me
, mod
, hh
= [], exp
= None):
945 if me
.exp
is not None:
946 x
= me
.mod
.exp(x
, me
.exp
)
947 if x
== 1: return PGEN_FAIL
949 if me
.mod
.exp(x
, h
) == 1: return PGEN_FAIL
953 class SimulStepper (PrimeGenEventHandler
):
954 def __init__(me
, mul
= 2, add
= 1, step
= 2):
958 def _stepfn(me
, step
):
960 raise ValueError, 'step must be positive'
962 return lambda f
: f
.step(step
)
963 j
= PrimeFilter(step
)
964 return lambda f
: f
.jump(j
)
965 def pg_begin(me
, ev
):
967 me
.lf
= PrimeFilter(x
)
968 me
.hf
= PrimeFilter(x
* me
.mul
+ me
.add
)
969 me
.lstep
= me
._stepfn(me
.step
)
970 me
.hstep
= me
._stepfn(me
.step
* me
.mul
)
971 SimulStepper
._cont(me
, ev
)
979 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
981 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
984 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
993 class SimulTester (PrimeGenEventHandler
):
994 def __init__(me
, mul
= 2, add
= 1):
997 def pg_begin(me
, ev
):
999 me
.lr
= RabinMiller(x
)
1000 me
.hr
= RabinMiller(x
* me
.mul
+ me
.add
)
1002 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
1003 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
1005 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
1006 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
1008 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
1011 def pg_done(me
, ev
):
1015 def sgprime(start
, step
= 2, name
= 'p', event
= pgen_nullev
, nsteps
= 0):
1017 return pgen(start
, name
, SimulStepper(step
= step
), SimulTester(), event
,
1018 nsteps
, RabinMiller
.iters(start
.nbits
))
1020 def findprimitive(mod
, hh
= [], exp
= None, name
= 'g', event
= pgen_nullev
):
1021 return pgen(0, name
, PrimitiveStepper(), PrimitiveTester(mod
, hh
, exp
),
1024 def kcdsaprime(pbits
, qbits
, rng
= rand
,
1025 event
= pgen_nullev
, name
= 'p', nsteps
= 0):
1026 hbits
= pbits
- qbits
1027 h
= pgen(rng
.mp(hbits
, 1), name
+ ' [h]',
1028 PrimeGenStepper(2), PrimeGenTester(),
1029 event
, nsteps
, RabinMiller
.iters(hbits
))
1030 q
= pgen(rng
.mp(qbits
, 1), name
, SimulStepper(2 * h
, 1, 2),
1031 SimulTester(2 * h
, 1), event
, nsteps
, RabinMiller
.iters(qbits
))
1035 #----- That's all, folks ----------------------------------------------------