bd8aa57e2bbb37f6f5ae4957feae8a26046902e2
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 ## How to fix a name back into the right identifier. Alas, the rules are not
91 ## Hyphens consistently become underscores.
92 name
= name
.replace('-', '_')
94 ## But slashes might become underscores or just vanish.
95 if name
.startswith('salsa20'): name
= name
.replace('/', '')
96 else: name
= name
.replace('/', '_')
101 ## Initialize the module. Drag in the static methods of the various
102 ## classes; create names for the various known crypto algorithms.
109 for i
in [gcciphers
, gcaeads
, gchashes
, gcmacs
, gcprps
]:
110 for c
in _itervalues(i
):
111 d
[_fixname(c
.name
)] = c
112 for c
in _itervalues(gccrands
):
113 d
[_fixname(c
.name
+ 'rand')] = c
116 ## A handy function for our work: add the methods of a named class to an
117 ## existing class. This is how we write the Python-implemented parts of our
120 for i
in cc
.__dict__
:
122 if type(a
) is _types
.MethodType
:
124 elif type(a
) not in (_types
.FunctionType
, staticmethod, classmethod):
128 ## Parsing functions tend to return the object parsed and the remainder of
129 ## the input. This checks that the remainder is input and, if so, returns
134 raise SyntaxError('junk at end of string')
137 ## Some pretty-printing utilities.
138 PRINT_SECRETS
= False
139 def _clsname(me
): return type(me
).__name__
140 def _repr_secret(thing
, secretp
= True):
141 if not secretp
or PRINT_SECRETS
: return repr(thing
)
142 else: return '#<SECRET>'
143 def _pp_str(me
, pp
, cyclep
): pp
.text(cyclep
and '...' or str(me
))
144 def _pp_secret(pp
, thing
, secretp
= True):
145 if not secretp
or PRINT_SECRETS
: pp
.pretty(thing
)
146 else: pp
.text('#<SECRET>')
147 def _pp_bgroup(pp
, text
):
149 pp
.begin_group(ind
, text
)
151 def _pp_bgroup_tyname(pp
, obj
, open = '('):
152 return _pp_bgroup(pp
, _clsname(obj
) + open)
153 def _pp_kv(pp
, k
, v
, secretp
= False):
154 ind
= _pp_bgroup(pp
, k
+ ' = ')
155 _pp_secret(pp
, v
, secretp
)
156 pp
.end_group(ind
, '')
157 def _pp_commas(pp
, printfn
, items
):
160 if firstp
: firstp
= False
161 else: pp
.text(','); pp
.breakable()
163 def _pp_dict(pp
, items
):
174 _pp_commas(pp
, p
, items
)
176 ###--------------------------------------------------------------------------
181 return ByteString(_unhexify(x
))
182 fromhex
= staticmethod(fromhex
)
183 def hex(me
): return _hexify(me
)
186 return 'bytes(%r)' % me
.hex()
187 _augment(ByteString
, _tmp
)
188 ByteString
.__hash__
= str.__hash__
189 bytes
= ByteString
.fromhex
191 ###--------------------------------------------------------------------------
192 ### Symmetric encryption.
195 def encrypt(me
, n
, m
, tsz
= None, h
= ByteString
.zero(0)):
196 if tsz
is None: tsz
= me
.__class__
.tagsz
.default
197 e
= me
.enc(n
, len(h
), len(m
), tsz
)
198 if not len(h
): a
= None
199 else: a
= e
.aad().hash(h
)
201 c1
, t
= e
.done(aad
= a
)
203 def decrypt(me
, n
, c
, t
, h
= ByteString
.zero(0)):
204 d
= me
.dec(n
, len(h
), len(c
), len(t
))
205 if not len(h
): a
= None
206 else: a
= d
.aad().hash(h
)
208 m
+= d
.done(t
, aad
= a
)
210 _augment(GAEKey
, _tmp
)
212 ###--------------------------------------------------------------------------
218 return ctstreq(h
, hh
)
219 _augment(GHash
, _tmp
)
220 _augment(Poly1305Hash
, _tmp
)
222 class _HashBase (object):
223 ## The standard hash methods. Assume that `hash' is defined and returns
225 def _check_range(me
, n
, max):
226 if not (0 <= n
<= max): raise OverflowError("out of range")
228 me
._check_range(n
, 0xff)
229 return me
.hash(_pack('B', n
))
231 me
._check_range(n
, 0xffff)
232 return me
.hash(_pack('<H', n
))
234 me
._check_range(n
, 0xffff)
235 return me
.hash(_pack('>H', n
))
238 me
._check_range(n
, 0xffffffff)
239 return me
.hash(_pack('<L', n
))
241 me
._check_range(n
, 0xffffffff)
242 return me
.hash(_pack('>L', n
))
245 me
._check_range(n
, 0xffffffffffffffff)
246 return me
.hash(_pack('<Q', n
))
248 me
._check_range(n
, 0xffffffffffffffff)
249 return me
.hash(_pack('>Q', n
))
251 def hashbuf8(me
, s
): return me
.hashu8(len(s
)).hash(s
)
252 def hashbuf16l(me
, s
): return me
.hashu16l(len(s
)).hash(s
)
253 def hashbuf16b(me
, s
): return me
.hashu16b(len(s
)).hash(s
)
254 hashbuf16
= hashbuf16b
255 def hashbuf32l(me
, s
): return me
.hashu32l(len(s
)).hash(s
)
256 def hashbuf32b(me
, s
): return me
.hashu32b(len(s
)).hash(s
)
257 hashbuf32
= hashbuf32b
258 def hashbuf64l(me
, s
): return me
.hashu64l(len(s
)).hash(s
)
259 def hashbuf64b(me
, s
): return me
.hashu64b(len(s
)).hash(s
)
260 hashbuf64
= hashbuf64b
261 def hashstrz(me
, s
): return me
.hash(s
).hashu8(0)
263 class _ShakeBase (_HashBase
):
265 ## Python gets really confused if I try to augment `__new__' on native
266 ## classes, so wrap and delegate. Sorry.
267 def __init__(me
, perso
= _bin(''), *args
, **kw
):
268 super(_ShakeBase
, me
).__init__(*args
, **kw
)
269 me
._h
= me
._SHAKE(perso
= perso
, func
= me
._FUNC
)
271 ## Delegate methods...
272 def copy(me
): new
= me
.__class__
._bare_new(); new
._copy(me
); return new
273 def _copy(me
, other
): me
._h
= other
._h
.copy()
274 def hash(me
, m
): me
._h
.hash(m
); return me
275 def xof(me
): me
._h
.xof(); return me
276 def get(me
, n
): return me
._h
.get(n
)
277 def mask(me
, m
): return me
._h
.mask(m
)
278 def done(me
, n
): return me
._h
.done(n
)
279 def check(me
, h
): return ctstreq(h
, me
.done(len(h
)))
281 def state(me
): return me
._h
.state
283 def buffered(me
): return me
._h
.buffered
285 def rate(me
): return me
._h
.rate
287 def _bare_new(cls
): return cls()
291 return ctstreq(h
, me
.done(len(h
)))
294 return me
.hashu8(len(nn
)).hash(nn
)
297 return me
.hash(nn
).hashu8(len(nn
))
298 def stringenc(me
, str):
299 return me
.leftenc(8*len(str)).hash(str)
300 def bytepad_before(me
):
301 return me
.leftenc(me
.rate
)
302 def bytepad_after(me
):
303 if me
.buffered
: me
.hash(me
._Z
[:me
.rate
- me
.buffered
])
310 _augment(Shake
, _tmp
)
311 _augment(_ShakeBase
, _tmp
)
312 Shake
._Z
= _ShakeBase
._Z
= ByteString
.zero(200)
314 class KMAC (_ShakeBase
):
316 def __init__(me
, k
, *arg
, **kw
):
317 super(KMAC
, me
).__init__(*arg
, **kw
)
318 with me
.bytepad(): me
.stringenc(k
)
319 def done(me
, n
= -1):
320 if n
< 0: n
= me
._TAGSZ
322 return super(KMAC
, me
).done(n
)
325 return super(KMAC
, me
).xof()
327 def _bare_new(cls
): return cls(_bin(""))
329 class KMAC128 (KMAC
): _SHAKE
= Shake128
; _TAGSZ
= 16
330 class KMAC256 (KMAC
): _SHAKE
= Shake256
; _TAGSZ
= 32
332 ###--------------------------------------------------------------------------
333 ### NaCl `secretbox'.
335 def secret_box(k
, n
, m
):
336 y
, t
= salsa20_naclbox(k
).encrypt(n
, m
)
339 def secret_unbox(k
, n
, c
):
341 return salsa20_naclbox(k
).decrypt(n
, c
[tsz
:], c
[0:tsz
])
343 ###--------------------------------------------------------------------------
344 ### Multiprecision integers and binary polynomials.
347 if isinstance(x
, BaseRat
): return x
._n
, x
._d
349 class BaseRat (object):
350 """Base class implementing fields of fractions over Euclidean domains."""
351 def __new__(cls
, a
, b
):
352 a
, b
= cls
.RING(a
), cls
.RING(b
)
356 me
= super(BaseRat
, cls
).__new__(cls
)
361 def numer(me
): return me
._n
363 def denom(me
): return me
._d
364 def __str__(me
): return '%s/%s' %
(me
._n
, me
._d
)
365 def __repr__(me
): return '%s(%s, %s)' %
(_clsname(me
), me
._n
, me
._d
)
366 _repr_pretty_
= _pp_str
368 def __add__(me
, you
):
369 n
, d
= _split_rat(you
)
370 return type(me
)(me
._n
*d
+ n
*me
._d
, d
*me
._d
)
372 def __sub__(me
, you
):
373 n
, d
= _split_rat(you
)
374 return type(me
)(me
._n
*d
- n
*me
._d
, d
*me
._d
)
375 def __rsub__(me
, you
):
376 n
, d
= _split_rat(you
)
377 return type(me
)(n
*me
._d
- me
._n
*d
, d
*me
._d
)
378 def __mul__(me
, you
):
379 n
, d
= _split_rat(you
)
380 return type(me
)(me
._n
*n
, me
._d
*d
)
382 def __truediv__(me
, you
):
383 n
, d
= _split_rat(you
)
384 return type(me
)(me
._n
*d
, me
._d
*n
)
385 def __rtruediv__(me
, you
):
386 n
, d
= _split_rat(you
)
387 return type(me
)(me
._d
*n
, me
._n
*d
)
388 __div__
= __truediv__
389 __rdiv__
= __rtruediv__
390 def _order(me
, you
, op
):
391 n
, d
= _split_rat(you
)
392 return op(me
._n
*d
, n
*me
._d
)
393 def __eq__(me
, you
): return me
._order(you
, lambda x
, y
: x
== y
)
394 def __ne__(me
, you
): return me
._order(you
, lambda x
, y
: x
!= y
)
395 def __le__(me
, you
): return me
._order(you
, lambda x
, y
: x
<= y
)
396 def __lt__(me
, you
): return me
._order(you
, lambda x
, y
: x
< y
)
397 def __gt__(me
, you
): return me
._order(you
, lambda x
, y
: x
> y
)
398 def __ge__(me
, you
): return me
._order(you
, lambda x
, y
: x
>= y
)
400 class IntRat (BaseRat
):
403 class GFRat (BaseRat
):
407 def negp(x
): return x
< 0
408 def posp(x
): return x
> 0
409 def zerop(x
): return x
== 0
410 def oddp(x
): return x
.testbit(0)
411 def evenp(x
): return not x
.testbit(0)
412 def mont(x
): return MPMont(x
)
413 def barrett(x
): return MPBarrett(x
)
414 def reduce(x
): return MPReduce(x
)
415 def __truediv__(me
, you
): return IntRat(me
, you
)
416 def __rtruediv__(me
, you
): return IntRat(you
, me
)
417 __div__
= __truediv__
418 __rdiv__
= __rtruediv__
419 _repr_pretty_
= _pp_str
423 def zerop(x
): return x
== 0
424 def reduce(x
): return GFReduce(x
)
425 def trace(x
, y
): return x
.reduce().trace(y
)
426 def halftrace(x
, y
): return x
.reduce().halftrace(y
)
427 def modsqrt(x
, y
): return x
.reduce().sqrt(y
)
428 def quadsolve(x
, y
): return x
.reduce().quadsolve(y
)
429 def __truediv__(me
, you
): return GFRat(me
, you
)
430 def __rtruediv__(me
, you
): return GFRat(you
, me
)
431 __div__
= __truediv__
432 __rdiv__
= __rtruediv__
433 _repr_pretty_
= _pp_str
438 'product(ITERABLE) or product(I, ...) -> PRODUCT'
439 return MPMul(*arg
).done()
440 product
= staticmethod(product
)
441 _augment(MPMul
, _tmp
)
443 ###--------------------------------------------------------------------------
447 def fromstring(str): return _checkend(Field
.parse(str))
448 fromstring
= staticmethod(fromstring
)
449 _augment(Field
, _tmp
)
452 def __repr__(me
): return '%s(%sL)' %
(_clsname(me
), me
.p
)
453 def __hash__(me
): return 0x114401de ^
hash(me
.p
)
454 def _repr_pretty_(me
, pp
, cyclep
):
455 ind
= _pp_bgroup_tyname(pp
, me
)
456 if cyclep
: pp
.text('...')
457 else: pp
.pretty(me
.p
)
458 pp
.end_group(ind
, ')')
459 def ec(me
, a
, b
): return ECPrimeProjCurve(me
, a
, b
)
460 _augment(PrimeField
, _tmp
)
463 def __repr__(me
): return '%s(%#xL)' %
(_clsname(me
), me
.p
)
464 def ec(me
, a
, b
): return ECBinProjCurve(me
, a
, b
)
465 def _repr_pretty_(me
, pp
, cyclep
):
466 ind
= _pp_bgroup_tyname(pp
, me
)
467 if cyclep
: pp
.text('...')
468 else: pp
.text('%#x' % me
.p
)
469 pp
.end_group(ind
, ')')
470 _augment(BinField
, _tmp
)
473 def __hash__(me
): return 0x23e4701c ^
hash(me
.p
)
474 _augment(BinPolyField
, _tmp
)
480 h ^
= 2*hash(me
.beta
) & 0xffffffff
482 _augment(BinNormField
, _tmp
)
485 def __str__(me
): return str(me
.value
)
486 def __repr__(me
): return '%s(%s)' %
(repr(me
.field
), repr(me
.value
))
487 _repr_pretty_
= _pp_str
490 ###--------------------------------------------------------------------------
495 return '%s(%r, %s, %s)' %
(_clsname(me
), me
.field
, me
.a
, me
.b
)
496 def _repr_pretty_(me
, pp
, cyclep
):
497 ind
= _pp_bgroup_tyname(pp
, me
)
501 pp
.pretty(me
.field
); pp
.text(','); pp
.breakable()
502 pp
.pretty(me
.a
); pp
.text(','); pp
.breakable()
504 pp
.end_group(ind
, ')')
506 return ecpt
.frombuf(me
, s
)
508 return ecpt
.fromraw(me
, s
)
511 _augment(ECCurve
, _tmp
)
517 h ^
= 2*hash(me
.a
) ^
0xffffffff
518 h ^
= 5*hash(me
.b
) ^
0xffffffff
520 _augment(ECPrimeCurve
, _tmp
)
526 h ^
= 2*hash(me
.a
) ^
0xffffffff
527 h ^
= 5*hash(me
.b
) ^
0xffffffff
529 _augment(ECBinCurve
, _tmp
)
533 if not me
: return '%s()' %
_clsname(me
)
534 return '%s(%s, %s)' %
(_clsname(me
), me
.ix
, me
.iy
)
536 if not me
: return 'inf'
537 return '(%s, %s)' %
(me
.ix
, me
.iy
)
538 def _repr_pretty_(me
, pp
, cyclep
):
544 ind
= _pp_bgroup(pp
, '(')
545 pp
.pretty(me
.ix
); pp
.text(','); pp
.breakable()
547 pp
.end_group(ind
, ')')
552 return '%s(curve = %r, G = %r, r = %s, h = %s)' % \
553 (_clsname(me
), me
.curve
, me
.G
, me
.r
, me
.h
)
554 def _repr_pretty_(me
, pp
, cyclep
):
555 ind
= _pp_bgroup_tyname(pp
, me
)
559 _pp_kv(pp
, 'curve', me
.curve
); pp
.text(','); pp
.breakable()
560 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
561 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
562 _pp_kv(pp
, 'h', me
.h
)
563 pp
.end_group(ind
, ')')
567 h ^
= 2*hash(me
.G
) & 0xffffffff
571 _augment(ECInfo
, _tmp
)
575 if not me
: return '%r()' %
(me
.curve
)
576 return '%r(%s, %s)' %
(me
.curve
, me
.x
, me
.y
)
578 if not me
: return 'inf'
579 return '(%s, %s)' %
(me
.x
, me
.y
)
580 def _repr_pretty_(me
, pp
, cyclep
):
586 ind
= _pp_bgroup(pp
, '(')
587 pp
.pretty(me
.x
); pp
.text(','); pp
.breakable()
589 pp
.end_group(ind
, ')')
590 _augment(ECPtCurve
, _tmp
)
592 ###--------------------------------------------------------------------------
596 def __repr__(me
): return '%s(%d)' %
(_clsname(me
), me
.default
)
597 def check(me
, sz
): return True
598 def best(me
, sz
): return sz
599 def pad(me
, sz
): return sz
600 _augment(KeySZAny
, _tmp
)
604 return '%s(%d, %d, %d, %d)' % \
605 (_clsname(me
), me
.default
, me
.min, me
.max, me
.mod
)
606 def _repr_pretty_(me
, pp
, cyclep
):
607 ind
= _pp_bgroup_tyname(pp
, me
)
611 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
612 pp
.pretty(me
.min); pp
.text(','); pp
.breakable()
613 pp
.pretty(me
.max); pp
.text(','); pp
.breakable()
615 pp
.end_group(ind
, ')')
616 def check(me
, sz
): return me
.min <= sz
<= me
.max and sz
%me
.mod
== 0
618 if sz
< me
.min: raise ValueError('key too small')
619 elif sz
> me
.max: return me
.max
620 else: return sz
- sz
%me
.mod
622 if sz
> me
.max: raise ValueError('key too large')
623 elif sz
< me
.min: return me
.min
624 else: sz
+= me
.mod
- 1; return sz
- sz
%me
.mod
625 _augment(KeySZRange
, _tmp
)
628 def __repr__(me
): return '%s(%d, %s)' %
(_clsname(me
), me
.default
, me
.set)
629 def _repr_pretty_(me
, pp
, cyclep
):
630 ind
= _pp_bgroup_tyname(pp
, me
)
634 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
635 ind1
= _pp_bgroup(pp
, '{')
636 _pp_commas(pp
, pp
.pretty
, me
.set)
637 pp
.end_group(ind1
, '}')
638 pp
.end_group(ind
, ')')
639 def check(me
, sz
): return sz
in me
.set
643 if found
< i
<= sz
: found
= i
644 if found
< 0: raise ValueError('key too small')
649 if sz
<= i
and (found
== -1 or i
< found
): found
= i
650 if found
< 0: raise ValueError('key too large')
652 _augment(KeySZSet
, _tmp
)
654 ###--------------------------------------------------------------------------
655 ### Key data objects.
658 def merge(me
, file, report
= None):
659 """KF.merge(FILE, [report = <built-in-reporter>])"""
663 me
.mergeline(name
, lno
, line
, report
)
666 def __repr__(me
): return '%s(%r)' %
(_clsname(me
), me
.name
)
667 _augment(KeyFile
, _tmp
)
670 def extract(me
, file, filter = ''):
671 """KEY.extract(FILE, [filter = <any>])"""
672 line
= me
.extractline(filter)
675 def __repr__(me
): return '%s(%r)' %
(_clsname(me
), me
.fulltag
)
680 return '%s({%s})' %
(_clsname(me
),
681 ', '.join(['%r: %r' % kv
for kv
in _iteritems(me
)()]))
682 def _repr_pretty_(me
, pp
, cyclep
):
683 ind
= _pp_bgroup_tyname(pp
, me
)
684 if cyclep
: pp
.text('...')
685 else: _pp_dict(pp
, _iteritems(me
))
686 pp
.end_group(ind
, ')')
687 _augment(KeyAttributes
, _tmp
)
691 return '%s(%s, %r)' %
(_clsname(me
),
692 _repr_secret(me
._guts(),
693 not (me
.flags
& KF_NONSECRET
)),
694 me
.writeflags(me
.flags
))
695 def _repr_pretty_(me
, pp
, cyclep
):
696 ind
= _pp_bgroup_tyname(pp
, me
)
700 _pp_secret(pp
, me
._guts(), not (me
.flags
& KF_NONSECRET
))
701 pp
.text(','); pp
.breakable()
702 pp
.pretty(me
.writeflags(me
.flags
))
703 pp
.end_group(ind
, ')')
704 _augment(KeyData
, _tmp
)
707 def _guts(me
): return me
.bin
708 _augment(KeyDataBinary
, _tmp
)
711 def _guts(me
): return me
.ct
712 _augment(KeyDataEncrypted
, _tmp
)
715 def _guts(me
): return me
.mp
716 _augment(KeyDataMP
, _tmp
)
719 def _guts(me
): return me
.str
720 _augment(KeyDataString
, _tmp
)
723 def _guts(me
): return me
.ecpt
724 _augment(KeyDataECPt
, _tmp
)
728 return '%s({%s})' %
(_clsname(me
),
729 ', '.join(['%r: %r' % kv
for kv
in _iteritems(me
)]))
730 def _repr_pretty_(me
, pp
, cyclep
):
731 ind
= _pp_bgroup_tyname(pp
, me
, '({ ')
732 if cyclep
: pp
.text('...')
733 else: _pp_dict(pp
, _iteritems(me
))
734 pp
.end_group(ind
, ' })')
735 _augment(KeyDataStructured
, _tmp
)
737 ###--------------------------------------------------------------------------
742 return '%s(p = %s, r = %s, g = %s)' %
(_clsname(me
), me
.p
, me
.r
, me
.g
)
743 def _repr_pretty_(me
, pp
, cyclep
):
744 ind
= _pp_bgroup_tyname(pp
, me
)
748 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
749 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
750 _pp_kv(pp
, 'g', me
.g
)
751 pp
.end_group(ind
, ')')
752 _augment(FGInfo
, _tmp
)
755 def group(me
): return PrimeGroup(me
)
756 _augment(DHInfo
, _tmp
)
759 def group(me
): return BinGroup(me
)
760 _augment(BinDHInfo
, _tmp
)
764 return '%s(%r)' %
(_clsname(me
), me
.info
)
765 def _repr_pretty_(me
, pp
, cyclep
):
766 ind
= _pp_bgroup_tyname(pp
, me
)
767 if cyclep
: pp
.text('...')
768 else: pp
.pretty(me
.info
)
769 pp
.end_group(ind
, ')')
770 _augment(Group
, _tmp
)
777 h ^
= 2*hash(info
.r
) & 0xffffffff
778 h ^
= 5*hash(info
.g
) & 0xffffffff
780 def _get_geval(me
, x
): return MP(x
)
781 _augment(PrimeGroup
, _tmp
)
788 h ^
= 2*hash(info
.r
) & 0xffffffff
789 h ^
= 5*hash(info
.g
) & 0xffffffff
791 def _get_geval(me
, x
): return GF(x
)
792 _augment(BinGroup
, _tmp
)
795 def __hash__(me
): return 0x0ec23dab ^
hash(me
.info
)
796 def _get_geval(me
, x
): return x
.toec()
797 _augment(ECGroup
, _tmp
)
801 return '%r(%r)' %
(me
.group
, str(me
))
802 def _repr_pretty_(me
, pp
, cyclep
):
803 pp
.pretty(type(me
)._get_geval(me
))
806 ###--------------------------------------------------------------------------
807 ### RSA encoding techniques.
809 class PKCS1Crypt (object):
810 def __init__(me
, ep
= _bin(''), rng
= rand
):
813 def encode(me
, msg
, nbits
):
814 return _base
._p1crypt_encode(msg
, nbits
, me
.ep
, me
.rng
)
815 def decode(me
, ct
, nbits
):
816 return _base
._p1crypt_decode(ct
, nbits
, me
.ep
, me
.rng
)
818 class PKCS1Sig (object):
819 def __init__(me
, ep
= _bin(''), rng
= rand
):
822 def encode(me
, msg
, nbits
):
823 return _base
._p1sig_encode(msg
, nbits
, me
.ep
, me
.rng
)
824 def decode(me
, msg
, sig
, nbits
):
825 return _base
._p1sig_decode(msg
, sig
, nbits
, me
.ep
, me
.rng
)
828 def __init__(me
, mgf
= sha_mgf
, hash = sha
, ep
= _bin(''), rng
= rand
):
833 def encode(me
, msg
, nbits
):
834 return _base
._oaep_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
835 def decode(me
, ct
, nbits
):
836 return _base
._oaep_decode(ct
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
839 def __init__(me
, mgf
= sha_mgf
, hash = sha
, saltsz
= None, rng
= rand
):
846 def encode(me
, msg
, nbits
):
847 return _base
._pss_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
848 def decode(me
, msg
, sig
, nbits
):
849 return _base
._pss_decode(msg
, sig
, nbits
,
850 me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
853 def encrypt(me
, msg
, enc
):
854 return me
.pubop(enc
.encode(msg
, me
.n
.nbits
))
855 def verify(me
, msg
, sig
, enc
):
856 if msg
is None: return enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
858 x
= enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
859 return x
is None or x
== msg
863 return '%s(n = %r, e = %r)' %
(_clsname(me
), me
.n
, me
.e
)
864 def _repr_pretty_(me
, pp
, cyclep
):
865 ind
= _pp_bgroup_tyname(pp
, me
)
869 _pp_kv(pp
, 'n', me
.n
); pp
.text(','); pp
.breakable()
870 _pp_kv(pp
, 'e', me
.e
)
871 pp
.end_group(ind
, ')')
872 _augment(RSAPub
, _tmp
)
875 def decrypt(me
, ct
, enc
): return enc
.decode(me
.privop(ct
), me
.n
.nbits
)
876 def sign(me
, msg
, enc
): return me
.privop(enc
.encode(msg
, me
.n
.nbits
))
878 return '%s(n = %r, e = %r, d = %s, ' \
879 'p = %s, q = %s, dp = %s, dq = %s, q_inv = %s)' % \
880 (_clsname(me
), me
.n
, me
.e
,
881 _repr_secret(me
.d
), _repr_secret(me
.p
), _repr_secret(me
.q
),
882 _repr_secret(me
.dp
), _repr_secret(me
.dq
), _repr_secret(me
.q_inv
))
883 def _repr_pretty_(me
, pp
, cyclep
):
884 ind
= _pp_bgroup_tyname(pp
, me
)
888 _pp_kv(pp
, 'n', me
.n
); pp
.text(','); pp
.breakable()
889 _pp_kv(pp
, 'e', me
.e
); pp
.text(','); pp
.breakable()
890 _pp_kv(pp
, 'd', me
.d
, secretp
= True); pp
.text(','); pp
.breakable()
891 _pp_kv(pp
, 'p', me
.p
, secretp
= True); pp
.text(','); pp
.breakable()
892 _pp_kv(pp
, 'q', me
.q
, secretp
= True); pp
.text(','); pp
.breakable()
893 _pp_kv(pp
, 'dp', me
.dp
, secretp
= True); pp
.text(','); pp
.breakable()
894 _pp_kv(pp
, 'dq', me
.dq
, secretp
= True); pp
.text(','); pp
.breakable()
895 _pp_kv(pp
, 'q_inv', me
.q_inv
, secretp
= True)
896 pp
.end_group(ind
, ')')
897 _augment(RSAPriv
, _tmp
)
899 ###--------------------------------------------------------------------------
900 ### DSA and related schemes.
903 def __repr__(me
): return '%s(G = %r, p = %r, hash = %r)' % \
904 (_clsname(me
), me
.G
, me
.p
, me
.hash)
905 def _repr_pretty_(me
, pp
, cyclep
):
906 ind
= _pp_bgroup_tyname(pp
, me
)
910 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
911 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
912 _pp_kv(pp
, 'hash', me
.hash)
913 pp
.end_group(ind
, ')')
914 _augment(DSAPub
, _tmp
)
915 _augment(KCDSAPub
, _tmp
)
918 def __repr__(me
): return '%s(G = %r, u = %s, p = %r, hash = %r)' % \
919 (_clsname(me
), me
.G
, _repr_secret(me
.u
), me
.p
, me
.hash)
920 def _repr_pretty_(me
, pp
, cyclep
):
921 ind
= _pp_bgroup_tyname(pp
, me
)
925 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
926 _pp_kv(pp
, 'u', me
.u
, True); pp
.text(','); pp
.breakable()
927 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
928 _pp_kv(pp
, 'hash', me
.hash)
929 pp
.end_group(ind
, ')')
930 _augment(DSAPriv
, _tmp
)
931 _augment(KCDSAPriv
, _tmp
)
933 ###--------------------------------------------------------------------------
934 ### Bernstein's elliptic curve crypto and related schemes.
936 X25519_BASE
= MP(9).storel(32)
937 X448_BASE
= MP(5).storel(56)
939 Z128
= ByteString
.zero(16)
941 class _BasePub (object):
942 def __init__(me
, pub
, *args
, **kw
):
943 if not me
._PUBSZ
.check(len(pub
)): raise ValueError('bad public key')
944 super(_BasePub
, me
).__init__(*args
, **kw
)
946 def __repr__(me
): return '%s(pub = %r)' %
(_clsname(me
), me
.pub
)
947 def _pp(me
, pp
): _pp_kv(pp
, 'pub', me
.pub
)
948 def _repr_pretty_(me
, pp
, cyclep
):
949 ind
= _pp_bgroup_tyname(pp
, me
)
950 if cyclep
: pp
.text('...')
952 pp
.end_group(ind
, ')')
954 class _BasePriv (object):
955 def __init__(me
, priv
, pub
= None, *args
, **kw
):
956 if not me
._KEYSZ
.check(len(priv
)): raise ValueError('bad private key')
957 if pub
is None: pub
= me
._pubkey(priv
)
958 super(_BasePriv
, me
).__init__(pub
= pub
, *args
, **kw
)
961 def generate(cls
, rng
= rand
):
962 return cls(rng
.block(cls
._KEYSZ
.default
))
964 return '%s(priv = %d, pub = %r)' % \
965 (_clsname(me
), _repr_secret(me
.priv
), me
.pub
)
967 _pp_kv(pp
, 'priv', me
.priv
, secretp
= True); pp
.text(','); pp
.breakable()
968 super(_BasePriv
, me
)._pp(pp
)
970 class _XDHPub (_BasePub
): pass
972 class _XDHPriv (_BasePriv
):
973 def _pubkey(me
, priv
): return me
._op(priv
, me
._BASE
)
974 def agree(me
, you
): return me
._op(me
.priv
, you
.pub
)
975 def boxkey(me
, recip
): return me
._hashkey(me
.agree(recip
))
976 def box(me
, recip
, n
, m
): return secret_box(me
.boxkey(recip
), n
, m
)
977 def unbox(me
, recip
, n
, c
): return secret_unbox(me
.boxkey(recip
), n
, c
)
979 class X25519Pub (_XDHPub
):
980 _PUBSZ
= KeySZSet(X25519_PUBSZ
)
983 class X25519Priv (_XDHPriv
, X25519Pub
):
984 _KEYSZ
= KeySZSet(X25519_KEYSZ
)
985 def _op(me
, k
, X
): return x25519(k
, X
)
986 def _hashkey(me
, z
): return hsalsa20_prf(z
, Z128
)
988 class X448Pub (_XDHPub
):
989 _PUBSZ
= KeySZSet(X448_PUBSZ
)
992 class X448Priv (_XDHPriv
, X448Pub
):
993 _KEYSZ
= KeySZSet(X448_KEYSZ
)
994 def _op(me
, k
, X
): return x448(k
, X
)
995 def _hashkey(me
, z
): return Shake256().hash(z
).done(salsa20
.keysz
.default
)
997 class _EdDSAPub (_BasePub
):
998 def beginhash(me
): return me
._HASH()
999 def endhash(me
, h
): return h
.done()
1001 class _EdDSAPriv (_BasePriv
, _EdDSAPub
):
1004 class Ed25519Pub (_EdDSAPub
):
1005 _PUBSZ
= KeySZSet(ED25519_PUBSZ
)
1007 def verify(me
, msg
, sig
, **kw
):
1008 return ed25519_verify(me
.pub
, msg
, sig
, **kw
)
1010 class Ed25519Priv (_EdDSAPriv
, Ed25519Pub
):
1011 _KEYSZ
= KeySZAny(ED25519_KEYSZ
)
1012 def _pubkey(me
, priv
): return ed25519_pubkey(priv
)
1013 def sign(me
, msg
, **kw
):
1014 return ed25519_sign(me
.priv
, msg
, pub
= me
.pub
, **kw
)
1016 class Ed448Pub (_EdDSAPub
):
1017 _PUBSZ
= KeySZSet(ED448_PUBSZ
)
1019 def verify(me
, msg
, sig
, **kw
):
1020 return ed448_verify(me
.pub
, msg
, sig
, **kw
)
1022 class Ed448Priv (_EdDSAPriv
, Ed448Pub
):
1023 _KEYSZ
= KeySZAny(ED448_KEYSZ
)
1024 def _pubkey(me
, priv
): return ed448_pubkey(priv
)
1025 def sign(me
, msg
, **kw
):
1026 return ed448_sign(me
.priv
, msg
, pub
= me
.pub
, **kw
)
1028 ###--------------------------------------------------------------------------
1029 ### Built-in algorithm and group tables.
1033 return '{%s}' %
', '.join(['%r: %r' % kv
for kv
in _iteritems(me
)])
1034 def _repr_pretty_(me
, pp
, cyclep
):
1035 ind
= _pp_bgroup(pp
, '{ ')
1036 if cyclep
: pp
.text('...')
1037 else: _pp_dict(pp
, _iteritems(me
))
1038 pp
.end_group(ind
, ' }')
1039 _augment(_base
._MiscTable
, _tmp
)
1041 ###--------------------------------------------------------------------------
1042 ### Prime number generation.
1044 class PrimeGenEventHandler (object):
1045 def pg_begin(me
, ev
):
1046 return me
.pg_try(ev
)
1047 def pg_done(me
, ev
):
1049 def pg_abort(me
, ev
):
1051 def pg_fail(me
, ev
):
1053 def pg_pass(me
, ev
):
1056 class SophieGermainStepJump (object):
1057 def pg_begin(me
, ev
):
1058 me
.lf
= PrimeFilter(ev
.x
)
1059 me
.hf
= me
.lf
.muladd(2, 1)
1065 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
1067 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
1070 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
1073 def pg_done(me
, ev
):
1077 class SophieGermainStepper (SophieGermainStepJump
):
1078 def __init__(me
, step
):
1082 me
.lf
.step(me
.lstep
)
1083 me
.hf
.step(me
.hstep
)
1085 class SophieGermainJumper (SophieGermainStepJump
):
1086 def __init__(me
, jump
):
1087 me
.ljump
= PrimeFilter(jump
);
1088 me
.hjump
= me
.ljump
.muladd(2, 0)
1090 me
.lf
.jump(me
.ljump
)
1091 me
.hf
.jump(me
.hjump
)
1092 def pg_done(me
, ev
):
1095 SophieGermainStepJump
.pg_done(me
, ev
)
1097 class SophieGermainTester (object):
1100 def pg_begin(me
, ev
):
1101 me
.lr
= RabinMiller(ev
.x
)
1102 me
.hr
= RabinMiller(2 * ev
.x
+ 1)
1104 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
1105 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
1107 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
1108 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
1110 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
1113 def pg_done(me
, ev
):
1117 class PrimitiveStepper (PrimeGenEventHandler
):
1123 def pg_begin(me
, ev
):
1124 me
.i
= iter(smallprimes
)
1125 return me
.pg_try(ev
)
1127 class PrimitiveTester (PrimeGenEventHandler
):
1128 def __init__(me
, mod
, hh
= [], exp
= None):
1129 me
.mod
= MPMont(mod
)
1134 if me
.exp
is not None:
1135 x
= me
.mod
.exp(x
, me
.exp
)
1136 if x
== 1: return PGEN_FAIL
1138 if me
.mod
.exp(x
, h
) == 1: return PGEN_FAIL
1142 class SimulStepper (PrimeGenEventHandler
):
1143 def __init__(me
, mul
= 2, add
= 1, step
= 2):
1147 def _stepfn(me
, step
):
1149 raise ValueError('step must be positive')
1151 return lambda f
: f
.step(step
)
1152 j
= PrimeFilter(step
)
1153 return lambda f
: f
.jump(j
)
1154 def pg_begin(me
, ev
):
1156 me
.lf
= PrimeFilter(x
)
1157 me
.hf
= PrimeFilter(x
* me
.mul
+ me
.add
)
1158 me
.lstep
= me
._stepfn(me
.step
)
1159 me
.hstep
= me
._stepfn(me
.step
* me
.mul
)
1160 SimulStepper
._cont(me
, ev
)
1168 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
1170 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
1173 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
1176 def pg_done(me
, ev
):
1182 class SimulTester (PrimeGenEventHandler
):
1183 def __init__(me
, mul
= 2, add
= 1):
1186 def pg_begin(me
, ev
):
1188 me
.lr
= RabinMiller(x
)
1189 me
.hr
= RabinMiller(x
* me
.mul
+ me
.add
)
1191 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
1192 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
1194 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
1195 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
1197 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
1200 def pg_done(me
, ev
):
1204 def sgprime(start
, step
= 2, name
= 'p', event
= pgen_nullev
, nsteps
= 0):
1206 return pgen(start
, name
, SimulStepper(step
= step
), SimulTester(), event
,
1207 nsteps
, RabinMiller
.iters(start
.nbits
))
1209 def findprimitive(mod
, hh
= [], exp
= None, name
= 'g', event
= pgen_nullev
):
1210 return pgen(0, name
, PrimitiveStepper(), PrimitiveTester(mod
, hh
, exp
),
1213 def kcdsaprime(pbits
, qbits
, rng
= rand
,
1214 event
= pgen_nullev
, name
= 'p', nsteps
= 0):
1215 hbits
= pbits
- qbits
1216 h
= pgen(rng
.mp(hbits
, 1), name
+ ' [h]',
1217 PrimeGenStepper(2), PrimeGenTester(),
1218 event
, nsteps
, RabinMiller
.iters(hbits
))
1219 q
= pgen(rng
.mp(qbits
, 1), name
, SimulStepper(2 * h
, 1, 2),
1220 SimulTester(2 * h
, 1), event
, nsteps
, RabinMiller
.iters(qbits
))
1224 #----- That's all, folks ----------------------------------------------------