5483cca889cd3c4cb36476bfa38f92fe132e3869
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.
26 from __future__
import with_statement
28 from binascii
import hexlify
as _hexify
, unhexlify
as _unhexify
29 from contextlib
import contextmanager
as _ctxmgr
30 try: import DLFCN
as _dlfcn
31 except ImportError: _dlfcn
= None
33 from struct
import pack
as _pack
35 import types
as _types
37 ###--------------------------------------------------------------------------
38 ### Import the main C extension module.
41 _dlflags
= _odlflags
= _sys
.getdlopenflags()
42 except AttributeError:
43 _dlflags
= _odlflags
= -1
45 ## Set the `deep binding' flag. Python has its own different MD5
46 ## implementation, and some distributions export `md5_init' and friends so
47 ## they override our versions, which doesn't end well. Figure out how to
48 ## turn this flag on so we don't have the problem.
50 try: _dlflags |
= _dlfcn
.RTLD_DEEPBIND
51 except AttributeError:
52 try: _dlflags |
= _os
.RTLD_DEEPBIND
53 except AttributeError:
54 if _os
.uname()[0] == 'Linux': _dlflags |
= 8 # magic knowledge
55 else: pass # can't do this.
56 _sys
.setdlopenflags(_dlflags
)
61 _sys
.setdlopenflags(_odlflags
)
63 del _dlflags
, _odlflags
65 ###--------------------------------------------------------------------------
68 ## For the benefit of the default keyreporter, we need the program name.
69 _base
._ego(_sys
.argv
[0])
71 ## Register our module.
72 _base
._set_home_module(_sys
.modules
[__name__
])
73 def default_lostexchook(why
, ty
, val
, tb
):
74 """`catacomb.lostexchook(WHY, TY, VAL, TB)' reports lost exceptions."""
75 _sys
.stderr
.write("\n\n!!! LOST EXCEPTION: %s\n" % why
)
76 _sys
.excepthook(ty
, val
, tb
)
77 _sys
.stderr
.write("\n")
78 lostexchook
= default_lostexchook
80 ## Text/binary conversions.
83 ## Iterating over dictionaries.
84 def _iteritems(dict): return dict.iteritems()
85 def _itervalues(dict): return dict.itervalues()
87 ## The built-in bignum type.
90 ## How to fix a name back into the right identifier. Alas, the rules are not
94 ## Hyphens consistently become underscores.
95 name
= name
.replace('-', '_')
97 ## But slashes might become underscores or just vanish.
98 if name
.startswith('salsa20'): name
= name
.replace('/', '')
99 else: name
= name
.replace('/', '_')
104 ## Initialize the module. Drag in the static methods of the various
105 ## classes; create names for the various known crypto algorithms.
112 for i
in [gcciphers
, gcaeads
, gchashes
, gcmacs
, gcprps
]:
113 for c
in _itervalues(i
):
114 d
[_fixname(c
.name
)] = c
115 for c
in _itervalues(gccrands
):
116 d
[_fixname(c
.name
+ 'rand')] = c
119 ## A handy function for our work: add the methods of a named class to an
120 ## existing class. This is how we write the Python-implemented parts of our
123 for i
in cc
.__dict__
:
125 if type(a
) is _types
.MethodType
:
127 elif type(a
) not in (_types
.FunctionType
, staticmethod, classmethod):
131 ## Parsing functions tend to return the object parsed and the remainder of
132 ## the input. This checks that the remainder is input and, if so, returns
137 raise SyntaxError('junk at end of string')
140 ## Some pretty-printing utilities.
141 PRINT_SECRETS
= False
142 def _clsname(me
): return type(me
).__name__
143 def _repr_secret(thing
, secretp
= True):
144 if not secretp
or PRINT_SECRETS
: return repr(thing
)
145 else: return '#<SECRET>'
146 def _pp_str(me
, pp
, cyclep
): pp
.text(cyclep
and '...' or str(me
))
147 def _pp_secret(pp
, thing
, secretp
= True):
148 if not secretp
or PRINT_SECRETS
: pp
.pretty(thing
)
149 else: pp
.text('#<SECRET>')
150 def _pp_bgroup(pp
, text
):
152 pp
.begin_group(ind
, text
)
154 def _pp_bgroup_tyname(pp
, obj
, open = '('):
155 return _pp_bgroup(pp
, _clsname(obj
) + open)
156 def _pp_kv(pp
, k
, v
, secretp
= False):
157 ind
= _pp_bgroup(pp
, k
+ ' = ')
158 _pp_secret(pp
, v
, secretp
)
159 pp
.end_group(ind
, '')
160 def _pp_commas(pp
, printfn
, items
):
163 if firstp
: firstp
= False
164 else: pp
.text(','); pp
.breakable()
166 def _pp_dict(pp
, items
):
177 _pp_commas(pp
, p
, items
)
179 ###--------------------------------------------------------------------------
184 return ByteString(_unhexify(x
))
185 fromhex
= staticmethod(fromhex
)
186 def hex(me
): return _hexify(me
)
189 return 'bytes(%r)' % me
.hex()
190 _augment(ByteString
, _tmp
)
191 ByteString
.__hash__
= str.__hash__
192 bytes
= ByteString
.fromhex
194 ###--------------------------------------------------------------------------
195 ### Symmetric encryption.
198 def encrypt(me
, n
, m
, tsz
= None, h
= ByteString
.zero(0)):
199 if tsz
is None: tsz
= me
.__class__
.tagsz
.default
200 e
= me
.enc(n
, len(h
), len(m
), tsz
)
201 if not len(h
): a
= None
202 else: a
= e
.aad().hash(h
)
204 c1
, t
= e
.done(aad
= a
)
206 def decrypt(me
, n
, c
, t
, h
= ByteString
.zero(0)):
207 d
= me
.dec(n
, len(h
), len(c
), len(t
))
208 if not len(h
): a
= None
209 else: a
= d
.aad().hash(h
)
211 m
+= d
.done(t
, aad
= a
)
213 _augment(GAEKey
, _tmp
)
215 ###--------------------------------------------------------------------------
221 return ctstreq(h
, hh
)
222 _augment(GHash
, _tmp
)
223 _augment(Poly1305Hash
, _tmp
)
225 class _HashBase (object):
226 ## The standard hash methods. Assume that `hash' is defined and returns
228 def _check_range(me
, n
, max):
229 if not (0 <= n
<= max): raise OverflowError("out of range")
231 me
._check_range(n
, 0xff)
232 return me
.hash(_pack('B', n
))
234 me
._check_range(n
, 0xffff)
235 return me
.hash(_pack('<H', n
))
237 me
._check_range(n
, 0xffff)
238 return me
.hash(_pack('>H', n
))
241 me
._check_range(n
, 0xffffffff)
242 return me
.hash(_pack('<L', n
))
244 me
._check_range(n
, 0xffffffff)
245 return me
.hash(_pack('>L', n
))
248 me
._check_range(n
, 0xffffffffffffffff)
249 return me
.hash(_pack('<Q', n
))
251 me
._check_range(n
, 0xffffffffffffffff)
252 return me
.hash(_pack('>Q', n
))
254 def hashbuf8(me
, s
): return me
.hashu8(len(s
)).hash(s
)
255 def hashbuf16l(me
, s
): return me
.hashu16l(len(s
)).hash(s
)
256 def hashbuf16b(me
, s
): return me
.hashu16b(len(s
)).hash(s
)
257 hashbuf16
= hashbuf16b
258 def hashbuf32l(me
, s
): return me
.hashu32l(len(s
)).hash(s
)
259 def hashbuf32b(me
, s
): return me
.hashu32b(len(s
)).hash(s
)
260 hashbuf32
= hashbuf32b
261 def hashbuf64l(me
, s
): return me
.hashu64l(len(s
)).hash(s
)
262 def hashbuf64b(me
, s
): return me
.hashu64b(len(s
)).hash(s
)
263 hashbuf64
= hashbuf64b
264 def hashstrz(me
, s
): return me
.hash(s
).hashu8(0)
266 class _ShakeBase (_HashBase
):
268 ## Python gets really confused if I try to augment `__new__' on native
269 ## classes, so wrap and delegate. Sorry.
270 def __init__(me
, perso
= _bin(''), *args
, **kw
):
271 super(_ShakeBase
, me
).__init__(*args
, **kw
)
272 me
._h
= me
._SHAKE(perso
= perso
, func
= me
._FUNC
)
274 ## Delegate methods...
275 def copy(me
): new
= me
.__class__
._bare_new(); new
._copy(me
); return new
276 def _copy(me
, other
): me
._h
= other
._h
.copy()
277 def hash(me
, m
): me
._h
.hash(m
); return me
278 def xof(me
): me
._h
.xof(); return me
279 def get(me
, n
): return me
._h
.get(n
)
280 def mask(me
, m
): return me
._h
.mask(m
)
281 def done(me
, n
): return me
._h
.done(n
)
282 def check(me
, h
): return ctstreq(h
, me
.done(len(h
)))
284 def state(me
): return me
._h
.state
286 def buffered(me
): return me
._h
.buffered
288 def rate(me
): return me
._h
.rate
290 def _bare_new(cls
): return cls()
294 return ctstreq(h
, me
.done(len(h
)))
297 return me
.hashu8(len(nn
)).hash(nn
)
300 return me
.hash(nn
).hashu8(len(nn
))
301 def stringenc(me
, str):
302 return me
.leftenc(8*len(str)).hash(str)
303 def bytepad_before(me
):
304 return me
.leftenc(me
.rate
)
305 def bytepad_after(me
):
306 if me
.buffered
: me
.hash(me
._Z
[:me
.rate
- me
.buffered
])
313 _augment(Shake
, _tmp
)
314 _augment(_ShakeBase
, _tmp
)
315 Shake
._Z
= _ShakeBase
._Z
= ByteString
.zero(200)
317 class KMAC (_ShakeBase
):
319 def __init__(me
, k
, *arg
, **kw
):
320 super(KMAC
, me
).__init__(*arg
, **kw
)
321 with me
.bytepad(): me
.stringenc(k
)
322 def done(me
, n
= -1):
323 if n
< 0: n
= me
._TAGSZ
325 return super(KMAC
, me
).done(n
)
328 return super(KMAC
, me
).xof()
330 def _bare_new(cls
): return cls(_bin(""))
332 class KMAC128 (KMAC
): _SHAKE
= Shake128
; _TAGSZ
= 16
333 class KMAC256 (KMAC
): _SHAKE
= Shake256
; _TAGSZ
= 32
335 ###--------------------------------------------------------------------------
336 ### NaCl `secretbox'.
338 def secret_box(k
, n
, m
):
339 y
, t
= salsa20_naclbox(k
).encrypt(n
, m
)
342 def secret_unbox(k
, n
, c
):
344 return salsa20_naclbox(k
).decrypt(n
, c
[tsz
:], c
[0:tsz
])
346 ###--------------------------------------------------------------------------
347 ### Multiprecision integers and binary polynomials.
350 if isinstance(x
, BaseRat
): return x
._n
, x
._d
352 class BaseRat (object):
353 """Base class implementing fields of fractions over Euclidean domains."""
354 def __new__(cls
, a
, b
):
355 a
, b
= cls
.RING(a
), cls
.RING(b
)
359 me
= super(BaseRat
, cls
).__new__(cls
)
364 def numer(me
): return me
._n
366 def denom(me
): return me
._d
367 def __str__(me
): return '%s/%s' %
(me
._n
, me
._d
)
368 def __repr__(me
): return '%s(%s, %s)' %
(_clsname(me
), me
._n
, me
._d
)
369 _repr_pretty_
= _pp_str
371 def __add__(me
, you
):
372 n
, d
= _split_rat(you
)
373 return type(me
)(me
._n
*d
+ n
*me
._d
, d
*me
._d
)
375 def __sub__(me
, you
):
376 n
, d
= _split_rat(you
)
377 return type(me
)(me
._n
*d
- n
*me
._d
, d
*me
._d
)
378 def __rsub__(me
, you
):
379 n
, d
= _split_rat(you
)
380 return type(me
)(n
*me
._d
- me
._n
*d
, d
*me
._d
)
381 def __mul__(me
, you
):
382 n
, d
= _split_rat(you
)
383 return type(me
)(me
._n
*n
, me
._d
*d
)
385 def __truediv__(me
, you
):
386 n
, d
= _split_rat(you
)
387 return type(me
)(me
._n
*d
, me
._d
*n
)
388 def __rtruediv__(me
, you
):
389 n
, d
= _split_rat(you
)
390 return type(me
)(me
._d
*n
, me
._n
*d
)
391 __div__
= __truediv__
392 __rdiv__
= __rtruediv__
393 def _order(me
, you
, op
):
394 n
, d
= _split_rat(you
)
395 return op(me
._n
*d
, n
*me
._d
)
396 def __eq__(me
, you
): return me
._order(you
, lambda x
, y
: x
== y
)
397 def __ne__(me
, you
): return me
._order(you
, lambda x
, y
: x
!= y
)
398 def __le__(me
, you
): return me
._order(you
, lambda x
, y
: x
<= y
)
399 def __lt__(me
, you
): return me
._order(you
, lambda x
, y
: x
< y
)
400 def __gt__(me
, you
): return me
._order(you
, lambda x
, y
: x
> y
)
401 def __ge__(me
, you
): return me
._order(you
, lambda x
, y
: x
>= y
)
403 class IntRat (BaseRat
):
405 def __new__(cls
, a
, b
):
406 if isinstance(a
, float) or isinstance(b
, float): return a
/b
407 return super(IntRat
, cls
).__new__(cls
, a
, b
)
408 def __float__(me
): return float(me
._n
)/float(me
._d
)
410 class GFRat (BaseRat
):
414 def negp(x
): return x
< 0
415 def posp(x
): return x
> 0
416 def zerop(x
): return x
== 0
417 def oddp(x
): return x
.testbit(0)
418 def evenp(x
): return not x
.testbit(0)
419 def mont(x
): return MPMont(x
)
420 def barrett(x
): return MPBarrett(x
)
421 def reduce(x
): return MPReduce(x
)
422 def __truediv__(me
, you
):
423 if isinstance(you
, float): return _long(me
)/you
424 else: return IntRat(me
, you
)
425 def __rtruediv__(me
, you
):
426 if isinstance(you
, float): return you
/_long(me
)
427 else: return IntRat(you
, me
)
428 __div__
= __truediv__
429 __rdiv__
= __rtruediv__
430 _repr_pretty_
= _pp_str
434 def zerop(x
): return x
== 0
435 def reduce(x
): return GFReduce(x
)
436 def trace(x
, y
): return x
.reduce().trace(y
)
437 def halftrace(x
, y
): return x
.reduce().halftrace(y
)
438 def modsqrt(x
, y
): return x
.reduce().sqrt(y
)
439 def quadsolve(x
, y
): return x
.reduce().quadsolve(y
)
440 def __truediv__(me
, you
): return GFRat(me
, you
)
441 def __rtruediv__(me
, you
): return GFRat(you
, me
)
442 __div__
= __truediv__
443 __rdiv__
= __rtruediv__
444 _repr_pretty_
= _pp_str
449 'product(ITERABLE) or product(I, ...) -> PRODUCT'
450 return MPMul(*arg
).done()
451 product
= staticmethod(product
)
452 _augment(MPMul
, _tmp
)
454 ###--------------------------------------------------------------------------
458 def fromstring(str): return _checkend(Field
.parse(str))
459 fromstring
= staticmethod(fromstring
)
460 _augment(Field
, _tmp
)
463 def __repr__(me
): return '%s(%s)' %
(_clsname(me
), me
.p
)
464 def __hash__(me
): return 0x114401de ^
hash(me
.p
)
465 def _repr_pretty_(me
, pp
, cyclep
):
466 ind
= _pp_bgroup_tyname(pp
, me
)
467 if cyclep
: pp
.text('...')
468 else: pp
.pretty(me
.p
)
469 pp
.end_group(ind
, ')')
470 def ec(me
, a
, b
): return ECPrimeProjCurve(me
, a
, b
)
471 _augment(PrimeField
, _tmp
)
474 def __repr__(me
): return '%s(%#x)' %
(_clsname(me
), me
.p
)
475 def ec(me
, a
, b
): return ECBinProjCurve(me
, a
, b
)
476 def _repr_pretty_(me
, pp
, cyclep
):
477 ind
= _pp_bgroup_tyname(pp
, me
)
478 if cyclep
: pp
.text('...')
479 else: pp
.text('%#x' % me
.p
)
480 pp
.end_group(ind
, ')')
481 _augment(BinField
, _tmp
)
484 def __hash__(me
): return 0x23e4701c ^
hash(me
.p
)
485 _augment(BinPolyField
, _tmp
)
491 h ^
= 2*hash(me
.beta
) & 0xffffffff
493 _augment(BinNormField
, _tmp
)
496 def __str__(me
): return str(me
.value
)
497 def __repr__(me
): return '%s(%s)' %
(repr(me
.field
), repr(me
.value
))
498 _repr_pretty_
= _pp_str
501 ###--------------------------------------------------------------------------
506 return '%s(%r, %s, %s)' %
(_clsname(me
), me
.field
, me
.a
, me
.b
)
507 def _repr_pretty_(me
, pp
, cyclep
):
508 ind
= _pp_bgroup_tyname(pp
, me
)
512 pp
.pretty(me
.field
); pp
.text(','); pp
.breakable()
513 pp
.pretty(me
.a
); pp
.text(','); pp
.breakable()
515 pp
.end_group(ind
, ')')
517 return ecpt
.frombuf(me
, s
)
519 return ecpt
.fromraw(me
, s
)
522 _augment(ECCurve
, _tmp
)
528 h ^
= 2*hash(me
.a
) ^
0xffffffff
529 h ^
= 5*hash(me
.b
) ^
0xffffffff
531 _augment(ECPrimeCurve
, _tmp
)
537 h ^
= 2*hash(me
.a
) ^
0xffffffff
538 h ^
= 5*hash(me
.b
) ^
0xffffffff
540 _augment(ECBinCurve
, _tmp
)
544 if not me
: return '%s()' %
_clsname(me
)
545 return '%s(%s, %s)' %
(_clsname(me
), me
.ix
, me
.iy
)
547 if not me
: return 'inf'
548 return '(%s, %s)' %
(me
.ix
, me
.iy
)
549 def _repr_pretty_(me
, pp
, cyclep
):
555 ind
= _pp_bgroup(pp
, '(')
556 pp
.pretty(me
.ix
); pp
.text(','); pp
.breakable()
558 pp
.end_group(ind
, ')')
563 return '%s(curve = %r, G = %r, r = %s, h = %s)' % \
564 (_clsname(me
), me
.curve
, me
.G
, me
.r
, me
.h
)
565 def _repr_pretty_(me
, pp
, cyclep
):
566 ind
= _pp_bgroup_tyname(pp
, me
)
570 _pp_kv(pp
, 'curve', me
.curve
); pp
.text(','); pp
.breakable()
571 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
572 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
573 _pp_kv(pp
, 'h', me
.h
)
574 pp
.end_group(ind
, ')')
578 h ^
= 2*hash(me
.G
) & 0xffffffff
582 _augment(ECInfo
, _tmp
)
586 if not me
: return '%r()' %
(me
.curve
)
587 return '%r(%s, %s)' %
(me
.curve
, me
.x
, me
.y
)
589 if not me
: return 'inf'
590 return '(%s, %s)' %
(me
.x
, me
.y
)
591 def _repr_pretty_(me
, pp
, cyclep
):
597 ind
= _pp_bgroup(pp
, '(')
598 pp
.pretty(me
.x
); pp
.text(','); pp
.breakable()
600 pp
.end_group(ind
, ')')
601 _augment(ECPtCurve
, _tmp
)
603 ###--------------------------------------------------------------------------
607 def __repr__(me
): return '%s(%d)' %
(_clsname(me
), me
.default
)
608 def check(me
, sz
): return True
609 def best(me
, sz
): return sz
610 def pad(me
, sz
): return sz
611 _augment(KeySZAny
, _tmp
)
615 return '%s(%d, %d, %d, %d)' % \
616 (_clsname(me
), me
.default
, me
.min, me
.max, me
.mod
)
617 def _repr_pretty_(me
, pp
, cyclep
):
618 ind
= _pp_bgroup_tyname(pp
, me
)
622 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
623 pp
.pretty(me
.min); pp
.text(','); pp
.breakable()
624 pp
.pretty(me
.max); pp
.text(','); pp
.breakable()
626 pp
.end_group(ind
, ')')
627 def check(me
, sz
): return me
.min <= sz
<= me
.max and sz
%me
.mod
== 0
629 if sz
< me
.min: raise ValueError('key too small')
630 elif sz
> me
.max: return me
.max
631 else: return sz
- sz
%me
.mod
633 if sz
> me
.max: raise ValueError('key too large')
634 elif sz
< me
.min: return me
.min
635 else: sz
+= me
.mod
- 1; return sz
- sz
%me
.mod
636 _augment(KeySZRange
, _tmp
)
639 def __repr__(me
): return '%s(%d, %s)' %
(_clsname(me
), me
.default
, me
.set)
640 def _repr_pretty_(me
, pp
, cyclep
):
641 ind
= _pp_bgroup_tyname(pp
, me
)
645 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
646 ind1
= _pp_bgroup(pp
, '{')
647 _pp_commas(pp
, pp
.pretty
, me
.set)
648 pp
.end_group(ind1
, '}')
649 pp
.end_group(ind
, ')')
650 def check(me
, sz
): return sz
in me
.set
654 if found
< i
<= sz
: found
= i
655 if found
< 0: raise ValueError('key too small')
660 if sz
<= i
and (found
== -1 or i
< found
): found
= i
661 if found
< 0: raise ValueError('key too large')
663 _augment(KeySZSet
, _tmp
)
665 ###--------------------------------------------------------------------------
666 ### Key data objects.
669 def merge(me
, file, report
= None):
670 """KF.merge(FILE, [report = <built-in-reporter>])"""
674 me
.mergeline(name
, lno
, line
, report
)
677 def __repr__(me
): return '%s(%r)' %
(_clsname(me
), me
.name
)
678 _augment(KeyFile
, _tmp
)
681 def extract(me
, file, filter = ''):
682 """KEY.extract(FILE, [filter = <any>])"""
683 line
= me
.extractline(filter)
686 def __repr__(me
): return '%s(%r)' %
(_clsname(me
), me
.fulltag
)
691 return '%s({%s})' %
(_clsname(me
),
692 ', '.join(['%r: %r' % kv
for kv
in _iteritems(me
)()]))
693 def _repr_pretty_(me
, pp
, cyclep
):
694 ind
= _pp_bgroup_tyname(pp
, me
)
695 if cyclep
: pp
.text('...')
696 else: _pp_dict(pp
, _iteritems(me
))
697 pp
.end_group(ind
, ')')
698 _augment(KeyAttributes
, _tmp
)
702 return '%s(%s, %r)' %
(_clsname(me
),
703 _repr_secret(me
._guts(),
704 not (me
.flags
& KF_NONSECRET
)),
705 me
.writeflags(me
.flags
))
706 def _repr_pretty_(me
, pp
, cyclep
):
707 ind
= _pp_bgroup_tyname(pp
, me
)
711 _pp_secret(pp
, me
._guts(), not (me
.flags
& KF_NONSECRET
))
712 pp
.text(','); pp
.breakable()
713 pp
.pretty(me
.writeflags(me
.flags
))
714 pp
.end_group(ind
, ')')
715 def __hash__(me
): return me
._HASHBASE ^
hash(me
._guts())
717 return type(me
) == type(kd
) and \
718 me
._guts() == kd
._guts() and \
722 _augment(KeyData
, _tmp
)
725 def _guts(me
): return me
.bin
727 return isinstance(kd
, KeyDataBinary
) and me
.bin
== kd
.bin
728 _augment(KeyDataBinary
, _tmp
)
729 KeyDataBinary
._HASHBASE
= 0x961755c3
732 def _guts(me
): return me
.ct
733 _augment(KeyDataEncrypted
, _tmp
)
734 KeyDataEncrypted
._HASHBASE
= 0xffe000d4
737 def _guts(me
): return me
.mp
738 _augment(KeyDataMP
, _tmp
)
739 KeyDataMP
._HASHBASE
= 0x1cb64d69
742 def _guts(me
): return me
.str
743 _augment(KeyDataString
, _tmp
)
744 KeyDataString
._HASHBASE
= 0x349c33ea
747 def _guts(me
): return me
.ecpt
748 _augment(KeyDataECPt
, _tmp
)
749 KeyDataECPt
._HASHBASE
= 0x2509718b
753 return '%s({%s})' %
(_clsname(me
),
754 ', '.join(['%r: %r' % kv
for kv
in _iteritems(me
)]))
755 def _repr_pretty_(me
, pp
, cyclep
):
756 ind
= _pp_bgroup_tyname(pp
, me
, '({ ')
757 if cyclep
: pp
.text('...')
758 else: _pp_dict(pp
, _iteritems(me
))
759 pp
.end_group(ind
, ' })')
762 for k
, v
in _iteritems(me
):
763 h
= ((h
<< 1) ^
3*hash(k
) ^
5*hash(v
))&0xffffffff
766 if type(me
) != type(kd
) or me
.flags
!= kd
.flags
or len(me
) != len(kd
):
768 for k
, v
in _iteritems(me
):
770 except KeyError: return False
771 if v
!= vv
: return False
773 _augment(KeyDataStructured
, _tmp
)
774 KeyDataStructured
._HASHBASE
= 0x85851b21
776 ###--------------------------------------------------------------------------
781 return '%s(p = %s, r = %s, g = %s)' %
(_clsname(me
), me
.p
, me
.r
, me
.g
)
782 def _repr_pretty_(me
, pp
, cyclep
):
783 ind
= _pp_bgroup_tyname(pp
, me
)
787 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
788 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
789 _pp_kv(pp
, 'g', me
.g
)
790 pp
.end_group(ind
, ')')
791 _augment(FGInfo
, _tmp
)
794 def group(me
): return PrimeGroup(me
)
795 _augment(DHInfo
, _tmp
)
798 def group(me
): return BinGroup(me
)
799 _augment(BinDHInfo
, _tmp
)
803 return '%s(%r)' %
(_clsname(me
), me
.info
)
804 def _repr_pretty_(me
, pp
, cyclep
):
805 ind
= _pp_bgroup_tyname(pp
, me
)
806 if cyclep
: pp
.text('...')
807 else: pp
.pretty(me
.info
)
808 pp
.end_group(ind
, ')')
809 _augment(Group
, _tmp
)
816 h ^
= 2*hash(info
.r
) & 0xffffffff
817 h ^
= 5*hash(info
.g
) & 0xffffffff
819 def _get_geval(me
, x
): return MP(x
)
820 _augment(PrimeGroup
, _tmp
)
827 h ^
= 2*hash(info
.r
) & 0xffffffff
828 h ^
= 5*hash(info
.g
) & 0xffffffff
830 def _get_geval(me
, x
): return GF(x
)
831 _augment(BinGroup
, _tmp
)
834 def __hash__(me
): return 0x0ec23dab ^
hash(me
.info
)
835 def _get_geval(me
, x
): return x
.toec()
836 _augment(ECGroup
, _tmp
)
840 return '%r(%r)' %
(me
.group
, str(me
))
841 def _repr_pretty_(me
, pp
, cyclep
):
842 pp
.pretty(type(me
)._get_geval(me
))
845 ###--------------------------------------------------------------------------
846 ### RSA encoding techniques.
848 class PKCS1Crypt (object):
849 def __init__(me
, ep
= _bin(''), rng
= rand
):
852 def encode(me
, msg
, nbits
):
853 return _base
._p1crypt_encode(msg
, nbits
, me
.ep
, me
.rng
)
854 def decode(me
, ct
, nbits
):
855 return _base
._p1crypt_decode(ct
, nbits
, me
.ep
, me
.rng
)
857 class PKCS1Sig (object):
858 def __init__(me
, ep
= _bin(''), rng
= rand
):
861 def encode(me
, msg
, nbits
):
862 return _base
._p1sig_encode(msg
, nbits
, me
.ep
, me
.rng
)
863 def decode(me
, msg
, sig
, nbits
):
864 return _base
._p1sig_decode(msg
, sig
, nbits
, me
.ep
, me
.rng
)
867 def __init__(me
, mgf
= sha_mgf
, hash = sha
, ep
= _bin(''), rng
= rand
):
872 def encode(me
, msg
, nbits
):
873 return _base
._oaep_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
874 def decode(me
, ct
, nbits
):
875 return _base
._oaep_decode(ct
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
878 def __init__(me
, mgf
= sha_mgf
, hash = sha
, saltsz
= None, rng
= rand
):
885 def encode(me
, msg
, nbits
):
886 return _base
._pss_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
887 def decode(me
, msg
, sig
, nbits
):
888 return _base
._pss_decode(msg
, sig
, nbits
,
889 me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
892 def encrypt(me
, msg
, enc
):
893 return me
.pubop(enc
.encode(msg
, me
.n
.nbits
))
894 def verify(me
, msg
, sig
, enc
):
895 if msg
is None: return enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
897 x
= enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
898 return x
is None or x
== msg
902 return '%s(n = %r, e = %r)' %
(_clsname(me
), me
.n
, me
.e
)
903 def _repr_pretty_(me
, pp
, cyclep
):
904 ind
= _pp_bgroup_tyname(pp
, me
)
908 _pp_kv(pp
, 'n', me
.n
); pp
.text(','); pp
.breakable()
909 _pp_kv(pp
, 'e', me
.e
)
910 pp
.end_group(ind
, ')')
911 _augment(RSAPub
, _tmp
)
914 def decrypt(me
, ct
, enc
): return enc
.decode(me
.privop(ct
), me
.n
.nbits
)
915 def sign(me
, msg
, enc
): return me
.privop(enc
.encode(msg
, me
.n
.nbits
))
917 return '%s(n = %r, e = %r, d = %s, ' \
918 'p = %s, q = %s, dp = %s, dq = %s, q_inv = %s)' % \
919 (_clsname(me
), me
.n
, me
.e
,
920 _repr_secret(me
.d
), _repr_secret(me
.p
), _repr_secret(me
.q
),
921 _repr_secret(me
.dp
), _repr_secret(me
.dq
), _repr_secret(me
.q_inv
))
922 def _repr_pretty_(me
, pp
, cyclep
):
923 ind
= _pp_bgroup_tyname(pp
, me
)
927 _pp_kv(pp
, 'n', me
.n
); pp
.text(','); pp
.breakable()
928 _pp_kv(pp
, 'e', me
.e
); pp
.text(','); pp
.breakable()
929 _pp_kv(pp
, 'd', me
.d
, secretp
= True); pp
.text(','); pp
.breakable()
930 _pp_kv(pp
, 'p', me
.p
, secretp
= True); pp
.text(','); pp
.breakable()
931 _pp_kv(pp
, 'q', me
.q
, secretp
= True); pp
.text(','); pp
.breakable()
932 _pp_kv(pp
, 'dp', me
.dp
, secretp
= True); pp
.text(','); pp
.breakable()
933 _pp_kv(pp
, 'dq', me
.dq
, secretp
= True); pp
.text(','); pp
.breakable()
934 _pp_kv(pp
, 'q_inv', me
.q_inv
, secretp
= True)
935 pp
.end_group(ind
, ')')
936 _augment(RSAPriv
, _tmp
)
938 ###--------------------------------------------------------------------------
939 ### DSA and related schemes.
942 def __repr__(me
): return '%s(G = %r, p = %r, hash = %r)' % \
943 (_clsname(me
), me
.G
, me
.p
, me
.hash)
944 def _repr_pretty_(me
, pp
, cyclep
):
945 ind
= _pp_bgroup_tyname(pp
, me
)
949 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
950 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
951 _pp_kv(pp
, 'hash', me
.hash)
952 pp
.end_group(ind
, ')')
953 _augment(DSAPub
, _tmp
)
954 _augment(KCDSAPub
, _tmp
)
957 def __repr__(me
): return '%s(G = %r, u = %s, p = %r, hash = %r)' % \
958 (_clsname(me
), me
.G
, _repr_secret(me
.u
), me
.p
, me
.hash)
959 def _repr_pretty_(me
, pp
, cyclep
):
960 ind
= _pp_bgroup_tyname(pp
, me
)
964 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
965 _pp_kv(pp
, 'u', me
.u
, True); pp
.text(','); pp
.breakable()
966 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
967 _pp_kv(pp
, 'hash', me
.hash)
968 pp
.end_group(ind
, ')')
969 _augment(DSAPriv
, _tmp
)
970 _augment(KCDSAPriv
, _tmp
)
972 ###--------------------------------------------------------------------------
973 ### Bernstein's elliptic curve crypto and related schemes.
975 X25519_BASE
= MP(9).storel(32)
976 X448_BASE
= MP(5).storel(56)
978 Z128
= ByteString
.zero(16)
980 class _BasePub (object):
981 def __init__(me
, pub
, *args
, **kw
):
982 if not me
._PUBSZ
.check(len(pub
)): raise ValueError('bad public key')
983 super(_BasePub
, me
).__init__(*args
, **kw
)
985 def __repr__(me
): return '%s(pub = %r)' %
(_clsname(me
), me
.pub
)
986 def _pp(me
, pp
): _pp_kv(pp
, 'pub', me
.pub
)
987 def _repr_pretty_(me
, pp
, cyclep
):
988 ind
= _pp_bgroup_tyname(pp
, me
)
989 if cyclep
: pp
.text('...')
991 pp
.end_group(ind
, ')')
993 class _BasePriv (object):
994 def __init__(me
, priv
, pub
= None, *args
, **kw
):
995 if not me
._KEYSZ
.check(len(priv
)): raise ValueError('bad private key')
996 if pub
is None: pub
= me
._pubkey(priv
)
997 super(_BasePriv
, me
).__init__(pub
= pub
, *args
, **kw
)
1000 def generate(cls
, rng
= rand
):
1001 return cls(rng
.block(cls
._KEYSZ
.default
))
1003 return '%s(priv = %d, pub = %r)' % \
1004 (_clsname(me
), _repr_secret(me
.priv
), me
.pub
)
1006 _pp_kv(pp
, 'priv', me
.priv
, secretp
= True); pp
.text(','); pp
.breakable()
1007 super(_BasePriv
, me
)._pp(pp
)
1009 class _XDHPub (_BasePub
): pass
1011 class _XDHPriv (_BasePriv
):
1012 def _pubkey(me
, priv
): return me
._op(priv
, me
._BASE
)
1013 def agree(me
, you
): return me
._op(me
.priv
, you
.pub
)
1014 def boxkey(me
, recip
): return me
._hashkey(me
.agree(recip
))
1015 def box(me
, recip
, n
, m
): return secret_box(me
.boxkey(recip
), n
, m
)
1016 def unbox(me
, recip
, n
, c
): return secret_unbox(me
.boxkey(recip
), n
, c
)
1018 class X25519Pub (_XDHPub
):
1019 _PUBSZ
= KeySZSet(X25519_PUBSZ
)
1022 class X25519Priv (_XDHPriv
, X25519Pub
):
1023 _KEYSZ
= KeySZSet(X25519_KEYSZ
)
1024 def _op(me
, k
, X
): return x25519(k
, X
)
1025 def _hashkey(me
, z
): return hsalsa20_prf(z
, Z128
)
1027 class X448Pub (_XDHPub
):
1028 _PUBSZ
= KeySZSet(X448_PUBSZ
)
1031 class X448Priv (_XDHPriv
, X448Pub
):
1032 _KEYSZ
= KeySZSet(X448_KEYSZ
)
1033 def _op(me
, k
, X
): return x448(k
, X
)
1034 def _hashkey(me
, z
): return Shake256().hash(z
).done(salsa20
.keysz
.default
)
1036 class _EdDSAPub (_BasePub
):
1037 def beginhash(me
): return me
._HASH()
1038 def endhash(me
, h
): return h
.done()
1040 class _EdDSAPriv (_BasePriv
, _EdDSAPub
):
1043 class Ed25519Pub (_EdDSAPub
):
1044 _PUBSZ
= KeySZSet(ED25519_PUBSZ
)
1046 def verify(me
, msg
, sig
, **kw
):
1047 return ed25519_verify(me
.pub
, msg
, sig
, **kw
)
1049 class Ed25519Priv (_EdDSAPriv
, Ed25519Pub
):
1050 _KEYSZ
= KeySZAny(ED25519_KEYSZ
)
1051 def _pubkey(me
, priv
): return ed25519_pubkey(priv
)
1052 def sign(me
, msg
, **kw
):
1053 return ed25519_sign(me
.priv
, msg
, pub
= me
.pub
, **kw
)
1055 class Ed448Pub (_EdDSAPub
):
1056 _PUBSZ
= KeySZSet(ED448_PUBSZ
)
1058 def verify(me
, msg
, sig
, **kw
):
1059 return ed448_verify(me
.pub
, msg
, sig
, **kw
)
1061 class Ed448Priv (_EdDSAPriv
, Ed448Pub
):
1062 _KEYSZ
= KeySZAny(ED448_KEYSZ
)
1063 def _pubkey(me
, priv
): return ed448_pubkey(priv
)
1064 def sign(me
, msg
, **kw
):
1065 return ed448_sign(me
.priv
, msg
, pub
= me
.pub
, **kw
)
1067 ###--------------------------------------------------------------------------
1068 ### Built-in algorithm and group tables.
1072 return '{%s}' %
', '.join(['%r: %r' % kv
for kv
in _iteritems(me
)])
1073 def _repr_pretty_(me
, pp
, cyclep
):
1074 ind
= _pp_bgroup(pp
, '{ ')
1075 if cyclep
: pp
.text('...')
1076 else: _pp_dict(pp
, _iteritems(me
))
1077 pp
.end_group(ind
, ' }')
1078 _augment(_base
._MiscTable
, _tmp
)
1080 ###--------------------------------------------------------------------------
1081 ### Prime number generation.
1083 class PrimeGenEventHandler (object):
1084 def pg_begin(me
, ev
):
1085 return me
.pg_try(ev
)
1086 def pg_done(me
, ev
):
1088 def pg_abort(me
, ev
):
1090 def pg_fail(me
, ev
):
1092 def pg_pass(me
, ev
):
1095 class SophieGermainStepJump (object):
1096 def pg_begin(me
, ev
):
1097 me
.lf
= PrimeFilter(ev
.x
)
1098 me
.hf
= me
.lf
.muladd(2, 1)
1104 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
1106 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
1109 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
1112 def pg_done(me
, ev
):
1116 class SophieGermainStepper (SophieGermainStepJump
):
1117 def __init__(me
, step
):
1121 me
.lf
.step(me
.lstep
)
1122 me
.hf
.step(me
.hstep
)
1124 class SophieGermainJumper (SophieGermainStepJump
):
1125 def __init__(me
, jump
):
1126 me
.ljump
= PrimeFilter(jump
);
1127 me
.hjump
= me
.ljump
.muladd(2, 0)
1129 me
.lf
.jump(me
.ljump
)
1130 me
.hf
.jump(me
.hjump
)
1131 def pg_done(me
, ev
):
1134 SophieGermainStepJump
.pg_done(me
, ev
)
1136 class SophieGermainTester (object):
1139 def pg_begin(me
, ev
):
1140 me
.lr
= RabinMiller(ev
.x
)
1141 me
.hr
= RabinMiller(2 * ev
.x
+ 1)
1143 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
1144 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
1146 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
1147 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
1149 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
1152 def pg_done(me
, ev
):
1156 class PrimitiveStepper (PrimeGenEventHandler
):
1162 def pg_begin(me
, ev
):
1163 me
.i
= iter(smallprimes
)
1164 return me
.pg_try(ev
)
1166 class PrimitiveTester (PrimeGenEventHandler
):
1167 def __init__(me
, mod
, hh
= [], exp
= None):
1168 me
.mod
= MPMont(mod
)
1173 if me
.exp
is not None:
1174 x
= me
.mod
.exp(x
, me
.exp
)
1175 if x
== 1: return PGEN_FAIL
1177 if me
.mod
.exp(x
, h
) == 1: return PGEN_FAIL
1181 class SimulStepper (PrimeGenEventHandler
):
1182 def __init__(me
, mul
= 2, add
= 1, step
= 2):
1186 def _stepfn(me
, step
):
1188 raise ValueError('step must be positive')
1190 return lambda f
: f
.step(step
)
1191 j
= PrimeFilter(step
)
1192 return lambda f
: f
.jump(j
)
1193 def pg_begin(me
, ev
):
1195 me
.lf
= PrimeFilter(x
)
1196 me
.hf
= PrimeFilter(x
* me
.mul
+ me
.add
)
1197 me
.lstep
= me
._stepfn(me
.step
)
1198 me
.hstep
= me
._stepfn(me
.step
* me
.mul
)
1199 SimulStepper
._cont(me
, ev
)
1207 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
1209 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
1212 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
1215 def pg_done(me
, ev
):
1221 class SimulTester (PrimeGenEventHandler
):
1222 def __init__(me
, mul
= 2, add
= 1):
1225 def pg_begin(me
, ev
):
1227 me
.lr
= RabinMiller(x
)
1228 me
.hr
= RabinMiller(x
* me
.mul
+ me
.add
)
1230 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
1231 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
1233 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
1234 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
1236 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
1239 def pg_done(me
, ev
):
1243 def sgprime(start
, step
= 2, name
= 'p', event
= pgen_nullev
, nsteps
= 0):
1245 return pgen(start
, name
, SimulStepper(step
= step
), SimulTester(), event
,
1246 nsteps
, RabinMiller
.iters(start
.nbits
))
1248 def findprimitive(mod
, hh
= [], exp
= None, name
= 'g', event
= pgen_nullev
):
1249 return pgen(0, name
, PrimitiveStepper(), PrimitiveTester(mod
, hh
, exp
),
1252 def kcdsaprime(pbits
, qbits
, rng
= rand
,
1253 event
= pgen_nullev
, name
= 'p', nsteps
= 0):
1254 hbits
= pbits
- qbits
1255 h
= pgen(rng
.mp(hbits
, 1), name
+ ' [h]',
1256 PrimeGenStepper(2), PrimeGenTester(),
1257 event
, nsteps
, RabinMiller
.iters(hbits
))
1258 q
= pgen(rng
.mp(qbits
, 1), name
, SimulStepper(2 * h
, 1, 2),
1259 SimulTester(2 * h
, 1), event
, nsteps
, RabinMiller
.iters(qbits
))
1263 #----- That's all, folks ----------------------------------------------------