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
)
255 return ctstreq(h
, me
.done(len(h
)))
256 _augment(Shake
, _tmp
)
258 KMAC128
.keysz
= KeySZAny(16); KMAC128
.tagsz
= 16
259 KMAC256
.keysz
= KeySZAny(32); KMAC256
.tagsz
= 32
261 ###--------------------------------------------------------------------------
262 ### NaCl `secretbox'.
264 def secret_box(k
, n
, m
):
265 y
, t
= salsa20_naclbox(k
).encrypt(n
, m
)
268 def secret_unbox(k
, n
, c
):
270 return salsa20_naclbox(k
).decrypt(n
, c
[tsz
:], c
[0:tsz
])
272 ###--------------------------------------------------------------------------
273 ### Multiprecision integers and binary polynomials.
275 class BaseRat (object):
276 """Base class implementing fields of fractions over Euclidean domains."""
277 def __new__(cls
, a
, b
):
278 a
, b
= cls
.RING
._implicit(a
), cls
.RING
._implicit(b
)
280 if r
== cls
.ZERO
: return q
282 me
= super(BaseRat
, cls
).__new__(cls
)
287 def numer(me
): return me
._n
289 def denom(me
): return me
._d
290 def __str__(me
): return '%s/%s' %
(me
._n
, me
._d
)
291 def __repr__(me
): return '%s(%s, %s)' %
(_clsname(me
), me
._n
, me
._d
)
292 _repr_pretty_
= _pp_str
294 def _split_rat(me
, x
):
295 if isinstance(x
, me
.__class__
): return x
._n
, x
._d
296 else: return x
, me
.ONE
297 def __add__(me
, you
):
298 n
, d
= me
._split_rat(you
)
299 return type(me
)(me
._n
*d
+ n
*me
._d
, d
*me
._d
)
301 def __sub__(me
, you
):
302 n
, d
= me
._split_rat(you
)
303 return type(me
)(me
._n
*d
- n
*me
._d
, d
*me
._d
)
304 def __rsub__(me
, you
):
305 n
, d
= me
._split_rat(you
)
306 return type(me
)(n
*me
._d
- me
._n
*d
, d
*me
._d
)
307 def __mul__(me
, you
):
308 n
, d
= me
._split_rat(you
)
309 return type(me
)(me
._n
*n
, me
._d
*d
)
311 def __truediv__(me
, you
):
312 n
, d
= me
._split_rat(you
)
313 return type(me
)(me
._n
*d
, me
._d
*n
)
314 def __rtruediv__(me
, you
):
315 n
, d
= me
._split_rat(you
)
316 return type(me
)(me
._d
*n
, me
._n
*d
)
317 if _sys
.version_info
< (3,):
318 __div__
= __truediv__
319 __rdiv__
= __rtruediv__
320 def _order(me
, you
, op
):
321 n
, d
= me
._split_rat(you
)
322 return op(me
._n
*d
, n
*me
._d
)
323 def __eq__(me
, you
): return me
._order(you
, lambda x
, y
: x
== y
)
324 def __ne__(me
, you
): return me
._order(you
, lambda x
, y
: x
!= y
)
325 def __le__(me
, you
): return me
._order(you
, lambda x
, y
: x
<= y
)
326 def __lt__(me
, you
): return me
._order(you
, lambda x
, y
: x
< y
)
327 def __gt__(me
, you
): return me
._order(you
, lambda x
, y
: x
> y
)
328 def __ge__(me
, you
): return me
._order(you
, lambda x
, y
: x
>= y
)
330 class IntRat (BaseRat
):
332 ZERO
, ONE
= MP(0), MP(1)
333 def __new__(cls
, a
, b
):
334 if isinstance(a
, float) or isinstance(b
, float): return a
/b
335 return super(IntRat
, cls
).__new__(cls
, a
, b
)
336 def __float__(me
): return float(me
._n
)/float(me
._d
)
338 class GFRat (BaseRat
):
340 ZERO
, ONE
= GF(0), GF(1)
343 def negp(x
): return x
< 0
344 def posp(x
): return x
> 0
345 def zerop(x
): return x
== 0
346 def oddp(x
): return x
.testbit(0)
347 def evenp(x
): return not x
.testbit(0)
348 def mont(x
): return MPMont(x
)
349 def barrett(x
): return MPBarrett(x
)
350 def reduce(x
): return MPReduce(x
)
351 def __truediv__(me
, you
):
352 if isinstance(you
, float): return _long(me
)/you
353 else: return IntRat(me
, you
)
354 def __rtruediv__(me
, you
):
355 if isinstance(you
, float): return you
/_long(me
)
356 else: return IntRat(you
, me
)
357 if _sys
.version_info
< (3,):
358 __div__
= __truediv__
359 __rdiv__
= __rtruediv__
360 _repr_pretty_
= _pp_str
364 def zerop(x
): return x
== 0
365 def reduce(x
): return GFReduce(x
)
366 def trace(x
, y
): return x
.reduce().trace(y
)
367 def halftrace(x
, y
): return x
.reduce().halftrace(y
)
368 def modsqrt(x
, y
): return x
.reduce().sqrt(y
)
369 def quadsolve(x
, y
): return x
.reduce().quadsolve(y
)
370 def __truediv__(me
, you
): return GFRat(me
, you
)
371 def __rtruediv__(me
, you
): return GFRat(you
, me
)
372 if _sys
.version_info
< (3,):
373 __div__
= __truediv__
374 __rdiv__
= __rtruediv__
375 _repr_pretty_
= _pp_str
380 'product(ITERABLE) or product(I, ...) -> PRODUCT'
381 return MPMul(*arg
).done()
382 product
= staticmethod(product
)
383 _augment(MPMul
, _tmp
)
385 ###--------------------------------------------------------------------------
389 def fromstring(str): return _checkend(Field
.parse(str))
390 fromstring
= staticmethod(fromstring
)
391 _augment(Field
, _tmp
)
394 def __repr__(me
): return '%s(%s)' %
(_clsname(me
), me
.p
)
395 def __hash__(me
): return 0x114401de ^
hash(me
.p
)
396 def _repr_pretty_(me
, pp
, cyclep
):
397 ind
= _pp_bgroup_tyname(pp
, me
)
398 if cyclep
: pp
.text('...')
399 else: pp
.pretty(me
.p
)
400 pp
.end_group(ind
, ')')
401 def ec(me
, a
, b
): return ECPrimeProjCurve(me
, a
, b
)
402 _augment(PrimeField
, _tmp
)
405 def __repr__(me
): return '%s(%#x)' %
(_clsname(me
), me
.p
)
406 def ec(me
, a
, b
): return ECBinProjCurve(me
, a
, b
)
407 def _repr_pretty_(me
, pp
, cyclep
):
408 ind
= _pp_bgroup_tyname(pp
, me
)
409 if cyclep
: pp
.text('...')
410 else: pp
.text('%#x' % me
.p
)
411 pp
.end_group(ind
, ')')
412 _augment(BinField
, _tmp
)
415 def __hash__(me
): return 0x23e4701c ^
hash(me
.p
)
416 _augment(BinPolyField
, _tmp
)
422 h ^
= 2*hash(me
.beta
) & 0xffffffff
424 _augment(BinNormField
, _tmp
)
427 def __str__(me
): return str(me
.value
)
428 def __repr__(me
): return '%s(%s)' %
(repr(me
.field
), repr(me
.value
))
429 _repr_pretty_
= _pp_str
432 ###--------------------------------------------------------------------------
437 return '%s(%r, %s, %s)' %
(_clsname(me
), me
.field
, me
.a
, me
.b
)
438 def _repr_pretty_(me
, pp
, cyclep
):
439 ind
= _pp_bgroup_tyname(pp
, me
)
443 pp
.pretty(me
.field
); pp
.text(','); pp
.breakable()
444 pp
.pretty(me
.a
); pp
.text(','); pp
.breakable()
446 pp
.end_group(ind
, ')')
447 def fromstring(str): return _checkend(ECCurve
.parse(str))
448 fromstring
= staticmethod(fromstring
)
450 return ecpt
.frombuf(me
, s
)
452 return ecpt
.fromraw(me
, s
)
455 _augment(ECCurve
, _tmp
)
461 h ^
= 2*hash(me
.a
) ^
0xffffffff
462 h ^
= 5*hash(me
.b
) ^
0xffffffff
464 _augment(ECPrimeCurve
, _tmp
)
470 h ^
= 2*hash(me
.a
) ^
0xffffffff
471 h ^
= 5*hash(me
.b
) ^
0xffffffff
473 _augment(ECBinCurve
, _tmp
)
477 if not me
: return '%s()' %
_clsname(me
)
478 return '%s(%s, %s)' %
(_clsname(me
), me
.ix
, me
.iy
)
480 if not me
: return 'inf'
481 return '(%s, %s)' %
(me
.ix
, me
.iy
)
482 def _repr_pretty_(me
, pp
, cyclep
):
488 ind
= _pp_bgroup(pp
, '(')
489 pp
.pretty(me
.ix
); pp
.text(','); pp
.breakable()
491 pp
.end_group(ind
, ')')
496 return '%s(curve = %r, G = %r, r = %s, h = %s)' % \
497 (_clsname(me
), me
.curve
, me
.G
, me
.r
, me
.h
)
498 def _repr_pretty_(me
, pp
, cyclep
):
499 ind
= _pp_bgroup_tyname(pp
, me
)
503 _pp_kv(pp
, 'curve', me
.curve
); pp
.text(','); pp
.breakable()
504 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
505 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
506 _pp_kv(pp
, 'h', me
.h
)
507 pp
.end_group(ind
, ')')
511 h ^
= 2*hash(me
.G
) & 0xffffffff
513 def fromstring(str): return _checkend(ECInfo
.parse(str))
514 fromstring
= staticmethod(fromstring
)
517 _augment(ECInfo
, _tmp
)
521 if not me
: return '%r()' %
(me
.curve
)
522 return '%r(%s, %s)' %
(me
.curve
, me
.x
, me
.y
)
524 if not me
: return 'inf'
525 return '(%s, %s)' %
(me
.x
, me
.y
)
526 def _repr_pretty_(me
, pp
, cyclep
):
532 ind
= _pp_bgroup(pp
, '(')
533 pp
.pretty(me
.x
); pp
.text(','); pp
.breakable()
535 pp
.end_group(ind
, ')')
536 _augment(ECPtCurve
, _tmp
)
538 ###--------------------------------------------------------------------------
542 def __repr__(me
): return '%s(%d)' %
(_clsname(me
), me
.default
)
543 def check(me
, sz
): return True
544 def best(me
, sz
): return sz
545 def pad(me
, sz
): return sz
546 _augment(KeySZAny
, _tmp
)
550 return '%s(%d, %d, %d, %d)' % \
551 (_clsname(me
), me
.default
, me
.min, me
.max, me
.mod
)
552 def _repr_pretty_(me
, pp
, cyclep
):
553 ind
= _pp_bgroup_tyname(pp
, me
)
557 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
558 pp
.pretty(me
.min); pp
.text(','); pp
.breakable()
559 pp
.pretty(me
.max); pp
.text(','); pp
.breakable()
561 pp
.end_group(ind
, ')')
562 def check(me
, sz
): return me
.min <= sz
<= me
.max and sz
%me
.mod
== 0
564 if sz
< me
.min: raise ValueError('key too small')
565 elif me
.max is not None and sz
> me
.max: return me
.max
566 else: return sz
- sz
%me
.mod
568 if me
.max is not None and sz
> me
.max: raise ValueError('key too large')
569 elif sz
< me
.min: return me
.min
570 else: sz
+= me
.mod
- 1; return sz
- sz
%me
.mod
571 _augment(KeySZRange
, _tmp
)
574 def __repr__(me
): return '%s(%d, %s)' %
(_clsname(me
), me
.default
, me
.set)
575 def _repr_pretty_(me
, pp
, cyclep
):
576 ind
= _pp_bgroup_tyname(pp
, me
)
580 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
581 ind1
= _pp_bgroup(pp
, '{')
582 _pp_commas(pp
, pp
.pretty
, me
.set)
583 pp
.end_group(ind1
, '}')
584 pp
.end_group(ind
, ')')
585 def check(me
, sz
): return sz
in me
.set
589 if found
< i
<= sz
: found
= i
590 if found
< 0: raise ValueError('key too small')
595 if sz
<= i
and (found
== -1 or i
< found
): found
= i
596 if found
< 0: raise ValueError('key too large')
598 _augment(KeySZSet
, _tmp
)
600 ###--------------------------------------------------------------------------
601 ### Key data objects.
604 def merge(me
, file, report
= None):
605 """KF.merge(FILE, [report = <built-in-reporter>])"""
609 me
.mergeline(name
, lno
, line
, report
)
612 def __repr__(me
): return '%s(%r)' %
(_clsname(me
), me
.name
)
613 _augment(KeyFile
, _tmp
)
616 def extract(me
, file, filter = ''):
617 """KEY.extract(FILE, [filter = <any>])"""
618 line
= me
.extractline(filter)
621 def __repr__(me
): return '%s(%r)' %
(_clsname(me
), me
.fulltag
)
626 return '%s({%s})' %
(_clsname(me
),
627 ', '.join(['%r: %r' % kv
for kv
in _iteritems(me
)()]))
628 def _repr_pretty_(me
, pp
, cyclep
):
629 ind
= _pp_bgroup_tyname(pp
, me
)
630 if cyclep
: pp
.text('...')
631 else: _pp_dict(pp
, _iteritems(me
))
632 pp
.end_group(ind
, ')')
633 _augment(KeyAttributes
, _tmp
)
637 return '%s(%s, %r)' %
(_clsname(me
),
638 _repr_secret(me
._guts(),
639 not (me
.flags
& KF_NONSECRET
)),
640 me
.writeflags(me
.flags
))
641 def _repr_pretty_(me
, pp
, cyclep
):
642 ind
= _pp_bgroup_tyname(pp
, me
)
646 _pp_secret(pp
, me
._guts(), not (me
.flags
& KF_NONSECRET
))
647 pp
.text(','); pp
.breakable()
648 pp
.pretty(me
.writeflags(me
.flags
))
649 pp
.end_group(ind
, ')')
650 def __hash__(me
): return me
._HASHBASE ^
hash(me
._guts())
652 return type(me
) == type(kd
) and \
653 me
._guts() == kd
._guts() and \
657 _augment(KeyData
, _tmp
)
660 def _guts(me
): return me
.bin
662 return isinstance(kd
, KeyDataBinary
) and me
.bin
== kd
.bin
663 _augment(KeyDataBinary
, _tmp
)
664 KeyDataBinary
._HASHBASE
= 0x961755c3
667 def _guts(me
): return me
.ct
668 _augment(KeyDataEncrypted
, _tmp
)
669 KeyDataEncrypted
._HASHBASE
= 0xffe000d4
672 def _guts(me
): return me
.mp
673 _augment(KeyDataMP
, _tmp
)
674 KeyDataMP
._HASHBASE
= 0x1cb64d69
677 def _guts(me
): return me
.str
678 _augment(KeyDataString
, _tmp
)
679 KeyDataString
._HASHBASE
= 0x349c33ea
682 def _guts(me
): return me
.ecpt
683 _augment(KeyDataECPt
, _tmp
)
684 KeyDataECPt
._HASHBASE
= 0x2509718b
688 return '%s({%s})' %
(_clsname(me
),
689 ', '.join(['%r: %r' % kv
for kv
in _iteritems(me
)]))
690 def _repr_pretty_(me
, pp
, cyclep
):
691 ind
= _pp_bgroup_tyname(pp
, me
, '({ ')
692 if cyclep
: pp
.text('...')
693 else: _pp_dict(pp
, _iteritems(me
))
694 pp
.end_group(ind
, ' })')
697 for k
, v
in _iteritems(me
):
698 h
= ((h
<< 1) ^
3*hash(k
) ^
5*hash(v
))&0xffffffff
701 if type(me
) != type(kd
) or me
.flags
!= kd
.flags
or len(me
) != len(kd
):
703 for k
, v
in _iteritems(me
):
705 except KeyError: return False
706 if v
!= vv
: return False
708 _augment(KeyDataStructured
, _tmp
)
709 KeyDataStructured
._HASHBASE
= 0x85851b21
711 ###--------------------------------------------------------------------------
716 return '%s(p = %s, r = %s, g = %s)' %
(_clsname(me
), me
.p
, me
.r
, me
.g
)
717 def _repr_pretty_(me
, pp
, cyclep
):
718 ind
= _pp_bgroup_tyname(pp
, me
)
722 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
723 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
724 _pp_kv(pp
, 'g', me
.g
)
725 pp
.end_group(ind
, ')')
726 _augment(FGInfo
, _tmp
)
729 def group(me
): return PrimeGroup(me
)
730 _augment(DHInfo
, _tmp
)
733 def group(me
): return BinGroup(me
)
734 _augment(BinDHInfo
, _tmp
)
738 return '%s(%r)' %
(_clsname(me
), me
.info
)
739 def _repr_pretty_(me
, pp
, cyclep
):
740 ind
= _pp_bgroup_tyname(pp
, me
)
741 if cyclep
: pp
.text('...')
742 else: pp
.pretty(me
.info
)
743 pp
.end_group(ind
, ')')
744 _augment(Group
, _tmp
)
751 h ^
= 2*hash(info
.r
) & 0xffffffff
752 h ^
= 5*hash(info
.g
) & 0xffffffff
754 def _get_geval(me
, x
): return MP(x
)
755 _augment(PrimeGroup
, _tmp
)
762 h ^
= 2*hash(info
.r
) & 0xffffffff
763 h ^
= 5*hash(info
.g
) & 0xffffffff
765 def _get_geval(me
, x
): return GF(x
)
766 _augment(BinGroup
, _tmp
)
769 def __hash__(me
): return 0x0ec23dab ^
hash(me
.info
)
770 def _get_geval(me
, x
): return x
.toec()
771 _augment(ECGroup
, _tmp
)
775 return '%r(%r)' %
(me
.group
, str(me
))
776 def _repr_pretty_(me
, pp
, cyclep
):
777 pp
.pretty(type(me
)._get_geval(me
))
780 ###--------------------------------------------------------------------------
781 ### RSA encoding techniques.
783 class PKCS1Crypt (object):
784 def __init__(me
, ep
= _bin(''), rng
= rand
):
787 def encode(me
, msg
, nbits
):
788 return _base
._p1crypt_encode(msg
, nbits
, me
.ep
, me
.rng
)
789 def decode(me
, ct
, nbits
):
790 return _base
._p1crypt_decode(ct
, nbits
, me
.ep
, me
.rng
)
792 class PKCS1Sig (object):
793 def __init__(me
, ep
= _bin(''), rng
= rand
):
796 def encode(me
, msg
, nbits
):
797 return _base
._p1sig_encode(msg
, nbits
, me
.ep
, me
.rng
)
798 def decode(me
, msg
, sig
, nbits
):
799 return _base
._p1sig_decode(msg
, sig
, nbits
, me
.ep
, me
.rng
)
802 def __init__(me
, mgf
= sha_mgf
, hash = sha
, ep
= _bin(''), rng
= rand
):
807 def encode(me
, msg
, nbits
):
808 return _base
._oaep_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
809 def decode(me
, ct
, nbits
):
810 return _base
._oaep_decode(ct
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
813 def __init__(me
, mgf
= sha_mgf
, hash = sha
, saltsz
= None, rng
= rand
):
820 def encode(me
, msg
, nbits
):
821 return _base
._pss_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
822 def decode(me
, msg
, sig
, nbits
):
823 return _base
._pss_decode(msg
, sig
, nbits
,
824 me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
827 def encrypt(me
, msg
, enc
):
828 return me
.pubop(enc
.encode(msg
, me
.n
.nbits
))
829 def verify(me
, msg
, sig
, enc
):
830 if msg
is None: return enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
832 x
= enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
833 return x
is None or x
== msg
837 return '%s(n = %r, e = %r)' %
(_clsname(me
), me
.n
, me
.e
)
838 def _repr_pretty_(me
, pp
, cyclep
):
839 ind
= _pp_bgroup_tyname(pp
, me
)
843 _pp_kv(pp
, 'n', me
.n
); pp
.text(','); pp
.breakable()
844 _pp_kv(pp
, 'e', me
.e
)
845 pp
.end_group(ind
, ')')
846 _augment(RSAPub
, _tmp
)
849 def decrypt(me
, ct
, enc
): return enc
.decode(me
.privop(ct
), me
.n
.nbits
)
850 def sign(me
, msg
, enc
): return me
.privop(enc
.encode(msg
, me
.n
.nbits
))
852 return '%s(n = %r, e = %r, d = %s, ' \
853 'p = %s, q = %s, dp = %s, dq = %s, q_inv = %s)' % \
854 (_clsname(me
), me
.n
, me
.e
,
855 _repr_secret(me
.d
), _repr_secret(me
.p
), _repr_secret(me
.q
),
856 _repr_secret(me
.dp
), _repr_secret(me
.dq
), _repr_secret(me
.q_inv
))
857 def _repr_pretty_(me
, pp
, cyclep
):
858 ind
= _pp_bgroup_tyname(pp
, me
)
862 _pp_kv(pp
, 'n', me
.n
); pp
.text(','); pp
.breakable()
863 _pp_kv(pp
, 'e', me
.e
); pp
.text(','); pp
.breakable()
864 _pp_kv(pp
, 'd', me
.d
, secretp
= True); pp
.text(','); pp
.breakable()
865 _pp_kv(pp
, 'p', me
.p
, secretp
= True); pp
.text(','); pp
.breakable()
866 _pp_kv(pp
, 'q', me
.q
, secretp
= True); pp
.text(','); pp
.breakable()
867 _pp_kv(pp
, 'dp', me
.dp
, secretp
= True); pp
.text(','); pp
.breakable()
868 _pp_kv(pp
, 'dq', me
.dq
, secretp
= True); pp
.text(','); pp
.breakable()
869 _pp_kv(pp
, 'q_inv', me
.q_inv
, secretp
= True)
870 pp
.end_group(ind
, ')')
871 _augment(RSAPriv
, _tmp
)
873 ###--------------------------------------------------------------------------
874 ### DSA and related schemes.
877 def __repr__(me
): return '%s(G = %r, p = %r, hash = %r)' % \
878 (_clsname(me
), me
.G
, me
.p
, me
.hash)
879 def _repr_pretty_(me
, pp
, cyclep
):
880 ind
= _pp_bgroup_tyname(pp
, me
)
884 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
885 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
886 _pp_kv(pp
, 'hash', me
.hash)
887 pp
.end_group(ind
, ')')
888 _augment(DSAPub
, _tmp
)
889 _augment(KCDSAPub
, _tmp
)
892 def __repr__(me
): return '%s(G = %r, u = %s, p = %r, hash = %r)' % \
893 (_clsname(me
), me
.G
, _repr_secret(me
.u
), me
.p
, me
.hash)
894 def _repr_pretty_(me
, pp
, cyclep
):
895 ind
= _pp_bgroup_tyname(pp
, me
)
899 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
900 _pp_kv(pp
, 'u', me
.u
, True); pp
.text(','); pp
.breakable()
901 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
902 _pp_kv(pp
, 'hash', me
.hash)
903 pp
.end_group(ind
, ')')
904 _augment(DSAPriv
, _tmp
)
905 _augment(KCDSAPriv
, _tmp
)
907 ###--------------------------------------------------------------------------
908 ### Bernstein's elliptic curve crypto and related schemes.
910 X25519_BASE
= MP(9).storel(32)
911 X448_BASE
= MP(5).storel(56)
913 Z128
= ByteString
.zero(16)
915 class _BasePub (object):
916 def __init__(me
, pub
, *args
, **kw
):
917 if not me
._PUBSZ
.check(len(pub
)): raise ValueError('bad public key')
918 super(_BasePub
, me
).__init__(*args
, **kw
)
920 def __repr__(me
): return '%s(pub = %r)' %
(_clsname(me
), me
.pub
)
921 def _pp(me
, pp
): _pp_kv(pp
, 'pub', me
.pub
)
922 def _repr_pretty_(me
, pp
, cyclep
):
923 ind
= _pp_bgroup_tyname(pp
, me
)
924 if cyclep
: pp
.text('...')
926 pp
.end_group(ind
, ')')
928 class _BasePriv (object):
929 def __init__(me
, priv
, pub
= None, *args
, **kw
):
930 if not me
._KEYSZ
.check(len(priv
)): raise ValueError('bad private key')
931 if pub
is None: pub
= me
._pubkey(priv
)
932 super(_BasePriv
, me
).__init__(pub
= pub
, *args
, **kw
)
935 def generate(cls
, rng
= rand
):
936 return cls(rng
.block(cls
._KEYSZ
.default
))
938 return '%s(priv = %d, pub = %r)' % \
939 (_clsname(me
), _repr_secret(me
.priv
), me
.pub
)
941 _pp_kv(pp
, 'priv', me
.priv
, secretp
= True); pp
.text(','); pp
.breakable()
942 super(_BasePriv
, me
)._pp(pp
)
944 class _XDHPub (_BasePub
): pass
946 class _XDHPriv (_BasePriv
):
947 def _pubkey(me
, priv
): return me
._op(priv
, me
._BASE
)
948 def agree(me
, you
): return me
._op(me
.priv
, you
.pub
)
949 def boxkey(me
, recip
): return me
._hashkey(me
.agree(recip
))
950 def box(me
, recip
, n
, m
): return secret_box(me
.boxkey(recip
), n
, m
)
951 def unbox(me
, recip
, n
, c
): return secret_unbox(me
.boxkey(recip
), n
, c
)
953 class X25519Pub (_XDHPub
):
954 _PUBSZ
= KeySZSet(X25519_PUBSZ
)
957 class X25519Priv (_XDHPriv
, X25519Pub
):
958 _KEYSZ
= KeySZSet(X25519_KEYSZ
)
959 def _op(me
, k
, X
): return x25519(k
, X
)
960 def _hashkey(me
, z
): return hsalsa20_prf(z
, Z128
)
962 class X448Pub (_XDHPub
):
963 _PUBSZ
= KeySZSet(X448_PUBSZ
)
966 class X448Priv (_XDHPriv
, X448Pub
):
967 _KEYSZ
= KeySZSet(X448_KEYSZ
)
968 def _op(me
, k
, X
): return x448(k
, X
)
969 def _hashkey(me
, z
): return Shake256().hash(z
).done(salsa20
.keysz
.default
)
971 class _EdDSAPub (_BasePub
):
972 def beginhash(me
): return me
._HASH()
973 def endhash(me
, h
): return h
.done()
975 class _EdDSAPriv (_BasePriv
, _EdDSAPub
):
978 class Ed25519Pub (_EdDSAPub
):
979 _PUBSZ
= KeySZSet(ED25519_PUBSZ
)
981 def verify(me
, msg
, sig
, **kw
):
982 return ed25519_verify(me
.pub
, msg
, sig
, **kw
)
984 class Ed25519Priv (_EdDSAPriv
, Ed25519Pub
):
985 _KEYSZ
= KeySZAny(ED25519_KEYSZ
)
986 def _pubkey(me
, priv
): return ed25519_pubkey(priv
)
987 def sign(me
, msg
, **kw
):
988 return ed25519_sign(me
.priv
, msg
, pub
= me
.pub
, **kw
)
990 class Ed448Pub (_EdDSAPub
):
991 _PUBSZ
= KeySZSet(ED448_PUBSZ
)
993 def verify(me
, msg
, sig
, **kw
):
994 return ed448_verify(me
.pub
, msg
, sig
, **kw
)
996 class Ed448Priv (_EdDSAPriv
, Ed448Pub
):
997 _KEYSZ
= KeySZAny(ED448_KEYSZ
)
998 def _pubkey(me
, priv
): return ed448_pubkey(priv
)
999 def sign(me
, msg
, **kw
):
1000 return ed448_sign(me
.priv
, msg
, pub
= me
.pub
, **kw
)
1002 ###--------------------------------------------------------------------------
1003 ### Built-in algorithm and group tables.
1007 return '{%s}' %
', '.join(['%r: %r' % kv
for kv
in _iteritems(me
)])
1008 def _repr_pretty_(me
, pp
, cyclep
):
1009 ind
= _pp_bgroup(pp
, '{ ')
1010 if cyclep
: pp
.text('...')
1011 else: _pp_dict(pp
, _iteritems(me
))
1012 pp
.end_group(ind
, ' }')
1013 _augment(_base
._MiscTable
, _tmp
)
1015 ###--------------------------------------------------------------------------
1016 ### Prime number generation.
1018 class PrimeGenEventHandler (object):
1019 def pg_begin(me
, ev
):
1020 return me
.pg_try(ev
)
1021 def pg_done(me
, ev
):
1023 def pg_abort(me
, ev
):
1025 def pg_fail(me
, ev
):
1027 def pg_pass(me
, ev
):
1030 class SophieGermainStepJump (object):
1031 def pg_begin(me
, ev
):
1032 me
.lf
= PrimeFilter(ev
.x
)
1033 me
.hf
= me
.lf
.muladd(2, 1)
1039 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
1041 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
1044 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
1047 def pg_done(me
, ev
):
1051 class SophieGermainStepper (SophieGermainStepJump
):
1052 def __init__(me
, step
):
1056 me
.lf
.step(me
.lstep
)
1057 me
.hf
.step(me
.hstep
)
1059 class SophieGermainJumper (SophieGermainStepJump
):
1060 def __init__(me
, jump
):
1061 me
.ljump
= PrimeFilter(jump
);
1062 me
.hjump
= me
.ljump
.muladd(2, 0)
1064 me
.lf
.jump(me
.ljump
)
1065 me
.hf
.jump(me
.hjump
)
1066 def pg_done(me
, ev
):
1069 SophieGermainStepJump
.pg_done(me
, ev
)
1071 class SophieGermainTester (object):
1074 def pg_begin(me
, ev
):
1075 me
.lr
= RabinMiller(ev
.x
)
1076 me
.hr
= RabinMiller(2 * ev
.x
+ 1)
1078 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
1079 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
1081 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
1082 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
1084 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
1087 def pg_done(me
, ev
):
1091 class PrimitiveStepper (PrimeGenEventHandler
):
1097 def pg_begin(me
, ev
):
1098 me
.i
= iter(smallprimes
)
1099 return me
.pg_try(ev
)
1101 class PrimitiveTester (PrimeGenEventHandler
):
1102 def __init__(me
, mod
, hh
= [], exp
= None):
1103 me
.mod
= MPMont(mod
)
1108 if me
.exp
is not None:
1109 x
= me
.mod
.exp(x
, me
.exp
)
1110 if x
== 1: return PGEN_FAIL
1112 if me
.mod
.exp(x
, h
) == 1: return PGEN_FAIL
1116 class SimulStepper (PrimeGenEventHandler
):
1117 def __init__(me
, mul
= 2, add
= 1, step
= 2):
1121 def _stepfn(me
, step
):
1123 raise ValueError('step must be positive')
1125 return lambda f
: f
.step(step
)
1126 j
= PrimeFilter(step
)
1127 return lambda f
: f
.jump(j
)
1128 def pg_begin(me
, ev
):
1130 me
.lf
= PrimeFilter(x
)
1131 me
.hf
= PrimeFilter(x
* me
.mul
+ me
.add
)
1132 me
.lstep
= me
._stepfn(me
.step
)
1133 me
.hstep
= me
._stepfn(me
.step
* me
.mul
)
1134 SimulStepper
._cont(me
, ev
)
1142 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
1144 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
1147 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
1150 def pg_done(me
, ev
):
1156 class SimulTester (PrimeGenEventHandler
):
1157 def __init__(me
, mul
= 2, add
= 1):
1160 def pg_begin(me
, ev
):
1162 me
.lr
= RabinMiller(x
)
1163 me
.hr
= RabinMiller(x
* me
.mul
+ me
.add
)
1165 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
1166 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
1168 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
1169 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
1171 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
1174 def pg_done(me
, ev
):
1178 def sgprime(start
, step
= 2, name
= 'p', event
= pgen_nullev
, nsteps
= 0):
1180 return pgen(start
, name
, SimulStepper(step
= step
), SimulTester(), event
,
1181 nsteps
, RabinMiller
.iters(start
.nbits
))
1183 def findprimitive(mod
, hh
= [], exp
= None, name
= 'g', event
= pgen_nullev
):
1184 return pgen(0, name
, PrimitiveStepper(), PrimitiveTester(mod
, hh
, exp
),
1187 def kcdsaprime(pbits
, qbits
, rng
= rand
,
1188 event
= pgen_nullev
, name
= 'p', nsteps
= 0):
1189 hbits
= pbits
- qbits
1190 h
= pgen(rng
.mp(hbits
, 1), name
+ ' [h]',
1191 PrimeGenStepper(2), PrimeGenTester(),
1192 event
, nsteps
, RabinMiller
.iters(hbits
))
1193 q
= pgen(rng
.mp(qbits
, 1), name
, SimulStepper(2 * h
, 1, 2),
1194 SimulTester(2 * h
, 1), event
, nsteps
, RabinMiller
.iters(qbits
))
1198 #----- That's all, folks ----------------------------------------------------