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
)
58 if _sys
.version_info
>= (3,): from . import _base
62 _sys
.setdlopenflags(_odlflags
)
64 del _dlflags
, _odlflags
66 ###--------------------------------------------------------------------------
69 ## For the benefit of the default keyreporter, we need the program name.
70 _base
._ego(_sys
.argv
[0])
72 ## Register our module.
73 _base
._set_home_module(_sys
.modules
[__name__
])
74 def default_lostexchook(why
, ty
, val
, tb
):
75 """`catacomb.lostexchook(WHY, TY, VAL, TB)' reports lost exceptions."""
76 _sys
.stderr
.write("\n\n!!! LOST EXCEPTION: %s\n" % why
)
77 _sys
.excepthook(ty
, val
, tb
)
78 _sys
.stderr
.write("\n")
79 lostexchook
= default_lostexchook
81 ## Text/binary conversions.
82 if _sys
.version_info
>= (3,):
83 def _bin(s
): return s
.encode('iso8859-1')
87 ## Iterating over dictionaries.
88 if _sys
.version_info
>= (3,):
89 def _iteritems(dict): return dict.items()
90 def _itervalues(dict): return dict.values()
92 def _iteritems(dict): return dict.iteritems()
93 def _itervalues(dict): return dict.itervalues()
95 ## The built-in bignum type.
97 except NameError: _long
= int
100 ## How to fix a name back into the right identifier. Alas, the rules are not
104 ## Hyphens consistently become underscores.
105 name
= name
.replace('-', '_')
107 ## But slashes might become underscores or just vanish.
108 if name
.startswith('salsa20'): name
= name
.replace('/', '')
109 else: name
= name
.replace('/', '_')
114 ## Initialize the module. Drag in the static methods of the various
115 ## classes; create names for the various known crypto algorithms.
122 for i
in [gcciphers
, gcaeads
, gchashes
, gcmacs
, gcprps
]:
123 for c
in _itervalues(i
):
124 d
[_fixname(c
.name
)] = c
125 for c
in _itervalues(gccrands
):
126 d
[_fixname(c
.name
+ 'rand')] = c
129 ## A handy function for our work: add the methods of a named class to an
130 ## existing class. This is how we write the Python-implemented parts of our
133 for i
in cc
.__dict__
:
135 if type(a
) is _types
.MethodType
:
137 elif type(a
) not in (_types
.FunctionType
, staticmethod, classmethod):
141 ## Parsing functions tend to return the object parsed and the remainder of
142 ## the input. This checks that the remainder is input and, if so, returns
147 raise SyntaxError('junk at end of string')
150 ## Some pretty-printing utilities.
151 PRINT_SECRETS
= False
152 def _clsname(me
): return type(me
).__name__
153 def _repr_secret(thing
, secretp
= True):
154 if not secretp
or PRINT_SECRETS
: return repr(thing
)
155 else: return '#<SECRET>'
156 def _pp_str(me
, pp
, cyclep
): pp
.text(cyclep
and '...' or str(me
))
157 def _pp_secret(pp
, thing
, secretp
= True):
158 if not secretp
or PRINT_SECRETS
: pp
.pretty(thing
)
159 else: pp
.text('#<SECRET>')
160 def _pp_bgroup(pp
, text
):
162 pp
.begin_group(ind
, text
)
164 def _pp_bgroup_tyname(pp
, obj
, open = '('):
165 return _pp_bgroup(pp
, _clsname(obj
) + open)
166 def _pp_kv(pp
, k
, v
, secretp
= False):
167 ind
= _pp_bgroup(pp
, k
+ ' = ')
168 _pp_secret(pp
, v
, secretp
)
169 pp
.end_group(ind
, '')
170 def _pp_commas(pp
, printfn
, items
):
173 if firstp
: firstp
= False
174 else: pp
.text(','); pp
.breakable()
176 def _pp_dict(pp
, items
):
187 _pp_commas(pp
, p
, items
)
189 ###--------------------------------------------------------------------------
192 if _sys
.version_info
>= (3,):
194 def __str__(me
): return '%s(%r)' %
(type(me
).__name__
, list(me
))
196 def _repr_pretty_(me
, pp
, cyclep
):
197 ind
= _pp_bgroup_tyname(pp
, me
, '([')
198 _pp_commas(pp
, pp
.pretty
, me
)
199 pp
.end_group(ind
, '])')
200 _augment(_base
._KeyView
, _tmp
)
201 _augment(_base
._ValueView
, _tmp
)
202 _augment(_base
._ItemView
, _tmp
)
204 ###--------------------------------------------------------------------------
209 return ByteString(_unhexify(x
))
210 fromhex
= staticmethod(fromhex
)
211 if _sys
.version_info
>= (3,):
212 def hex(me
): return _hexify(me
).decode()
214 def hex(me
): return _hexify(me
)
217 return 'bytes(%r)' % me
.hex()
218 _augment(ByteString
, _tmp
)
219 ByteString
.__hash__
= str.__hash__
220 bytes
= ByteString
.fromhex
222 ###--------------------------------------------------------------------------
223 ### Symmetric encryption.
226 def encrypt(me
, n
, m
, tsz
= None, h
= ByteString
.zero(0)):
227 if tsz
is None: tsz
= me
.__class__
.tagsz
.default
228 e
= me
.enc(n
, len(h
), len(m
), tsz
)
229 if not len(h
): a
= None
230 else: a
= e
.aad().hash(h
)
232 c1
, t
= e
.done(aad
= a
)
234 def decrypt(me
, n
, c
, t
, h
= ByteString
.zero(0)):
235 d
= me
.dec(n
, len(h
), len(c
), len(t
))
236 if not len(h
): a
= None
237 else: a
= d
.aad().hash(h
)
239 m
+= d
.done(t
, aad
= a
)
241 _augment(GAEKey
, _tmp
)
243 ###--------------------------------------------------------------------------
249 return ctstreq(h
, hh
)
250 _augment(GHash
, _tmp
)
251 _augment(Poly1305Hash
, _tmp
)
253 class _HashBase (object):
254 ## The standard hash methods. Assume that `hash' is defined and returns
256 def _check_range(me
, n
, max):
257 if not (0 <= n
<= max): raise OverflowError("out of range")
259 me
._check_range(n
, 0xff)
260 return me
.hash(_pack('B', n
))
262 me
._check_range(n
, 0xffff)
263 return me
.hash(_pack('<H', n
))
265 me
._check_range(n
, 0xffff)
266 return me
.hash(_pack('>H', n
))
269 me
._check_range(n
, 0xffffffff)
270 return me
.hash(_pack('<L', n
))
272 me
._check_range(n
, 0xffffffff)
273 return me
.hash(_pack('>L', n
))
276 me
._check_range(n
, 0xffffffffffffffff)
277 return me
.hash(_pack('<Q', n
))
279 me
._check_range(n
, 0xffffffffffffffff)
280 return me
.hash(_pack('>Q', n
))
282 def hashbuf8(me
, s
): return me
.hashu8(len(s
)).hash(s
)
283 def hashbuf16l(me
, s
): return me
.hashu16l(len(s
)).hash(s
)
284 def hashbuf16b(me
, s
): return me
.hashu16b(len(s
)).hash(s
)
285 hashbuf16
= hashbuf16b
286 def hashbuf32l(me
, s
): return me
.hashu32l(len(s
)).hash(s
)
287 def hashbuf32b(me
, s
): return me
.hashu32b(len(s
)).hash(s
)
288 hashbuf32
= hashbuf32b
289 def hashbuf64l(me
, s
): return me
.hashu64l(len(s
)).hash(s
)
290 def hashbuf64b(me
, s
): return me
.hashu64b(len(s
)).hash(s
)
291 hashbuf64
= hashbuf64b
292 def hashstrz(me
, s
): return me
.hash(s
).hashu8(0)
294 class _ShakeBase (_HashBase
):
296 ## Python gets really confused if I try to augment `__new__' on native
297 ## classes, so wrap and delegate. Sorry.
298 def __init__(me
, perso
= _bin(''), *args
, **kw
):
299 super(_ShakeBase
, me
).__init__(*args
, **kw
)
300 me
._h
= me
._SHAKE(perso
= perso
, func
= me
._FUNC
)
302 ## Delegate methods...
303 def copy(me
): new
= me
.__class__
._bare_new(); new
._copy(me
); return new
304 def _copy(me
, other
): me
._h
= other
._h
.copy()
305 def hash(me
, m
): me
._h
.hash(m
); return me
306 def xof(me
): me
._h
.xof(); return me
307 def get(me
, n
): return me
._h
.get(n
)
308 def mask(me
, m
): return me
._h
.mask(m
)
309 def done(me
, n
): return me
._h
.done(n
)
310 def check(me
, h
): return ctstreq(h
, me
.done(len(h
)))
312 def state(me
): return me
._h
.state
314 def buffered(me
): return me
._h
.buffered
316 def rate(me
): return me
._h
.rate
318 def _bare_new(cls
): return cls()
322 return ctstreq(h
, me
.done(len(h
)))
325 return me
.hashu8(len(nn
)).hash(nn
)
328 return me
.hash(nn
).hashu8(len(nn
))
329 def stringenc(me
, str):
330 return me
.leftenc(8*len(str)).hash(str)
331 def bytepad_before(me
):
332 return me
.leftenc(me
.rate
)
333 def bytepad_after(me
):
334 if me
.buffered
: me
.hash(me
._Z
[:me
.rate
- me
.buffered
])
341 _augment(Shake
, _tmp
)
342 _augment(_ShakeBase
, _tmp
)
343 Shake
._Z
= _ShakeBase
._Z
= ByteString
.zero(200)
345 class KMAC (_ShakeBase
):
347 def __init__(me
, k
, *arg
, **kw
):
348 super(KMAC
, me
).__init__(*arg
, **kw
)
349 with me
.bytepad(): me
.stringenc(k
)
350 def done(me
, n
= -1):
351 if n
< 0: n
= me
._TAGSZ
353 return super(KMAC
, me
).done(n
)
356 return super(KMAC
, me
).xof()
358 def _bare_new(cls
): return cls(_bin(""))
360 class KMAC128 (KMAC
): _SHAKE
= Shake128
; _TAGSZ
= 16
361 class KMAC256 (KMAC
): _SHAKE
= Shake256
; _TAGSZ
= 32
363 ###--------------------------------------------------------------------------
364 ### NaCl `secretbox'.
366 def secret_box(k
, n
, m
):
367 y
, t
= salsa20_naclbox(k
).encrypt(n
, m
)
370 def secret_unbox(k
, n
, c
):
372 return salsa20_naclbox(k
).decrypt(n
, c
[tsz
:], c
[0:tsz
])
374 ###--------------------------------------------------------------------------
375 ### Multiprecision integers and binary polynomials.
378 if isinstance(x
, BaseRat
): return x
._n
, x
._d
380 class BaseRat (object):
381 """Base class implementing fields of fractions over Euclidean domains."""
382 def __new__(cls
, a
, b
):
383 a
, b
= cls
.RING(a
), cls
.RING(b
)
387 me
= super(BaseRat
, cls
).__new__(cls
)
392 def numer(me
): return me
._n
394 def denom(me
): return me
._d
395 def __str__(me
): return '%s/%s' %
(me
._n
, me
._d
)
396 def __repr__(me
): return '%s(%s, %s)' %
(_clsname(me
), me
._n
, me
._d
)
397 _repr_pretty_
= _pp_str
399 def __add__(me
, you
):
400 n
, d
= _split_rat(you
)
401 return type(me
)(me
._n
*d
+ n
*me
._d
, d
*me
._d
)
403 def __sub__(me
, you
):
404 n
, d
= _split_rat(you
)
405 return type(me
)(me
._n
*d
- n
*me
._d
, d
*me
._d
)
406 def __rsub__(me
, you
):
407 n
, d
= _split_rat(you
)
408 return type(me
)(n
*me
._d
- me
._n
*d
, d
*me
._d
)
409 def __mul__(me
, you
):
410 n
, d
= _split_rat(you
)
411 return type(me
)(me
._n
*n
, me
._d
*d
)
413 def __truediv__(me
, you
):
414 n
, d
= _split_rat(you
)
415 return type(me
)(me
._n
*d
, me
._d
*n
)
416 def __rtruediv__(me
, you
):
417 n
, d
= _split_rat(you
)
418 return type(me
)(me
._d
*n
, me
._n
*d
)
419 if _sys
.version_info
< (3,):
420 __div__
= __truediv__
421 __rdiv__
= __rtruediv__
422 def _order(me
, you
, op
):
423 n
, d
= _split_rat(you
)
424 return op(me
._n
*d
, n
*me
._d
)
425 def __eq__(me
, you
): return me
._order(you
, lambda x
, y
: x
== y
)
426 def __ne__(me
, you
): return me
._order(you
, lambda x
, y
: x
!= y
)
427 def __le__(me
, you
): return me
._order(you
, lambda x
, y
: x
<= y
)
428 def __lt__(me
, you
): return me
._order(you
, lambda x
, y
: x
< y
)
429 def __gt__(me
, you
): return me
._order(you
, lambda x
, y
: x
> y
)
430 def __ge__(me
, you
): return me
._order(you
, lambda x
, y
: x
>= y
)
432 class IntRat (BaseRat
):
434 def __new__(cls
, a
, b
):
435 if isinstance(a
, float) or isinstance(b
, float): return a
/b
436 return super(IntRat
, cls
).__new__(cls
, a
, b
)
437 def __float__(me
): return float(me
._n
)/float(me
._d
)
439 class GFRat (BaseRat
):
443 def negp(x
): return x
< 0
444 def posp(x
): return x
> 0
445 def zerop(x
): return x
== 0
446 def oddp(x
): return x
.testbit(0)
447 def evenp(x
): return not x
.testbit(0)
448 def mont(x
): return MPMont(x
)
449 def barrett(x
): return MPBarrett(x
)
450 def reduce(x
): return MPReduce(x
)
451 def __truediv__(me
, you
):
452 if isinstance(you
, float): return _long(me
)/you
453 else: return IntRat(me
, you
)
454 def __rtruediv__(me
, you
):
455 if isinstance(you
, float): return you
/_long(me
)
456 else: return IntRat(you
, me
)
457 if _sys
.version_info
< (3,):
458 __div__
= __truediv__
459 __rdiv__
= __rtruediv__
460 _repr_pretty_
= _pp_str
464 def zerop(x
): return x
== 0
465 def reduce(x
): return GFReduce(x
)
466 def trace(x
, y
): return x
.reduce().trace(y
)
467 def halftrace(x
, y
): return x
.reduce().halftrace(y
)
468 def modsqrt(x
, y
): return x
.reduce().sqrt(y
)
469 def quadsolve(x
, y
): return x
.reduce().quadsolve(y
)
470 def __truediv__(me
, you
): return GFRat(me
, you
)
471 def __rtruediv__(me
, you
): return GFRat(you
, me
)
472 if _sys
.version_info
< (3,):
473 __div__
= __truediv__
474 __rdiv__
= __rtruediv__
475 _repr_pretty_
= _pp_str
480 'product(ITERABLE) or product(I, ...) -> PRODUCT'
481 return MPMul(*arg
).done()
482 product
= staticmethod(product
)
483 _augment(MPMul
, _tmp
)
485 ###--------------------------------------------------------------------------
489 def fromstring(str): return _checkend(Field
.parse(str))
490 fromstring
= staticmethod(fromstring
)
491 _augment(Field
, _tmp
)
494 def __repr__(me
): return '%s(%s)' %
(_clsname(me
), me
.p
)
495 def __hash__(me
): return 0x114401de ^
hash(me
.p
)
496 def _repr_pretty_(me
, pp
, cyclep
):
497 ind
= _pp_bgroup_tyname(pp
, me
)
498 if cyclep
: pp
.text('...')
499 else: pp
.pretty(me
.p
)
500 pp
.end_group(ind
, ')')
501 def ec(me
, a
, b
): return ECPrimeProjCurve(me
, a
, b
)
502 _augment(PrimeField
, _tmp
)
505 def __repr__(me
): return '%s(%#x)' %
(_clsname(me
), me
.p
)
506 def ec(me
, a
, b
): return ECBinProjCurve(me
, a
, b
)
507 def _repr_pretty_(me
, pp
, cyclep
):
508 ind
= _pp_bgroup_tyname(pp
, me
)
509 if cyclep
: pp
.text('...')
510 else: pp
.text('%#x' % me
.p
)
511 pp
.end_group(ind
, ')')
512 _augment(BinField
, _tmp
)
515 def __hash__(me
): return 0x23e4701c ^
hash(me
.p
)
516 _augment(BinPolyField
, _tmp
)
522 h ^
= 2*hash(me
.beta
) & 0xffffffff
524 _augment(BinNormField
, _tmp
)
527 def __str__(me
): return str(me
.value
)
528 def __repr__(me
): return '%s(%s)' %
(repr(me
.field
), repr(me
.value
))
529 _repr_pretty_
= _pp_str
532 ###--------------------------------------------------------------------------
537 return '%s(%r, %s, %s)' %
(_clsname(me
), me
.field
, me
.a
, me
.b
)
538 def _repr_pretty_(me
, pp
, cyclep
):
539 ind
= _pp_bgroup_tyname(pp
, me
)
543 pp
.pretty(me
.field
); pp
.text(','); pp
.breakable()
544 pp
.pretty(me
.a
); pp
.text(','); pp
.breakable()
546 pp
.end_group(ind
, ')')
548 return ecpt
.frombuf(me
, s
)
550 return ecpt
.fromraw(me
, s
)
553 _augment(ECCurve
, _tmp
)
559 h ^
= 2*hash(me
.a
) ^
0xffffffff
560 h ^
= 5*hash(me
.b
) ^
0xffffffff
562 _augment(ECPrimeCurve
, _tmp
)
568 h ^
= 2*hash(me
.a
) ^
0xffffffff
569 h ^
= 5*hash(me
.b
) ^
0xffffffff
571 _augment(ECBinCurve
, _tmp
)
575 if not me
: return '%s()' %
_clsname(me
)
576 return '%s(%s, %s)' %
(_clsname(me
), me
.ix
, me
.iy
)
578 if not me
: return 'inf'
579 return '(%s, %s)' %
(me
.ix
, me
.iy
)
580 def _repr_pretty_(me
, pp
, cyclep
):
586 ind
= _pp_bgroup(pp
, '(')
587 pp
.pretty(me
.ix
); pp
.text(','); pp
.breakable()
589 pp
.end_group(ind
, ')')
594 return '%s(curve = %r, G = %r, r = %s, h = %s)' % \
595 (_clsname(me
), me
.curve
, me
.G
, me
.r
, me
.h
)
596 def _repr_pretty_(me
, pp
, cyclep
):
597 ind
= _pp_bgroup_tyname(pp
, me
)
601 _pp_kv(pp
, 'curve', me
.curve
); pp
.text(','); pp
.breakable()
602 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
603 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
604 _pp_kv(pp
, 'h', me
.h
)
605 pp
.end_group(ind
, ')')
609 h ^
= 2*hash(me
.G
) & 0xffffffff
613 _augment(ECInfo
, _tmp
)
617 if not me
: return '%r()' %
(me
.curve
)
618 return '%r(%s, %s)' %
(me
.curve
, me
.x
, me
.y
)
620 if not me
: return 'inf'
621 return '(%s, %s)' %
(me
.x
, me
.y
)
622 def _repr_pretty_(me
, pp
, cyclep
):
628 ind
= _pp_bgroup(pp
, '(')
629 pp
.pretty(me
.x
); pp
.text(','); pp
.breakable()
631 pp
.end_group(ind
, ')')
632 _augment(ECPtCurve
, _tmp
)
634 ###--------------------------------------------------------------------------
638 def __repr__(me
): return '%s(%d)' %
(_clsname(me
), me
.default
)
639 def check(me
, sz
): return True
640 def best(me
, sz
): return sz
641 def pad(me
, sz
): return sz
642 _augment(KeySZAny
, _tmp
)
646 return '%s(%d, %d, %d, %d)' % \
647 (_clsname(me
), me
.default
, me
.min, me
.max, me
.mod
)
648 def _repr_pretty_(me
, pp
, cyclep
):
649 ind
= _pp_bgroup_tyname(pp
, me
)
653 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
654 pp
.pretty(me
.min); pp
.text(','); pp
.breakable()
655 pp
.pretty(me
.max); pp
.text(','); pp
.breakable()
657 pp
.end_group(ind
, ')')
658 def check(me
, sz
): return me
.min <= sz
<= me
.max and sz
%me
.mod
== 0
660 if sz
< me
.min: raise ValueError('key too small')
661 elif sz
> me
.max: return me
.max
662 else: return sz
- sz
%me
.mod
664 if sz
> me
.max: raise ValueError('key too large')
665 elif sz
< me
.min: return me
.min
666 else: sz
+= me
.mod
- 1; return sz
- sz
%me
.mod
667 _augment(KeySZRange
, _tmp
)
670 def __repr__(me
): return '%s(%d, %s)' %
(_clsname(me
), me
.default
, me
.set)
671 def _repr_pretty_(me
, pp
, cyclep
):
672 ind
= _pp_bgroup_tyname(pp
, me
)
676 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
677 ind1
= _pp_bgroup(pp
, '{')
678 _pp_commas(pp
, pp
.pretty
, me
.set)
679 pp
.end_group(ind1
, '}')
680 pp
.end_group(ind
, ')')
681 def check(me
, sz
): return sz
in me
.set
685 if found
< i
<= sz
: found
= i
686 if found
< 0: raise ValueError('key too small')
691 if sz
<= i
and (found
== -1 or i
< found
): found
= i
692 if found
< 0: raise ValueError('key too large')
694 _augment(KeySZSet
, _tmp
)
696 ###--------------------------------------------------------------------------
697 ### Key data objects.
700 def merge(me
, file, report
= None):
701 """KF.merge(FILE, [report = <built-in-reporter>])"""
705 me
.mergeline(name
, lno
, line
, report
)
708 def __repr__(me
): return '%s(%r)' %
(_clsname(me
), me
.name
)
709 _augment(KeyFile
, _tmp
)
712 def extract(me
, file, filter = ''):
713 """KEY.extract(FILE, [filter = <any>])"""
714 line
= me
.extractline(filter)
717 def __repr__(me
): return '%s(%r)' %
(_clsname(me
), me
.fulltag
)
722 return '%s({%s})' %
(_clsname(me
),
723 ', '.join(['%r: %r' % kv
for kv
in _iteritems(me
)()]))
724 def _repr_pretty_(me
, pp
, cyclep
):
725 ind
= _pp_bgroup_tyname(pp
, me
)
726 if cyclep
: pp
.text('...')
727 else: _pp_dict(pp
, _iteritems(me
))
728 pp
.end_group(ind
, ')')
729 _augment(KeyAttributes
, _tmp
)
733 return '%s(%s, %r)' %
(_clsname(me
),
734 _repr_secret(me
._guts(),
735 not (me
.flags
& KF_NONSECRET
)),
736 me
.writeflags(me
.flags
))
737 def _repr_pretty_(me
, pp
, cyclep
):
738 ind
= _pp_bgroup_tyname(pp
, me
)
742 _pp_secret(pp
, me
._guts(), not (me
.flags
& KF_NONSECRET
))
743 pp
.text(','); pp
.breakable()
744 pp
.pretty(me
.writeflags(me
.flags
))
745 pp
.end_group(ind
, ')')
746 def __hash__(me
): return me
._HASHBASE ^
hash(me
._guts())
748 return type(me
) == type(kd
) and \
749 me
._guts() == kd
._guts() and \
753 _augment(KeyData
, _tmp
)
756 def _guts(me
): return me
.bin
758 return isinstance(kd
, KeyDataBinary
) and me
.bin
== kd
.bin
759 _augment(KeyDataBinary
, _tmp
)
760 KeyDataBinary
._HASHBASE
= 0x961755c3
763 def _guts(me
): return me
.ct
764 _augment(KeyDataEncrypted
, _tmp
)
765 KeyDataEncrypted
._HASHBASE
= 0xffe000d4
768 def _guts(me
): return me
.mp
769 _augment(KeyDataMP
, _tmp
)
770 KeyDataMP
._HASHBASE
= 0x1cb64d69
773 def _guts(me
): return me
.str
774 _augment(KeyDataString
, _tmp
)
775 KeyDataString
._HASHBASE
= 0x349c33ea
778 def _guts(me
): return me
.ecpt
779 _augment(KeyDataECPt
, _tmp
)
780 KeyDataECPt
._HASHBASE
= 0x2509718b
784 return '%s({%s})' %
(_clsname(me
),
785 ', '.join(['%r: %r' % kv
for kv
in _iteritems(me
)]))
786 def _repr_pretty_(me
, pp
, cyclep
):
787 ind
= _pp_bgroup_tyname(pp
, me
, '({ ')
788 if cyclep
: pp
.text('...')
789 else: _pp_dict(pp
, _iteritems(me
))
790 pp
.end_group(ind
, ' })')
793 for k
, v
in _iteritems(me
):
794 h
= ((h
<< 1) ^
3*hash(k
) ^
5*hash(v
))&0xffffffff
797 if type(me
) != type(kd
) or me
.flags
!= kd
.flags
or len(me
) != len(kd
):
799 for k
, v
in _iteritems(me
):
801 except KeyError: return False
802 if v
!= vv
: return False
804 _augment(KeyDataStructured
, _tmp
)
805 KeyDataStructured
._HASHBASE
= 0x85851b21
807 ###--------------------------------------------------------------------------
812 return '%s(p = %s, r = %s, g = %s)' %
(_clsname(me
), me
.p
, me
.r
, me
.g
)
813 def _repr_pretty_(me
, pp
, cyclep
):
814 ind
= _pp_bgroup_tyname(pp
, me
)
818 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
819 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
820 _pp_kv(pp
, 'g', me
.g
)
821 pp
.end_group(ind
, ')')
822 _augment(FGInfo
, _tmp
)
825 def group(me
): return PrimeGroup(me
)
826 _augment(DHInfo
, _tmp
)
829 def group(me
): return BinGroup(me
)
830 _augment(BinDHInfo
, _tmp
)
834 return '%s(%r)' %
(_clsname(me
), me
.info
)
835 def _repr_pretty_(me
, pp
, cyclep
):
836 ind
= _pp_bgroup_tyname(pp
, me
)
837 if cyclep
: pp
.text('...')
838 else: pp
.pretty(me
.info
)
839 pp
.end_group(ind
, ')')
840 _augment(Group
, _tmp
)
847 h ^
= 2*hash(info
.r
) & 0xffffffff
848 h ^
= 5*hash(info
.g
) & 0xffffffff
850 def _get_geval(me
, x
): return MP(x
)
851 _augment(PrimeGroup
, _tmp
)
858 h ^
= 2*hash(info
.r
) & 0xffffffff
859 h ^
= 5*hash(info
.g
) & 0xffffffff
861 def _get_geval(me
, x
): return GF(x
)
862 _augment(BinGroup
, _tmp
)
865 def __hash__(me
): return 0x0ec23dab ^
hash(me
.info
)
866 def _get_geval(me
, x
): return x
.toec()
867 _augment(ECGroup
, _tmp
)
871 return '%r(%r)' %
(me
.group
, str(me
))
872 def _repr_pretty_(me
, pp
, cyclep
):
873 pp
.pretty(type(me
)._get_geval(me
))
876 ###--------------------------------------------------------------------------
877 ### RSA encoding techniques.
879 class PKCS1Crypt (object):
880 def __init__(me
, ep
= _bin(''), rng
= rand
):
883 def encode(me
, msg
, nbits
):
884 return _base
._p1crypt_encode(msg
, nbits
, me
.ep
, me
.rng
)
885 def decode(me
, ct
, nbits
):
886 return _base
._p1crypt_decode(ct
, nbits
, me
.ep
, me
.rng
)
888 class PKCS1Sig (object):
889 def __init__(me
, ep
= _bin(''), rng
= rand
):
892 def encode(me
, msg
, nbits
):
893 return _base
._p1sig_encode(msg
, nbits
, me
.ep
, me
.rng
)
894 def decode(me
, msg
, sig
, nbits
):
895 return _base
._p1sig_decode(msg
, sig
, nbits
, me
.ep
, me
.rng
)
898 def __init__(me
, mgf
= sha_mgf
, hash = sha
, ep
= _bin(''), rng
= rand
):
903 def encode(me
, msg
, nbits
):
904 return _base
._oaep_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
905 def decode(me
, ct
, nbits
):
906 return _base
._oaep_decode(ct
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
909 def __init__(me
, mgf
= sha_mgf
, hash = sha
, saltsz
= None, rng
= rand
):
916 def encode(me
, msg
, nbits
):
917 return _base
._pss_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
918 def decode(me
, msg
, sig
, nbits
):
919 return _base
._pss_decode(msg
, sig
, nbits
,
920 me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
923 def encrypt(me
, msg
, enc
):
924 return me
.pubop(enc
.encode(msg
, me
.n
.nbits
))
925 def verify(me
, msg
, sig
, enc
):
926 if msg
is None: return enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
928 x
= enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
929 return x
is None or x
== msg
933 return '%s(n = %r, e = %r)' %
(_clsname(me
), me
.n
, me
.e
)
934 def _repr_pretty_(me
, pp
, cyclep
):
935 ind
= _pp_bgroup_tyname(pp
, me
)
939 _pp_kv(pp
, 'n', me
.n
); pp
.text(','); pp
.breakable()
940 _pp_kv(pp
, 'e', me
.e
)
941 pp
.end_group(ind
, ')')
942 _augment(RSAPub
, _tmp
)
945 def decrypt(me
, ct
, enc
): return enc
.decode(me
.privop(ct
), me
.n
.nbits
)
946 def sign(me
, msg
, enc
): return me
.privop(enc
.encode(msg
, me
.n
.nbits
))
948 return '%s(n = %r, e = %r, d = %s, ' \
949 'p = %s, q = %s, dp = %s, dq = %s, q_inv = %s)' % \
950 (_clsname(me
), me
.n
, me
.e
,
951 _repr_secret(me
.d
), _repr_secret(me
.p
), _repr_secret(me
.q
),
952 _repr_secret(me
.dp
), _repr_secret(me
.dq
), _repr_secret(me
.q_inv
))
953 def _repr_pretty_(me
, pp
, cyclep
):
954 ind
= _pp_bgroup_tyname(pp
, me
)
958 _pp_kv(pp
, 'n', me
.n
); pp
.text(','); pp
.breakable()
959 _pp_kv(pp
, 'e', me
.e
); pp
.text(','); pp
.breakable()
960 _pp_kv(pp
, 'd', me
.d
, secretp
= True); pp
.text(','); pp
.breakable()
961 _pp_kv(pp
, 'p', me
.p
, secretp
= True); pp
.text(','); pp
.breakable()
962 _pp_kv(pp
, 'q', me
.q
, secretp
= True); pp
.text(','); pp
.breakable()
963 _pp_kv(pp
, 'dp', me
.dp
, secretp
= True); pp
.text(','); pp
.breakable()
964 _pp_kv(pp
, 'dq', me
.dq
, secretp
= True); pp
.text(','); pp
.breakable()
965 _pp_kv(pp
, 'q_inv', me
.q_inv
, secretp
= True)
966 pp
.end_group(ind
, ')')
967 _augment(RSAPriv
, _tmp
)
969 ###--------------------------------------------------------------------------
970 ### DSA and related schemes.
973 def __repr__(me
): return '%s(G = %r, p = %r, hash = %r)' % \
974 (_clsname(me
), me
.G
, me
.p
, me
.hash)
975 def _repr_pretty_(me
, pp
, cyclep
):
976 ind
= _pp_bgroup_tyname(pp
, me
)
980 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
981 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
982 _pp_kv(pp
, 'hash', me
.hash)
983 pp
.end_group(ind
, ')')
984 _augment(DSAPub
, _tmp
)
985 _augment(KCDSAPub
, _tmp
)
988 def __repr__(me
): return '%s(G = %r, u = %s, p = %r, hash = %r)' % \
989 (_clsname(me
), me
.G
, _repr_secret(me
.u
), me
.p
, me
.hash)
990 def _repr_pretty_(me
, pp
, cyclep
):
991 ind
= _pp_bgroup_tyname(pp
, me
)
995 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
996 _pp_kv(pp
, 'u', me
.u
, True); pp
.text(','); pp
.breakable()
997 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
998 _pp_kv(pp
, 'hash', me
.hash)
999 pp
.end_group(ind
, ')')
1000 _augment(DSAPriv
, _tmp
)
1001 _augment(KCDSAPriv
, _tmp
)
1003 ###--------------------------------------------------------------------------
1004 ### Bernstein's elliptic curve crypto and related schemes.
1006 X25519_BASE
= MP(9).storel(32)
1007 X448_BASE
= MP(5).storel(56)
1009 Z128
= ByteString
.zero(16)
1011 class _BasePub (object):
1012 def __init__(me
, pub
, *args
, **kw
):
1013 if not me
._PUBSZ
.check(len(pub
)): raise ValueError('bad public key')
1014 super(_BasePub
, me
).__init__(*args
, **kw
)
1016 def __repr__(me
): return '%s(pub = %r)' %
(_clsname(me
), me
.pub
)
1017 def _pp(me
, pp
): _pp_kv(pp
, 'pub', me
.pub
)
1018 def _repr_pretty_(me
, pp
, cyclep
):
1019 ind
= _pp_bgroup_tyname(pp
, me
)
1020 if cyclep
: pp
.text('...')
1022 pp
.end_group(ind
, ')')
1024 class _BasePriv (object):
1025 def __init__(me
, priv
, pub
= None, *args
, **kw
):
1026 if not me
._KEYSZ
.check(len(priv
)): raise ValueError('bad private key')
1027 if pub
is None: pub
= me
._pubkey(priv
)
1028 super(_BasePriv
, me
).__init__(pub
= pub
, *args
, **kw
)
1031 def generate(cls
, rng
= rand
):
1032 return cls(rng
.block(cls
._KEYSZ
.default
))
1034 return '%s(priv = %d, pub = %r)' % \
1035 (_clsname(me
), _repr_secret(me
.priv
), me
.pub
)
1037 _pp_kv(pp
, 'priv', me
.priv
, secretp
= True); pp
.text(','); pp
.breakable()
1038 super(_BasePriv
, me
)._pp(pp
)
1040 class _XDHPub (_BasePub
): pass
1042 class _XDHPriv (_BasePriv
):
1043 def _pubkey(me
, priv
): return me
._op(priv
, me
._BASE
)
1044 def agree(me
, you
): return me
._op(me
.priv
, you
.pub
)
1045 def boxkey(me
, recip
): return me
._hashkey(me
.agree(recip
))
1046 def box(me
, recip
, n
, m
): return secret_box(me
.boxkey(recip
), n
, m
)
1047 def unbox(me
, recip
, n
, c
): return secret_unbox(me
.boxkey(recip
), n
, c
)
1049 class X25519Pub (_XDHPub
):
1050 _PUBSZ
= KeySZSet(X25519_PUBSZ
)
1053 class X25519Priv (_XDHPriv
, X25519Pub
):
1054 _KEYSZ
= KeySZSet(X25519_KEYSZ
)
1055 def _op(me
, k
, X
): return x25519(k
, X
)
1056 def _hashkey(me
, z
): return hsalsa20_prf(z
, Z128
)
1058 class X448Pub (_XDHPub
):
1059 _PUBSZ
= KeySZSet(X448_PUBSZ
)
1062 class X448Priv (_XDHPriv
, X448Pub
):
1063 _KEYSZ
= KeySZSet(X448_KEYSZ
)
1064 def _op(me
, k
, X
): return x448(k
, X
)
1065 def _hashkey(me
, z
): return Shake256().hash(z
).done(salsa20
.keysz
.default
)
1067 class _EdDSAPub (_BasePub
):
1068 def beginhash(me
): return me
._HASH()
1069 def endhash(me
, h
): return h
.done()
1071 class _EdDSAPriv (_BasePriv
, _EdDSAPub
):
1074 class Ed25519Pub (_EdDSAPub
):
1075 _PUBSZ
= KeySZSet(ED25519_PUBSZ
)
1077 def verify(me
, msg
, sig
, **kw
):
1078 return ed25519_verify(me
.pub
, msg
, sig
, **kw
)
1080 class Ed25519Priv (_EdDSAPriv
, Ed25519Pub
):
1081 _KEYSZ
= KeySZAny(ED25519_KEYSZ
)
1082 def _pubkey(me
, priv
): return ed25519_pubkey(priv
)
1083 def sign(me
, msg
, **kw
):
1084 return ed25519_sign(me
.priv
, msg
, pub
= me
.pub
, **kw
)
1086 class Ed448Pub (_EdDSAPub
):
1087 _PUBSZ
= KeySZSet(ED448_PUBSZ
)
1089 def verify(me
, msg
, sig
, **kw
):
1090 return ed448_verify(me
.pub
, msg
, sig
, **kw
)
1092 class Ed448Priv (_EdDSAPriv
, Ed448Pub
):
1093 _KEYSZ
= KeySZAny(ED448_KEYSZ
)
1094 def _pubkey(me
, priv
): return ed448_pubkey(priv
)
1095 def sign(me
, msg
, **kw
):
1096 return ed448_sign(me
.priv
, msg
, pub
= me
.pub
, **kw
)
1098 ###--------------------------------------------------------------------------
1099 ### Built-in algorithm and group tables.
1103 return '{%s}' %
', '.join(['%r: %r' % kv
for kv
in _iteritems(me
)])
1104 def _repr_pretty_(me
, pp
, cyclep
):
1105 ind
= _pp_bgroup(pp
, '{ ')
1106 if cyclep
: pp
.text('...')
1107 else: _pp_dict(pp
, _iteritems(me
))
1108 pp
.end_group(ind
, ' }')
1109 _augment(_base
._MiscTable
, _tmp
)
1111 ###--------------------------------------------------------------------------
1112 ### Prime number generation.
1114 class PrimeGenEventHandler (object):
1115 def pg_begin(me
, ev
):
1116 return me
.pg_try(ev
)
1117 def pg_done(me
, ev
):
1119 def pg_abort(me
, ev
):
1121 def pg_fail(me
, ev
):
1123 def pg_pass(me
, ev
):
1126 class SophieGermainStepJump (object):
1127 def pg_begin(me
, ev
):
1128 me
.lf
= PrimeFilter(ev
.x
)
1129 me
.hf
= me
.lf
.muladd(2, 1)
1135 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
1137 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
1140 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
1143 def pg_done(me
, ev
):
1147 class SophieGermainStepper (SophieGermainStepJump
):
1148 def __init__(me
, step
):
1152 me
.lf
.step(me
.lstep
)
1153 me
.hf
.step(me
.hstep
)
1155 class SophieGermainJumper (SophieGermainStepJump
):
1156 def __init__(me
, jump
):
1157 me
.ljump
= PrimeFilter(jump
);
1158 me
.hjump
= me
.ljump
.muladd(2, 0)
1160 me
.lf
.jump(me
.ljump
)
1161 me
.hf
.jump(me
.hjump
)
1162 def pg_done(me
, ev
):
1165 SophieGermainStepJump
.pg_done(me
, ev
)
1167 class SophieGermainTester (object):
1170 def pg_begin(me
, ev
):
1171 me
.lr
= RabinMiller(ev
.x
)
1172 me
.hr
= RabinMiller(2 * ev
.x
+ 1)
1174 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
1175 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
1177 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
1178 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
1180 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
1183 def pg_done(me
, ev
):
1187 class PrimitiveStepper (PrimeGenEventHandler
):
1193 def pg_begin(me
, ev
):
1194 me
.i
= iter(smallprimes
)
1195 return me
.pg_try(ev
)
1197 class PrimitiveTester (PrimeGenEventHandler
):
1198 def __init__(me
, mod
, hh
= [], exp
= None):
1199 me
.mod
= MPMont(mod
)
1204 if me
.exp
is not None:
1205 x
= me
.mod
.exp(x
, me
.exp
)
1206 if x
== 1: return PGEN_FAIL
1208 if me
.mod
.exp(x
, h
) == 1: return PGEN_FAIL
1212 class SimulStepper (PrimeGenEventHandler
):
1213 def __init__(me
, mul
= 2, add
= 1, step
= 2):
1217 def _stepfn(me
, step
):
1219 raise ValueError('step must be positive')
1221 return lambda f
: f
.step(step
)
1222 j
= PrimeFilter(step
)
1223 return lambda f
: f
.jump(j
)
1224 def pg_begin(me
, ev
):
1226 me
.lf
= PrimeFilter(x
)
1227 me
.hf
= PrimeFilter(x
* me
.mul
+ me
.add
)
1228 me
.lstep
= me
._stepfn(me
.step
)
1229 me
.hstep
= me
._stepfn(me
.step
* me
.mul
)
1230 SimulStepper
._cont(me
, ev
)
1238 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
1240 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
1243 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
1246 def pg_done(me
, ev
):
1252 class SimulTester (PrimeGenEventHandler
):
1253 def __init__(me
, mul
= 2, add
= 1):
1256 def pg_begin(me
, ev
):
1258 me
.lr
= RabinMiller(x
)
1259 me
.hr
= RabinMiller(x
* me
.mul
+ me
.add
)
1261 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
1262 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
1264 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
1265 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
1267 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
1270 def pg_done(me
, ev
):
1274 def sgprime(start
, step
= 2, name
= 'p', event
= pgen_nullev
, nsteps
= 0):
1276 return pgen(start
, name
, SimulStepper(step
= step
), SimulTester(), event
,
1277 nsteps
, RabinMiller
.iters(start
.nbits
))
1279 def findprimitive(mod
, hh
= [], exp
= None, name
= 'g', event
= pgen_nullev
):
1280 return pgen(0, name
, PrimitiveStepper(), PrimitiveTester(mod
, hh
, exp
),
1283 def kcdsaprime(pbits
, qbits
, rng
= rand
,
1284 event
= pgen_nullev
, name
= 'p', nsteps
= 0):
1285 hbits
= pbits
- qbits
1286 h
= pgen(rng
.mp(hbits
, 1), name
+ ' [h]',
1287 PrimeGenStepper(2), PrimeGenTester(),
1288 event
, nsteps
, RabinMiller
.iters(hbits
))
1289 q
= pgen(rng
.mp(qbits
, 1), name
, SimulStepper(2 * h
, 1, 2),
1290 SimulTester(2 * h
, 1), event
, nsteps
, RabinMiller
.iters(qbits
))
1294 #----- That's all, folks ----------------------------------------------------