d59d3f3e5216137648a683bdf8e0c224a75f2dd0
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.
276 if isinstance(x
, BaseRat
): return x
._n
, x
._d
278 class BaseRat (object):
279 """Base class implementing fields of fractions over Euclidean domains."""
280 def __new__(cls
, a
, b
):
281 a
, b
= cls
.RING(a
), cls
.RING(b
)
285 me
= super(BaseRat
, cls
).__new__(cls
)
290 def numer(me
): return me
._n
292 def denom(me
): return me
._d
293 def __str__(me
): return '%s/%s' %
(me
._n
, me
._d
)
294 def __repr__(me
): return '%s(%s, %s)' %
(_clsname(me
), me
._n
, me
._d
)
295 _repr_pretty_
= _pp_str
297 def __add__(me
, you
):
298 n
, d
= _split_rat(you
)
299 return type(me
)(me
._n
*d
+ n
*me
._d
, d
*me
._d
)
301 def __sub__(me
, you
):
302 n
, d
= _split_rat(you
)
303 return type(me
)(me
._n
*d
- n
*me
._d
, d
*me
._d
)
304 def __rsub__(me
, you
):
305 n
, d
= _split_rat(you
)
306 return type(me
)(n
*me
._d
- me
._n
*d
, d
*me
._d
)
307 def __mul__(me
, you
):
308 n
, d
= _split_rat(you
)
309 return type(me
)(me
._n
*n
, me
._d
*d
)
311 def __truediv__(me
, you
):
312 n
, d
= _split_rat(you
)
313 return type(me
)(me
._n
*d
, me
._d
*n
)
314 def __rtruediv__(me
, you
):
315 n
, d
= _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
= _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 def __new__(cls
, a
, b
):
333 if isinstance(a
, float) or isinstance(b
, float): return a
/b
334 return super(IntRat
, cls
).__new__(cls
, a
, b
)
335 def __float__(me
): return float(me
._n
)/float(me
._d
)
337 class GFRat (BaseRat
):
341 def negp(x
): return x
< 0
342 def posp(x
): return x
> 0
343 def zerop(x
): return x
== 0
344 def oddp(x
): return x
.testbit(0)
345 def evenp(x
): return not x
.testbit(0)
346 def mont(x
): return MPMont(x
)
347 def barrett(x
): return MPBarrett(x
)
348 def reduce(x
): return MPReduce(x
)
349 def __truediv__(me
, you
):
350 if isinstance(you
, float): return _long(me
)/you
351 else: return IntRat(me
, you
)
352 def __rtruediv__(me
, you
):
353 if isinstance(you
, float): return you
/_long(me
)
354 else: return IntRat(you
, me
)
355 if _sys
.version_info
< (3,):
356 __div__
= __truediv__
357 __rdiv__
= __rtruediv__
358 _repr_pretty_
= _pp_str
362 def zerop(x
): return x
== 0
363 def reduce(x
): return GFReduce(x
)
364 def trace(x
, y
): return x
.reduce().trace(y
)
365 def halftrace(x
, y
): return x
.reduce().halftrace(y
)
366 def modsqrt(x
, y
): return x
.reduce().sqrt(y
)
367 def quadsolve(x
, y
): return x
.reduce().quadsolve(y
)
368 def __truediv__(me
, you
): return GFRat(me
, you
)
369 def __rtruediv__(me
, you
): return GFRat(you
, me
)
370 if _sys
.version_info
< (3,):
371 __div__
= __truediv__
372 __rdiv__
= __rtruediv__
373 _repr_pretty_
= _pp_str
378 'product(ITERABLE) or product(I, ...) -> PRODUCT'
379 return MPMul(*arg
).done()
380 product
= staticmethod(product
)
381 _augment(MPMul
, _tmp
)
383 ###--------------------------------------------------------------------------
387 def fromstring(str): return _checkend(Field
.parse(str))
388 fromstring
= staticmethod(fromstring
)
389 _augment(Field
, _tmp
)
392 def __repr__(me
): return '%s(%s)' %
(_clsname(me
), me
.p
)
393 def __hash__(me
): return 0x114401de ^
hash(me
.p
)
394 def _repr_pretty_(me
, pp
, cyclep
):
395 ind
= _pp_bgroup_tyname(pp
, me
)
396 if cyclep
: pp
.text('...')
397 else: pp
.pretty(me
.p
)
398 pp
.end_group(ind
, ')')
399 def ec(me
, a
, b
): return ECPrimeProjCurve(me
, a
, b
)
400 _augment(PrimeField
, _tmp
)
403 def __repr__(me
): return '%s(%#x)' %
(_clsname(me
), me
.p
)
404 def ec(me
, a
, b
): return ECBinProjCurve(me
, a
, b
)
405 def _repr_pretty_(me
, pp
, cyclep
):
406 ind
= _pp_bgroup_tyname(pp
, me
)
407 if cyclep
: pp
.text('...')
408 else: pp
.text('%#x' % me
.p
)
409 pp
.end_group(ind
, ')')
410 _augment(BinField
, _tmp
)
413 def __hash__(me
): return 0x23e4701c ^
hash(me
.p
)
414 _augment(BinPolyField
, _tmp
)
420 h ^
= 2*hash(me
.beta
) & 0xffffffff
422 _augment(BinNormField
, _tmp
)
425 def __str__(me
): return str(me
.value
)
426 def __repr__(me
): return '%s(%s)' %
(repr(me
.field
), repr(me
.value
))
427 _repr_pretty_
= _pp_str
430 ###--------------------------------------------------------------------------
435 return '%s(%r, %s, %s)' %
(_clsname(me
), me
.field
, me
.a
, me
.b
)
436 def _repr_pretty_(me
, pp
, cyclep
):
437 ind
= _pp_bgroup_tyname(pp
, me
)
441 pp
.pretty(me
.field
); pp
.text(','); pp
.breakable()
442 pp
.pretty(me
.a
); pp
.text(','); pp
.breakable()
444 pp
.end_group(ind
, ')')
446 return ecpt
.frombuf(me
, s
)
448 return ecpt
.fromraw(me
, s
)
451 _augment(ECCurve
, _tmp
)
457 h ^
= 2*hash(me
.a
) ^
0xffffffff
458 h ^
= 5*hash(me
.b
) ^
0xffffffff
460 _augment(ECPrimeCurve
, _tmp
)
466 h ^
= 2*hash(me
.a
) ^
0xffffffff
467 h ^
= 5*hash(me
.b
) ^
0xffffffff
469 _augment(ECBinCurve
, _tmp
)
473 if not me
: return '%s()' %
_clsname(me
)
474 return '%s(%s, %s)' %
(_clsname(me
), me
.ix
, me
.iy
)
476 if not me
: return 'inf'
477 return '(%s, %s)' %
(me
.ix
, me
.iy
)
478 def _repr_pretty_(me
, pp
, cyclep
):
484 ind
= _pp_bgroup(pp
, '(')
485 pp
.pretty(me
.ix
); pp
.text(','); pp
.breakable()
487 pp
.end_group(ind
, ')')
492 return '%s(curve = %r, G = %r, r = %s, h = %s)' % \
493 (_clsname(me
), me
.curve
, me
.G
, me
.r
, me
.h
)
494 def _repr_pretty_(me
, pp
, cyclep
):
495 ind
= _pp_bgroup_tyname(pp
, me
)
499 _pp_kv(pp
, 'curve', me
.curve
); pp
.text(','); pp
.breakable()
500 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
501 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
502 _pp_kv(pp
, 'h', me
.h
)
503 pp
.end_group(ind
, ')')
507 h ^
= 2*hash(me
.G
) & 0xffffffff
511 _augment(ECInfo
, _tmp
)
515 if not me
: return '%r()' %
(me
.curve
)
516 return '%r(%s, %s)' %
(me
.curve
, me
.x
, me
.y
)
518 if not me
: return 'inf'
519 return '(%s, %s)' %
(me
.x
, me
.y
)
520 def _repr_pretty_(me
, pp
, cyclep
):
526 ind
= _pp_bgroup(pp
, '(')
527 pp
.pretty(me
.x
); pp
.text(','); pp
.breakable()
529 pp
.end_group(ind
, ')')
530 _augment(ECPtCurve
, _tmp
)
532 ###--------------------------------------------------------------------------
536 def __repr__(me
): return '%s(%d)' %
(_clsname(me
), me
.default
)
537 def check(me
, sz
): return True
538 def best(me
, sz
): return sz
539 def pad(me
, sz
): return sz
540 _augment(KeySZAny
, _tmp
)
544 return '%s(%d, %d, %d, %d)' % \
545 (_clsname(me
), me
.default
, me
.min, me
.max, me
.mod
)
546 def _repr_pretty_(me
, pp
, cyclep
):
547 ind
= _pp_bgroup_tyname(pp
, me
)
551 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
552 pp
.pretty(me
.min); pp
.text(','); pp
.breakable()
553 pp
.pretty(me
.max); pp
.text(','); pp
.breakable()
555 pp
.end_group(ind
, ')')
556 def check(me
, sz
): return me
.min <= sz
<= me
.max and sz
%me
.mod
== 0
558 if sz
< me
.min: raise ValueError('key too small')
559 elif me
.max is not None and sz
> me
.max: return me
.max
560 else: return sz
- sz
%me
.mod
562 if me
.max is not None and sz
> me
.max: raise ValueError('key too large')
563 elif sz
< me
.min: return me
.min
564 else: sz
+= me
.mod
- 1; return sz
- sz
%me
.mod
565 _augment(KeySZRange
, _tmp
)
568 def __repr__(me
): return '%s(%d, %s)' %
(_clsname(me
), me
.default
, me
.set)
569 def _repr_pretty_(me
, pp
, cyclep
):
570 ind
= _pp_bgroup_tyname(pp
, me
)
574 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
575 ind1
= _pp_bgroup(pp
, '{')
576 _pp_commas(pp
, pp
.pretty
, me
.set)
577 pp
.end_group(ind1
, '}')
578 pp
.end_group(ind
, ')')
579 def check(me
, sz
): return sz
in me
.set
583 if found
< i
<= sz
: found
= i
584 if found
< 0: raise ValueError('key too small')
589 if sz
<= i
and (found
== -1 or i
< found
): found
= i
590 if found
< 0: raise ValueError('key too large')
592 _augment(KeySZSet
, _tmp
)
594 ###--------------------------------------------------------------------------
595 ### Key data objects.
598 def merge(me
, file, report
= None):
599 """KF.merge(FILE, [report = <built-in-reporter>])"""
603 me
.mergeline(name
, lno
, line
, report
)
606 def __repr__(me
): return '%s(%r)' %
(_clsname(me
), me
.name
)
607 _augment(KeyFile
, _tmp
)
610 def extract(me
, file, filter = ''):
611 """KEY.extract(FILE, [filter = <any>])"""
612 line
= me
.extractline(filter)
615 def __repr__(me
): return '%s(%r)' %
(_clsname(me
), me
.fulltag
)
620 return '%s({%s})' %
(_clsname(me
),
621 ', '.join(['%r: %r' % kv
for kv
in _iteritems(me
)()]))
622 def _repr_pretty_(me
, pp
, cyclep
):
623 ind
= _pp_bgroup_tyname(pp
, me
)
624 if cyclep
: pp
.text('...')
625 else: _pp_dict(pp
, _iteritems(me
))
626 pp
.end_group(ind
, ')')
627 _augment(KeyAttributes
, _tmp
)
631 return '%s(%s, %r)' %
(_clsname(me
),
632 _repr_secret(me
._guts(),
633 not (me
.flags
& KF_NONSECRET
)),
634 me
.writeflags(me
.flags
))
635 def _repr_pretty_(me
, pp
, cyclep
):
636 ind
= _pp_bgroup_tyname(pp
, me
)
640 _pp_secret(pp
, me
._guts(), not (me
.flags
& KF_NONSECRET
))
641 pp
.text(','); pp
.breakable()
642 pp
.pretty(me
.writeflags(me
.flags
))
643 pp
.end_group(ind
, ')')
644 def __hash__(me
): return me
._HASHBASE ^
hash(me
._guts())
646 return type(me
) == type(kd
) and \
647 me
._guts() == kd
._guts() and \
651 _augment(KeyData
, _tmp
)
654 def _guts(me
): return me
.bin
656 return isinstance(kd
, KeyDataBinary
) and me
.bin
== kd
.bin
657 _augment(KeyDataBinary
, _tmp
)
658 KeyDataBinary
._HASHBASE
= 0x961755c3
661 def _guts(me
): return me
.ct
662 _augment(KeyDataEncrypted
, _tmp
)
663 KeyDataEncrypted
._HASHBASE
= 0xffe000d4
666 def _guts(me
): return me
.mp
667 _augment(KeyDataMP
, _tmp
)
668 KeyDataMP
._HASHBASE
= 0x1cb64d69
671 def _guts(me
): return me
.str
672 _augment(KeyDataString
, _tmp
)
673 KeyDataString
._HASHBASE
= 0x349c33ea
676 def _guts(me
): return me
.ecpt
677 _augment(KeyDataECPt
, _tmp
)
678 KeyDataECPt
._HASHBASE
= 0x2509718b
682 return '%s({%s})' %
(_clsname(me
),
683 ', '.join(['%r: %r' % kv
for kv
in _iteritems(me
)]))
684 def _repr_pretty_(me
, pp
, cyclep
):
685 ind
= _pp_bgroup_tyname(pp
, me
, '({ ')
686 if cyclep
: pp
.text('...')
687 else: _pp_dict(pp
, _iteritems(me
))
688 pp
.end_group(ind
, ' })')
691 for k
, v
in _iteritems(me
):
692 h
= ((h
<< 1) ^
3*hash(k
) ^
5*hash(v
))&0xffffffff
695 if type(me
) != type(kd
) or me
.flags
!= kd
.flags
or len(me
) != len(kd
):
697 for k
, v
in _iteritems(me
):
699 except KeyError: return False
700 if v
!= vv
: return False
702 _augment(KeyDataStructured
, _tmp
)
703 KeyDataStructured
._HASHBASE
= 0x85851b21
705 ###--------------------------------------------------------------------------
710 return '%s(p = %s, r = %s, g = %s)' %
(_clsname(me
), me
.p
, me
.r
, me
.g
)
711 def _repr_pretty_(me
, pp
, cyclep
):
712 ind
= _pp_bgroup_tyname(pp
, me
)
716 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
717 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
718 _pp_kv(pp
, 'g', me
.g
)
719 pp
.end_group(ind
, ')')
720 _augment(FGInfo
, _tmp
)
723 def group(me
): return PrimeGroup(me
)
724 _augment(DHInfo
, _tmp
)
727 def group(me
): return BinGroup(me
)
728 _augment(BinDHInfo
, _tmp
)
732 return '%s(%r)' %
(_clsname(me
), me
.info
)
733 def _repr_pretty_(me
, pp
, cyclep
):
734 ind
= _pp_bgroup_tyname(pp
, me
)
735 if cyclep
: pp
.text('...')
736 else: pp
.pretty(me
.info
)
737 pp
.end_group(ind
, ')')
738 _augment(Group
, _tmp
)
745 h ^
= 2*hash(info
.r
) & 0xffffffff
746 h ^
= 5*hash(info
.g
) & 0xffffffff
748 def _get_geval(me
, x
): return MP(x
)
749 _augment(PrimeGroup
, _tmp
)
756 h ^
= 2*hash(info
.r
) & 0xffffffff
757 h ^
= 5*hash(info
.g
) & 0xffffffff
759 def _get_geval(me
, x
): return GF(x
)
760 _augment(BinGroup
, _tmp
)
763 def __hash__(me
): return 0x0ec23dab ^
hash(me
.info
)
764 def _get_geval(me
, x
): return x
.toec()
765 _augment(ECGroup
, _tmp
)
769 return '%r(%r)' %
(me
.group
, str(me
))
770 def _repr_pretty_(me
, pp
, cyclep
):
771 pp
.pretty(type(me
)._get_geval(me
))
774 ###--------------------------------------------------------------------------
775 ### RSA encoding techniques.
777 class PKCS1Crypt (object):
778 def __init__(me
, ep
= _bin(''), rng
= rand
):
781 def encode(me
, msg
, nbits
):
782 return _base
._p1crypt_encode(msg
, nbits
, me
.ep
, me
.rng
)
783 def decode(me
, ct
, nbits
):
784 return _base
._p1crypt_decode(ct
, nbits
, me
.ep
, me
.rng
)
786 class PKCS1Sig (object):
787 def __init__(me
, ep
= _bin(''), rng
= rand
):
790 def encode(me
, msg
, nbits
):
791 return _base
._p1sig_encode(msg
, nbits
, me
.ep
, me
.rng
)
792 def decode(me
, msg
, sig
, nbits
):
793 return _base
._p1sig_decode(msg
, sig
, nbits
, me
.ep
, me
.rng
)
796 def __init__(me
, mgf
= sha_mgf
, hash = sha
, ep
= _bin(''), rng
= rand
):
801 def encode(me
, msg
, nbits
):
802 return _base
._oaep_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
803 def decode(me
, ct
, nbits
):
804 return _base
._oaep_decode(ct
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
807 def __init__(me
, mgf
= sha_mgf
, hash = sha
, saltsz
= None, rng
= rand
):
814 def encode(me
, msg
, nbits
):
815 return _base
._pss_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
816 def decode(me
, msg
, sig
, nbits
):
817 return _base
._pss_decode(msg
, sig
, nbits
,
818 me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
821 def encrypt(me
, msg
, enc
):
822 return me
.pubop(enc
.encode(msg
, me
.n
.nbits
))
823 def verify(me
, msg
, sig
, enc
):
824 if msg
is None: return enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
826 x
= enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
827 return x
is None or x
== msg
831 return '%s(n = %r, e = %r)' %
(_clsname(me
), me
.n
, me
.e
)
832 def _repr_pretty_(me
, pp
, cyclep
):
833 ind
= _pp_bgroup_tyname(pp
, me
)
837 _pp_kv(pp
, 'n', me
.n
); pp
.text(','); pp
.breakable()
838 _pp_kv(pp
, 'e', me
.e
)
839 pp
.end_group(ind
, ')')
840 _augment(RSAPub
, _tmp
)
843 def decrypt(me
, ct
, enc
): return enc
.decode(me
.privop(ct
), me
.n
.nbits
)
844 def sign(me
, msg
, enc
): return me
.privop(enc
.encode(msg
, me
.n
.nbits
))
846 return '%s(n = %r, e = %r, d = %s, ' \
847 'p = %s, q = %s, dp = %s, dq = %s, q_inv = %s)' % \
848 (_clsname(me
), me
.n
, me
.e
,
849 _repr_secret(me
.d
), _repr_secret(me
.p
), _repr_secret(me
.q
),
850 _repr_secret(me
.dp
), _repr_secret(me
.dq
), _repr_secret(me
.q_inv
))
851 def _repr_pretty_(me
, pp
, cyclep
):
852 ind
= _pp_bgroup_tyname(pp
, me
)
856 _pp_kv(pp
, 'n', me
.n
); pp
.text(','); pp
.breakable()
857 _pp_kv(pp
, 'e', me
.e
); pp
.text(','); pp
.breakable()
858 _pp_kv(pp
, 'd', me
.d
, secretp
= True); pp
.text(','); pp
.breakable()
859 _pp_kv(pp
, 'p', me
.p
, secretp
= True); pp
.text(','); pp
.breakable()
860 _pp_kv(pp
, 'q', me
.q
, secretp
= True); pp
.text(','); pp
.breakable()
861 _pp_kv(pp
, 'dp', me
.dp
, secretp
= True); pp
.text(','); pp
.breakable()
862 _pp_kv(pp
, 'dq', me
.dq
, secretp
= True); pp
.text(','); pp
.breakable()
863 _pp_kv(pp
, 'q_inv', me
.q_inv
, secretp
= True)
864 pp
.end_group(ind
, ')')
865 _augment(RSAPriv
, _tmp
)
867 ###--------------------------------------------------------------------------
868 ### DSA and related schemes.
871 def __repr__(me
): return '%s(G = %r, p = %r, hash = %r)' % \
872 (_clsname(me
), me
.G
, me
.p
, me
.hash)
873 def _repr_pretty_(me
, pp
, cyclep
):
874 ind
= _pp_bgroup_tyname(pp
, me
)
878 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
879 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
880 _pp_kv(pp
, 'hash', me
.hash)
881 pp
.end_group(ind
, ')')
882 _augment(DSAPub
, _tmp
)
883 _augment(KCDSAPub
, _tmp
)
886 def __repr__(me
): return '%s(G = %r, u = %s, p = %r, hash = %r)' % \
887 (_clsname(me
), me
.G
, _repr_secret(me
.u
), me
.p
, me
.hash)
888 def _repr_pretty_(me
, pp
, cyclep
):
889 ind
= _pp_bgroup_tyname(pp
, me
)
893 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
894 _pp_kv(pp
, 'u', me
.u
, True); pp
.text(','); pp
.breakable()
895 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
896 _pp_kv(pp
, 'hash', me
.hash)
897 pp
.end_group(ind
, ')')
898 _augment(DSAPriv
, _tmp
)
899 _augment(KCDSAPriv
, _tmp
)
901 ###--------------------------------------------------------------------------
902 ### Bernstein's elliptic curve crypto and related schemes.
904 X25519_BASE
= MP(9).storel(32)
905 X448_BASE
= MP(5).storel(56)
907 Z128
= ByteString
.zero(16)
909 class _BasePub (object):
910 def __init__(me
, pub
, *args
, **kw
):
911 if not me
._PUBSZ
.check(len(pub
)): raise ValueError('bad public key')
912 super(_BasePub
, me
).__init__(*args
, **kw
)
914 def __repr__(me
): return '%s(pub = %r)' %
(_clsname(me
), me
.pub
)
915 def _pp(me
, pp
): _pp_kv(pp
, 'pub', me
.pub
)
916 def _repr_pretty_(me
, pp
, cyclep
):
917 ind
= _pp_bgroup_tyname(pp
, me
)
918 if cyclep
: pp
.text('...')
920 pp
.end_group(ind
, ')')
922 class _BasePriv (object):
923 def __init__(me
, priv
, pub
= None, *args
, **kw
):
924 if not me
._KEYSZ
.check(len(priv
)): raise ValueError('bad private key')
925 if pub
is None: pub
= me
._pubkey(priv
)
926 super(_BasePriv
, me
).__init__(pub
= pub
, *args
, **kw
)
929 def generate(cls
, rng
= rand
):
930 return cls(rng
.block(cls
._KEYSZ
.default
))
932 return '%s(priv = %d, pub = %r)' % \
933 (_clsname(me
), _repr_secret(me
.priv
), me
.pub
)
935 _pp_kv(pp
, 'priv', me
.priv
, secretp
= True); pp
.text(','); pp
.breakable()
936 super(_BasePriv
, me
)._pp(pp
)
938 class _XDHPub (_BasePub
): pass
940 class _XDHPriv (_BasePriv
):
941 def _pubkey(me
, priv
): return me
._op(priv
, me
._BASE
)
942 def agree(me
, you
): return me
._op(me
.priv
, you
.pub
)
943 def boxkey(me
, recip
): return me
._hashkey(me
.agree(recip
))
944 def box(me
, recip
, n
, m
): return secret_box(me
.boxkey(recip
), n
, m
)
945 def unbox(me
, recip
, n
, c
): return secret_unbox(me
.boxkey(recip
), n
, c
)
947 class X25519Pub (_XDHPub
):
948 _PUBSZ
= KeySZSet(X25519_PUBSZ
)
951 class X25519Priv (_XDHPriv
, X25519Pub
):
952 _KEYSZ
= KeySZSet(X25519_KEYSZ
)
953 def _op(me
, k
, X
): return x25519(k
, X
)
954 def _hashkey(me
, z
): return hsalsa20_prf(z
, Z128
)
956 class X448Pub (_XDHPub
):
957 _PUBSZ
= KeySZSet(X448_PUBSZ
)
960 class X448Priv (_XDHPriv
, X448Pub
):
961 _KEYSZ
= KeySZSet(X448_KEYSZ
)
962 def _op(me
, k
, X
): return x448(k
, X
)
963 def _hashkey(me
, z
): return Shake256().hash(z
).done(salsa20
.keysz
.default
)
965 class _EdDSAPub (_BasePub
):
966 def beginhash(me
): return me
._HASH()
967 def endhash(me
, h
): return h
.done()
969 class _EdDSAPriv (_BasePriv
, _EdDSAPub
):
972 class Ed25519Pub (_EdDSAPub
):
973 _PUBSZ
= KeySZSet(ED25519_PUBSZ
)
975 def verify(me
, msg
, sig
, **kw
):
976 return ed25519_verify(me
.pub
, msg
, sig
, **kw
)
978 class Ed25519Priv (_EdDSAPriv
, Ed25519Pub
):
979 _KEYSZ
= KeySZAny(ED25519_KEYSZ
)
980 def _pubkey(me
, priv
): return ed25519_pubkey(priv
)
981 def sign(me
, msg
, **kw
):
982 return ed25519_sign(me
.priv
, msg
, pub
= me
.pub
, **kw
)
984 class Ed448Pub (_EdDSAPub
):
985 _PUBSZ
= KeySZSet(ED448_PUBSZ
)
987 def verify(me
, msg
, sig
, **kw
):
988 return ed448_verify(me
.pub
, msg
, sig
, **kw
)
990 class Ed448Priv (_EdDSAPriv
, Ed448Pub
):
991 _KEYSZ
= KeySZAny(ED448_KEYSZ
)
992 def _pubkey(me
, priv
): return ed448_pubkey(priv
)
993 def sign(me
, msg
, **kw
):
994 return ed448_sign(me
.priv
, msg
, pub
= me
.pub
, **kw
)
996 ###--------------------------------------------------------------------------
997 ### Built-in algorithm and group tables.
1001 return '{%s}' %
', '.join(['%r: %r' % kv
for kv
in _iteritems(me
)])
1002 def _repr_pretty_(me
, pp
, cyclep
):
1003 ind
= _pp_bgroup(pp
, '{ ')
1004 if cyclep
: pp
.text('...')
1005 else: _pp_dict(pp
, _iteritems(me
))
1006 pp
.end_group(ind
, ' }')
1007 _augment(_base
._MiscTable
, _tmp
)
1009 ###--------------------------------------------------------------------------
1010 ### Prime number generation.
1012 class PrimeGenEventHandler (object):
1013 def pg_begin(me
, ev
):
1014 return me
.pg_try(ev
)
1015 def pg_done(me
, ev
):
1017 def pg_abort(me
, ev
):
1019 def pg_fail(me
, ev
):
1021 def pg_pass(me
, ev
):
1024 class SophieGermainStepJump (object):
1025 def pg_begin(me
, ev
):
1026 me
.lf
= PrimeFilter(ev
.x
)
1027 me
.hf
= me
.lf
.muladd(2, 1)
1033 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
1035 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
1038 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
1041 def pg_done(me
, ev
):
1045 class SophieGermainStepper (SophieGermainStepJump
):
1046 def __init__(me
, step
):
1050 me
.lf
.step(me
.lstep
)
1051 me
.hf
.step(me
.hstep
)
1053 class SophieGermainJumper (SophieGermainStepJump
):
1054 def __init__(me
, jump
):
1055 me
.ljump
= PrimeFilter(jump
);
1056 me
.hjump
= me
.ljump
.muladd(2, 0)
1058 me
.lf
.jump(me
.ljump
)
1059 me
.hf
.jump(me
.hjump
)
1060 def pg_done(me
, ev
):
1063 SophieGermainStepJump
.pg_done(me
, ev
)
1065 class SophieGermainTester (object):
1068 def pg_begin(me
, ev
):
1069 me
.lr
= RabinMiller(ev
.x
)
1070 me
.hr
= RabinMiller(2 * ev
.x
+ 1)
1072 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
1073 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
1075 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
1076 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
1078 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
1081 def pg_done(me
, ev
):
1085 class PrimitiveStepper (PrimeGenEventHandler
):
1091 def pg_begin(me
, ev
):
1092 me
.i
= iter(smallprimes
)
1093 return me
.pg_try(ev
)
1095 class PrimitiveTester (PrimeGenEventHandler
):
1096 def __init__(me
, mod
, hh
= [], exp
= None):
1097 me
.mod
= MPMont(mod
)
1102 if me
.exp
is not None:
1103 x
= me
.mod
.exp(x
, me
.exp
)
1104 if x
== 1: return PGEN_FAIL
1106 if me
.mod
.exp(x
, h
) == 1: return PGEN_FAIL
1110 class SimulStepper (PrimeGenEventHandler
):
1111 def __init__(me
, mul
= 2, add
= 1, step
= 2):
1115 def _stepfn(me
, step
):
1117 raise ValueError('step must be positive')
1119 return lambda f
: f
.step(step
)
1120 j
= PrimeFilter(step
)
1121 return lambda f
: f
.jump(j
)
1122 def pg_begin(me
, ev
):
1124 me
.lf
= PrimeFilter(x
)
1125 me
.hf
= PrimeFilter(x
* me
.mul
+ me
.add
)
1126 me
.lstep
= me
._stepfn(me
.step
)
1127 me
.hstep
= me
._stepfn(me
.step
* me
.mul
)
1128 SimulStepper
._cont(me
, ev
)
1136 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
1138 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
1141 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
1144 def pg_done(me
, ev
):
1150 class SimulTester (PrimeGenEventHandler
):
1151 def __init__(me
, mul
= 2, add
= 1):
1154 def pg_begin(me
, ev
):
1156 me
.lr
= RabinMiller(x
)
1157 me
.hr
= RabinMiller(x
* me
.mul
+ me
.add
)
1159 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
1160 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
1162 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
1163 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
1165 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
1168 def pg_done(me
, ev
):
1172 def sgprime(start
, step
= 2, name
= 'p', event
= pgen_nullev
, nsteps
= 0):
1174 return pgen(start
, name
, SimulStepper(step
= step
), SimulTester(), event
,
1175 nsteps
, RabinMiller
.iters(start
.nbits
))
1177 def findprimitive(mod
, hh
= [], exp
= None, name
= 'g', event
= pgen_nullev
):
1178 return pgen(0, name
, PrimitiveStepper(), PrimitiveTester(mod
, hh
, exp
),
1181 def kcdsaprime(pbits
, qbits
, rng
= rand
,
1182 event
= pgen_nullev
, name
= 'p', nsteps
= 0):
1183 hbits
= pbits
- qbits
1184 h
= pgen(rng
.mp(hbits
, 1), name
+ ' [h]',
1185 PrimeGenStepper(2), PrimeGenTester(),
1186 event
, nsteps
, RabinMiller
.iters(hbits
))
1187 q
= pgen(rng
.mp(qbits
, 1), name
, SimulStepper(2 * h
, 1, 2),
1188 SimulTester(2 * h
, 1), event
, nsteps
, RabinMiller
.iters(qbits
))
1192 #----- That's all, folks ----------------------------------------------------