bbbe74b5cfad76c83030000999294ae52909cff3
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 ## How to fix a name back into the right identifier. Alas, the rules are not
87 ## Hyphens consistently become underscores.
88 name
= name
.replace('-', '_')
90 ## But slashes might become underscores or just vanish.
91 if name
.startswith('salsa20'): name
= name
.replace('/', '')
92 else: name
= name
.replace('/', '_')
97 ## Initialize the module. Drag in the static methods of the various
98 ## classes; create names for the various known crypto algorithms.
105 for i
in [gcciphers
, gcaeads
, gchashes
, gcmacs
, gcprps
]:
106 for c
in i
.itervalues():
107 d
[_fixname(c
.name
)] = c
108 for c
in gccrands
.itervalues():
109 d
[_fixname(c
.name
+ 'rand')] = c
112 ## A handy function for our work: add the methods of a named class to an
113 ## existing class. This is how we write the Python-implemented parts of our
116 for i
in cc
.__dict__
:
118 if type(a
) is _types
.MethodType
:
120 elif type(a
) not in (_types
.FunctionType
, staticmethod, classmethod):
124 ## Parsing functions tend to return the object parsed and the remainder of
125 ## the input. This checks that the remainder is input and, if so, returns
130 raise SyntaxError('junk at end of string')
133 ## Some pretty-printing utilities.
134 PRINT_SECRETS
= False
135 def _clsname(me
): return type(me
).__name__
136 def _repr_secret(thing
, secretp
= True):
137 if not secretp
or PRINT_SECRETS
: return repr(thing
)
138 else: return '#<SECRET>'
139 def _pp_str(me
, pp
, cyclep
): pp
.text(cyclep
and '...' or str(me
))
140 def _pp_secret(pp
, thing
, secretp
= True):
141 if not secretp
or PRINT_SECRETS
: pp
.pretty(thing
)
142 else: pp
.text('#<SECRET>')
143 def _pp_bgroup(pp
, text
):
145 pp
.begin_group(ind
, text
)
147 def _pp_bgroup_tyname(pp
, obj
, open = '('):
148 return _pp_bgroup(pp
, _clsname(obj
) + open)
149 def _pp_kv(pp
, k
, v
, secretp
= False):
150 ind
= _pp_bgroup(pp
, k
+ ' = ')
151 _pp_secret(pp
, v
, secretp
)
152 pp
.end_group(ind
, '')
153 def _pp_commas(pp
, printfn
, items
):
156 if firstp
: firstp
= False
157 else: pp
.text(','); pp
.breakable()
159 def _pp_dict(pp
, items
):
169 _pp_commas(pp
, p
, items
)
171 ###--------------------------------------------------------------------------
176 return ByteString(_unhexify(x
))
177 fromhex
= staticmethod(fromhex
)
181 return 'bytes(%r)' %
hex(me
)
182 _augment(ByteString
, _tmp
)
183 ByteString
.__hash__
= str.__hash__
184 bytes
= ByteString
.fromhex
186 ###--------------------------------------------------------------------------
187 ### Symmetric encryption.
190 def encrypt(me
, n
, m
, tsz
= None, h
= ByteString('')):
191 if tsz
is None: tsz
= me
.__class__
.tagsz
.default
192 e
= me
.enc(n
, len(h
), len(m
), tsz
)
193 if not len(h
): a
= None
194 else: a
= e
.aad().hash(h
)
196 c1
, t
= e
.done(aad
= a
)
198 def decrypt(me
, n
, c
, t
, h
= ByteString('')):
199 d
= me
.dec(n
, len(h
), len(c
), len(t
))
200 if not len(h
): a
= None
201 else: a
= d
.aad().hash(h
)
203 m
+= d
.done(t
, aad
= a
)
205 _augment(GAEKey
, _tmp
)
207 ###--------------------------------------------------------------------------
213 return ctstreq(h
, hh
)
214 _augment(GHash
, _tmp
)
215 _augment(Poly1305Hash
, _tmp
)
217 class _HashBase (object):
218 ## The standard hash methods. Assume that `hash' is defined and returns
220 def _check_range(me
, n
, max):
221 if not (0 <= n
<= max): raise OverflowError("out of range")
223 me
._check_range(n
, 0xff)
224 return me
.hash(_pack('B', n
))
226 me
._check_range(n
, 0xffff)
227 return me
.hash(_pack('<H', n
))
229 me
._check_range(n
, 0xffff)
230 return me
.hash(_pack('>H', n
))
233 me
._check_range(n
, 0xffffffff)
234 return me
.hash(_pack('<L', n
))
236 me
._check_range(n
, 0xffffffff)
237 return me
.hash(_pack('>L', n
))
240 me
._check_range(n
, 0xffffffffffffffff)
241 return me
.hash(_pack('<Q', n
))
243 me
._check_range(n
, 0xffffffffffffffff)
244 return me
.hash(_pack('>Q', n
))
246 def hashbuf8(me
, s
): return me
.hashu8(len(s
)).hash(s
)
247 def hashbuf16l(me
, s
): return me
.hashu16l(len(s
)).hash(s
)
248 def hashbuf16b(me
, s
): return me
.hashu16b(len(s
)).hash(s
)
249 hashbuf16
= hashbuf16b
250 def hashbuf32l(me
, s
): return me
.hashu32l(len(s
)).hash(s
)
251 def hashbuf32b(me
, s
): return me
.hashu32b(len(s
)).hash(s
)
252 hashbuf32
= hashbuf32b
253 def hashbuf64l(me
, s
): return me
.hashu64l(len(s
)).hash(s
)
254 def hashbuf64b(me
, s
): return me
.hashu64b(len(s
)).hash(s
)
255 hashbuf64
= hashbuf64b
256 def hashstrz(me
, s
): return me
.hash(s
).hashu8(0)
258 class _ShakeBase (_HashBase
):
260 ## Python gets really confused if I try to augment `__new__' on native
261 ## classes, so wrap and delegate. Sorry.
262 def __init__(me
, perso
= _bin(''), *args
, **kw
):
263 super(_ShakeBase
, me
).__init__(*args
, **kw
)
264 me
._h
= me
._SHAKE(perso
= perso
, func
= me
._FUNC
)
266 ## Delegate methods...
267 def copy(me
): new
= me
.__class__
._bare_new(); new
._copy(me
); return new
268 def _copy(me
, other
): me
._h
= other
._h
.copy()
269 def hash(me
, m
): me
._h
.hash(m
); return me
270 def xof(me
): me
._h
.xof(); return me
271 def get(me
, n
): return me
._h
.get(n
)
272 def mask(me
, m
): return me
._h
.mask(m
)
273 def done(me
, n
): return me
._h
.done(n
)
274 def check(me
, h
): return ctstreq(h
, me
.done(len(h
)))
276 def state(me
): return me
._h
.state
278 def buffered(me
): return me
._h
.buffered
280 def rate(me
): return me
._h
.rate
282 def _bare_new(cls
): return cls()
286 return ctstreq(h
, me
.done(len(h
)))
289 return me
.hashu8(len(nn
)).hash(nn
)
292 return me
.hash(nn
).hashu8(len(nn
))
293 def stringenc(me
, str):
294 return me
.leftenc(8*len(str)).hash(str)
295 def bytepad_before(me
):
296 return me
.leftenc(me
.rate
)
297 def bytepad_after(me
):
298 if me
.buffered
: me
.hash(me
._Z
[:me
.rate
- me
.buffered
])
305 _augment(Shake
, _tmp
)
306 _augment(_ShakeBase
, _tmp
)
307 Shake
._Z
= _ShakeBase
._Z
= ByteString
.zero(200)
309 class KMAC (_ShakeBase
):
311 def __init__(me
, k
, *arg
, **kw
):
312 super(KMAC
, me
).__init__(*arg
, **kw
)
313 with me
.bytepad(): me
.stringenc(k
)
314 def done(me
, n
= -1):
315 if n
< 0: n
= me
._TAGSZ
317 return super(KMAC
, me
).done(n
)
320 return super(KMAC
, me
).xof()
322 def _bare_new(cls
): return cls(_bin(""))
324 class KMAC128 (KMAC
): _SHAKE
= Shake128
; _TAGSZ
= 16
325 class KMAC256 (KMAC
): _SHAKE
= Shake256
; _TAGSZ
= 32
327 ###--------------------------------------------------------------------------
328 ### NaCl `secretbox'.
330 def secret_box(k
, n
, m
):
331 y
, t
= salsa20_naclbox(k
).encrypt(n
, m
)
334 def secret_unbox(k
, n
, c
):
336 return salsa20_naclbox(k
).decrypt(n
, c
[tsz
:], c
[0:tsz
])
338 ###--------------------------------------------------------------------------
339 ### Multiprecision integers and binary polynomials.
342 if isinstance(x
, BaseRat
): return x
._n
, x
._d
344 class BaseRat (object):
345 """Base class implementing fields of fractions over Euclidean domains."""
346 def __new__(cls
, a
, b
):
347 a
, b
= cls
.RING(a
), cls
.RING(b
)
351 me
= super(BaseRat
, cls
).__new__(cls
)
356 def numer(me
): return me
._n
358 def denom(me
): return me
._d
359 def __str__(me
): return '%s/%s' %
(me
._n
, me
._d
)
360 def __repr__(me
): return '%s(%s, %s)' %
(_clsname(me
), me
._n
, me
._d
)
361 _repr_pretty_
= _pp_str
363 def __add__(me
, you
):
364 n
, d
= _split_rat(you
)
365 return type(me
)(me
._n
*d
+ n
*me
._d
, d
*me
._d
)
367 def __sub__(me
, you
):
368 n
, d
= _split_rat(you
)
369 return type(me
)(me
._n
*d
- n
*me
._d
, d
*me
._d
)
370 def __rsub__(me
, you
):
371 n
, d
= _split_rat(you
)
372 return type(me
)(n
*me
._d
- me
._n
*d
, d
*me
._d
)
373 def __mul__(me
, you
):
374 n
, d
= _split_rat(you
)
375 return type(me
)(me
._n
*n
, me
._d
*d
)
377 def __truediv__(me
, you
):
378 n
, d
= _split_rat(you
)
379 return type(me
)(me
._n
*d
, me
._d
*n
)
380 def __rtruediv__(me
, you
):
381 n
, d
= _split_rat(you
)
382 return type(me
)(me
._d
*n
, me
._n
*d
)
383 __div__
= __truediv__
384 __rdiv__
= __rtruediv__
385 def __cmp__(me
, you
):
386 n
, d
= _split_rat(you
)
387 return cmp(me
._n
*d
, n
*me
._d
)
388 def __rcmp__(me
, you
):
389 n
, d
= _split_rat(you
)
390 return cmp(n
*me
._d
, me
._n
*d
)
392 class IntRat (BaseRat
):
395 class GFRat (BaseRat
):
399 def negp(x
): return x
< 0
400 def posp(x
): return x
> 0
401 def zerop(x
): return x
== 0
402 def oddp(x
): return x
.testbit(0)
403 def evenp(x
): return not x
.testbit(0)
404 def mont(x
): return MPMont(x
)
405 def barrett(x
): return MPBarrett(x
)
406 def reduce(x
): return MPReduce(x
)
407 def __truediv__(me
, you
): return IntRat(me
, you
)
408 def __rtruediv__(me
, you
): return IntRat(you
, me
)
409 __div__
= __truediv__
410 __rdiv__
= __rtruediv__
411 _repr_pretty_
= _pp_str
415 def zerop(x
): return x
== 0
416 def reduce(x
): return GFReduce(x
)
417 def trace(x
, y
): return x
.reduce().trace(y
)
418 def halftrace(x
, y
): return x
.reduce().halftrace(y
)
419 def modsqrt(x
, y
): return x
.reduce().sqrt(y
)
420 def quadsolve(x
, y
): return x
.reduce().quadsolve(y
)
421 def __truediv__(me
, you
): return GFRat(me
, you
)
422 def __rtruediv__(me
, you
): return GFRat(you
, me
)
423 __div__
= __truediv__
424 __rdiv__
= __rtruediv__
425 _repr_pretty_
= _pp_str
430 'product(ITERABLE) or product(I, ...) -> PRODUCT'
431 return MPMul(*arg
).done()
432 product
= staticmethod(product
)
433 _augment(MPMul
, _tmp
)
435 ###--------------------------------------------------------------------------
439 def fromstring(str): return _checkend(Field
.parse(str))
440 fromstring
= staticmethod(fromstring
)
441 _augment(Field
, _tmp
)
444 def __repr__(me
): return '%s(%sL)' %
(_clsname(me
), me
.p
)
445 def __hash__(me
): return 0x114401de ^
hash(me
.p
)
446 def _repr_pretty_(me
, pp
, cyclep
):
447 ind
= _pp_bgroup_tyname(pp
, me
)
448 if cyclep
: pp
.text('...')
449 else: pp
.pretty(me
.p
)
450 pp
.end_group(ind
, ')')
451 def ec(me
, a
, b
): return ECPrimeProjCurve(me
, a
, b
)
452 _augment(PrimeField
, _tmp
)
455 def __repr__(me
): return '%s(%#xL)' %
(_clsname(me
), me
.p
)
456 def ec(me
, a
, b
): return ECBinProjCurve(me
, a
, b
)
457 def _repr_pretty_(me
, pp
, cyclep
):
458 ind
= _pp_bgroup_tyname(pp
, me
)
459 if cyclep
: pp
.text('...')
460 else: pp
.text('%#x' % me
.p
)
461 pp
.end_group(ind
, ')')
462 _augment(BinField
, _tmp
)
465 def __hash__(me
): return 0x23e4701c ^
hash(me
.p
)
466 _augment(BinPolyField
, _tmp
)
472 h ^
= 2*hash(me
.beta
) & 0xffffffff
474 _augment(BinNormField
, _tmp
)
477 def __str__(me
): return str(me
.value
)
478 def __repr__(me
): return '%s(%s)' %
(repr(me
.field
), repr(me
.value
))
479 _repr_pretty_
= _pp_str
482 ###--------------------------------------------------------------------------
487 return '%s(%r, %s, %s)' %
(_clsname(me
), me
.field
, me
.a
, me
.b
)
488 def _repr_pretty_(me
, pp
, cyclep
):
489 ind
= _pp_bgroup_tyname(pp
, me
)
493 pp
.pretty(me
.field
); pp
.text(','); pp
.breakable()
494 pp
.pretty(me
.a
); pp
.text(','); pp
.breakable()
496 pp
.end_group(ind
, ')')
498 return ecpt
.frombuf(me
, s
)
500 return ecpt
.fromraw(me
, s
)
503 _augment(ECCurve
, _tmp
)
509 h ^
= 2*hash(me
.a
) ^
0xffffffff
510 h ^
= 5*hash(me
.b
) ^
0xffffffff
512 _augment(ECPrimeCurve
, _tmp
)
518 h ^
= 2*hash(me
.a
) ^
0xffffffff
519 h ^
= 5*hash(me
.b
) ^
0xffffffff
521 _augment(ECBinCurve
, _tmp
)
525 if not me
: return '%s()' %
_clsname(me
)
526 return '%s(%s, %s)' %
(_clsname(me
), me
.ix
, me
.iy
)
528 if not me
: return 'inf'
529 return '(%s, %s)' %
(me
.ix
, me
.iy
)
530 def _repr_pretty_(me
, pp
, cyclep
):
536 ind
= _pp_bgroup(pp
, '(')
537 pp
.pretty(me
.ix
); pp
.text(','); pp
.breakable()
539 pp
.end_group(ind
, ')')
544 return '%s(curve = %r, G = %r, r = %s, h = %s)' % \
545 (_clsname(me
), me
.curve
, me
.G
, me
.r
, me
.h
)
546 def _repr_pretty_(me
, pp
, cyclep
):
547 ind
= _pp_bgroup_tyname(pp
, me
)
551 _pp_kv(pp
, 'curve', me
.curve
); pp
.text(','); pp
.breakable()
552 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
553 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
554 _pp_kv(pp
, 'h', me
.h
)
555 pp
.end_group(ind
, ')')
559 h ^
= 2*hash(me
.G
) & 0xffffffff
563 _augment(ECInfo
, _tmp
)
567 if not me
: return '%r()' %
(me
.curve
)
568 return '%r(%s, %s)' %
(me
.curve
, me
.x
, me
.y
)
570 if not me
: return 'inf'
571 return '(%s, %s)' %
(me
.x
, me
.y
)
572 def _repr_pretty_(me
, pp
, cyclep
):
578 ind
= _pp_bgroup(pp
, '(')
579 pp
.pretty(me
.x
); pp
.text(','); pp
.breakable()
581 pp
.end_group(ind
, ')')
582 _augment(ECPtCurve
, _tmp
)
584 ###--------------------------------------------------------------------------
588 def __repr__(me
): return '%s(%d)' %
(_clsname(me
), me
.default
)
589 def check(me
, sz
): return True
590 def best(me
, sz
): return sz
591 def pad(me
, sz
): return sz
592 _augment(KeySZAny
, _tmp
)
596 return '%s(%d, %d, %d, %d)' % \
597 (_clsname(me
), me
.default
, me
.min, me
.max, me
.mod
)
598 def _repr_pretty_(me
, pp
, cyclep
):
599 ind
= _pp_bgroup_tyname(pp
, me
)
603 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
604 pp
.pretty(me
.min); pp
.text(','); pp
.breakable()
605 pp
.pretty(me
.max); pp
.text(','); pp
.breakable()
607 pp
.end_group(ind
, ')')
608 def check(me
, sz
): return me
.min <= sz
<= me
.max and sz
%me
.mod
== 0
610 if sz
< me
.min: raise ValueError('key too small')
611 elif sz
> me
.max: return me
.max
612 else: return sz
- sz
%me
.mod
614 if sz
> me
.max: raise ValueError('key too large')
615 elif sz
< me
.min: return me
.min
616 else: sz
+= me
.mod
- 1; return sz
- sz
%me
.mod
617 _augment(KeySZRange
, _tmp
)
620 def __repr__(me
): return '%s(%d, %s)' %
(_clsname(me
), me
.default
, me
.set)
621 def _repr_pretty_(me
, pp
, cyclep
):
622 ind
= _pp_bgroup_tyname(pp
, me
)
626 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
627 ind1
= _pp_bgroup(pp
, '{')
628 _pp_commas(pp
, pp
.pretty
, me
.set)
629 pp
.end_group(ind1
, '}')
630 pp
.end_group(ind
, ')')
631 def check(me
, sz
): return sz
in me
.set
635 if found
< i
<= sz
: found
= i
636 if found
< 0: raise ValueError('key too small')
641 if sz
<= i
and (found
== -1 or i
< found
): found
= i
642 if found
< 0: raise ValueError('key too large')
644 _augment(KeySZSet
, _tmp
)
646 ###--------------------------------------------------------------------------
647 ### Key data objects.
650 def __repr__(me
): return '%s(%r)' %
(_clsname(me
), me
.name
)
651 _augment(KeyFile
, _tmp
)
654 def __repr__(me
): return '%s(%r)' %
(_clsname(me
), me
.fulltag
)
659 return '%s({%s})' %
(_clsname(me
),
660 ', '.join(['%r: %r' % kv
for kv
in me
.iteritems()]))
661 def _repr_pretty_(me
, pp
, cyclep
):
662 ind
= _pp_bgroup_tyname(pp
, me
)
663 if cyclep
: pp
.text('...')
664 else: _pp_dict(pp
, me
.iteritems())
665 pp
.end_group(ind
, ')')
666 _augment(KeyAttributes
, _tmp
)
670 return '%s(%s, %r)' %
(_clsname(me
),
671 _repr_secret(me
._guts(),
672 not (me
.flags
& KF_NONSECRET
)),
673 me
.writeflags(me
.flags
))
674 def _repr_pretty_(me
, pp
, cyclep
):
675 ind
= _pp_bgroup_tyname(pp
, me
)
679 _pp_secret(pp
, me
._guts(), not (me
.flags
& KF_NONSECRET
))
680 pp
.text(','); pp
.breakable()
681 pp
.pretty(me
.writeflags(me
.flags
))
682 pp
.end_group(ind
, ')')
683 _augment(KeyData
, _tmp
)
686 def _guts(me
): return me
.bin
687 _augment(KeyDataBinary
, _tmp
)
690 def _guts(me
): return me
.ct
691 _augment(KeyDataEncrypted
, _tmp
)
694 def _guts(me
): return me
.mp
695 _augment(KeyDataMP
, _tmp
)
698 def _guts(me
): return me
.str
699 _augment(KeyDataString
, _tmp
)
702 def _guts(me
): return me
.ecpt
703 _augment(KeyDataECPt
, _tmp
)
707 return '%s({%s})' %
(_clsname(me
),
708 ', '.join(['%r: %r' % kv
for kv
in me
.iteritems()]))
709 def _repr_pretty_(me
, pp
, cyclep
):
710 ind
= _pp_bgroup_tyname(pp
, me
, '({ ')
711 if cyclep
: pp
.text('...')
712 else: _pp_dict(pp
, me
.iteritems())
713 pp
.end_group(ind
, ' })')
714 _augment(KeyDataStructured
, _tmp
)
716 ###--------------------------------------------------------------------------
721 return '%s(p = %s, r = %s, g = %s)' %
(_clsname(me
), me
.p
, me
.r
, me
.g
)
722 def _repr_pretty_(me
, pp
, cyclep
):
723 ind
= _pp_bgroup_tyname(pp
, me
)
727 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
728 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
729 _pp_kv(pp
, 'g', me
.g
)
730 pp
.end_group(ind
, ')')
731 _augment(FGInfo
, _tmp
)
734 def group(me
): return PrimeGroup(me
)
735 _augment(DHInfo
, _tmp
)
738 def group(me
): return BinGroup(me
)
739 _augment(BinDHInfo
, _tmp
)
743 return '%s(%r)' %
(_clsname(me
), me
.info
)
744 def _repr_pretty_(me
, pp
, cyclep
):
745 ind
= _pp_bgroup_tyname(pp
, me
)
746 if cyclep
: pp
.text('...')
747 else: pp
.pretty(me
.info
)
748 pp
.end_group(ind
, ')')
749 _augment(Group
, _tmp
)
756 h ^
= 2*hash(info
.r
) & 0xffffffff
757 h ^
= 5*hash(info
.g
) & 0xffffffff
759 def _get_geval(me
, x
): return MP(x
)
760 _augment(PrimeGroup
, _tmp
)
767 h ^
= 2*hash(info
.r
) & 0xffffffff
768 h ^
= 5*hash(info
.g
) & 0xffffffff
770 def _get_geval(me
, x
): return GF(x
)
771 _augment(BinGroup
, _tmp
)
774 def __hash__(me
): return 0x0ec23dab ^
hash(me
.info
)
775 def _get_geval(me
, x
): return x
.toec()
776 _augment(ECGroup
, _tmp
)
780 return '%r(%r)' %
(me
.group
, str(me
))
781 def _repr_pretty_(me
, pp
, cyclep
):
782 pp
.pretty(type(me
)._get_geval(me
))
785 ###--------------------------------------------------------------------------
786 ### RSA encoding techniques.
788 class PKCS1Crypt (object):
789 def __init__(me
, ep
= _bin(''), rng
= rand
):
792 def encode(me
, msg
, nbits
):
793 return _base
._p1crypt_encode(msg
, nbits
, me
.ep
, me
.rng
)
794 def decode(me
, ct
, nbits
):
795 return _base
._p1crypt_decode(ct
, nbits
, me
.ep
, me
.rng
)
797 class PKCS1Sig (object):
798 def __init__(me
, ep
= _bin(''), rng
= rand
):
801 def encode(me
, msg
, nbits
):
802 return _base
._p1sig_encode(msg
, nbits
, me
.ep
, me
.rng
)
803 def decode(me
, msg
, sig
, nbits
):
804 return _base
._p1sig_decode(msg
, sig
, nbits
, me
.ep
, me
.rng
)
807 def __init__(me
, mgf
= sha_mgf
, hash = sha
, ep
= _bin(''), rng
= rand
):
812 def encode(me
, msg
, nbits
):
813 return _base
._oaep_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
814 def decode(me
, ct
, nbits
):
815 return _base
._oaep_decode(ct
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
818 def __init__(me
, mgf
= sha_mgf
, hash = sha
, saltsz
= None, rng
= rand
):
825 def encode(me
, msg
, nbits
):
826 return _base
._pss_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
827 def decode(me
, msg
, sig
, nbits
):
828 return _base
._pss_decode(msg
, sig
, nbits
,
829 me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
832 def encrypt(me
, msg
, enc
):
833 return me
.pubop(enc
.encode(msg
, me
.n
.nbits
))
834 def verify(me
, msg
, sig
, enc
):
835 if msg
is None: return enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
837 x
= enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
838 return x
is None or x
== msg
842 return '%s(n = %r, e = %r)' %
(_clsname(me
), me
.n
, me
.e
)
843 def _repr_pretty_(me
, pp
, cyclep
):
844 ind
= _pp_bgroup_tyname(pp
, me
)
848 _pp_kv(pp
, 'n', me
.n
); pp
.text(','); pp
.breakable()
849 _pp_kv(pp
, 'e', me
.e
)
850 pp
.end_group(ind
, ')')
851 _augment(RSAPub
, _tmp
)
854 def decrypt(me
, ct
, enc
): return enc
.decode(me
.privop(ct
), me
.n
.nbits
)
855 def sign(me
, msg
, enc
): return me
.privop(enc
.encode(msg
, me
.n
.nbits
))
857 return '%s(n = %r, e = %r, d = %s, ' \
858 'p = %s, q = %s, dp = %s, dq = %s, q_inv = %s)' % \
859 (_clsname(me
), me
.n
, me
.e
,
860 _repr_secret(me
.d
), _repr_secret(me
.p
), _repr_secret(me
.q
),
861 _repr_secret(me
.dp
), _repr_secret(me
.dq
), _repr_secret(me
.q_inv
))
862 def _repr_pretty_(me
, pp
, cyclep
):
863 ind
= _pp_bgroup_tyname(pp
, me
)
867 _pp_kv(pp
, 'n', me
.n
); pp
.text(','); pp
.breakable()
868 _pp_kv(pp
, 'e', me
.e
); pp
.text(','); pp
.breakable()
869 _pp_kv(pp
, 'd', me
.d
, secretp
= True); pp
.text(','); pp
.breakable()
870 _pp_kv(pp
, 'p', me
.p
, secretp
= True); pp
.text(','); pp
.breakable()
871 _pp_kv(pp
, 'q', me
.q
, secretp
= True); pp
.text(','); pp
.breakable()
872 _pp_kv(pp
, 'dp', me
.dp
, secretp
= True); pp
.text(','); pp
.breakable()
873 _pp_kv(pp
, 'dq', me
.dq
, secretp
= True); pp
.text(','); pp
.breakable()
874 _pp_kv(pp
, 'q_inv', me
.q_inv
, secretp
= True)
875 pp
.end_group(ind
, ')')
876 _augment(RSAPriv
, _tmp
)
878 ###--------------------------------------------------------------------------
879 ### DSA and related schemes.
882 def __repr__(me
): return '%s(G = %r, p = %r, hash = %r)' % \
883 (_clsname(me
), me
.G
, me
.p
, me
.hash)
884 def _repr_pretty_(me
, pp
, cyclep
):
885 ind
= _pp_bgroup_tyname(pp
, me
)
889 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
890 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
891 _pp_kv(pp
, 'hash', me
.hash)
892 pp
.end_group(ind
, ')')
893 _augment(DSAPub
, _tmp
)
894 _augment(KCDSAPub
, _tmp
)
897 def __repr__(me
): return '%s(G = %r, u = %s, p = %r, hash = %r)' % \
898 (_clsname(me
), me
.G
, _repr_secret(me
.u
), me
.p
, me
.hash)
899 def _repr_pretty_(me
, pp
, cyclep
):
900 ind
= _pp_bgroup_tyname(pp
, me
)
904 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
905 _pp_kv(pp
, 'u', me
.u
, True); pp
.text(','); pp
.breakable()
906 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
907 _pp_kv(pp
, 'hash', me
.hash)
908 pp
.end_group(ind
, ')')
909 _augment(DSAPriv
, _tmp
)
910 _augment(KCDSAPriv
, _tmp
)
912 ###--------------------------------------------------------------------------
913 ### Bernstein's elliptic curve crypto and related schemes.
915 X25519_BASE
= MP(9).storel(32)
916 X448_BASE
= MP(5).storel(56)
918 Z128
= ByteString
.zero(16)
920 class _BasePub (object):
921 def __init__(me
, pub
, *args
, **kw
):
922 if not me
._PUBSZ
.check(len(pub
)): raise ValueError('bad public key')
923 super(_BasePub
, me
).__init__(*args
, **kw
)
925 def __repr__(me
): return '%s(pub = %r)' %
(_clsname(me
), me
.pub
)
926 def _pp(me
, pp
): _pp_kv(pp
, 'pub', me
.pub
)
927 def _repr_pretty_(me
, pp
, cyclep
):
928 ind
= _pp_bgroup_tyname(pp
, me
)
929 if cyclep
: pp
.text('...')
931 pp
.end_group(ind
, ')')
933 class _BasePriv (object):
934 def __init__(me
, priv
, pub
= None, *args
, **kw
):
935 if not me
._KEYSZ
.check(len(priv
)): raise ValueError('bad private key')
936 if pub
is None: pub
= me
._pubkey(priv
)
937 super(_BasePriv
, me
).__init__(pub
= pub
, *args
, **kw
)
940 def generate(cls
, rng
= rand
):
941 return cls(rng
.block(cls
._KEYSZ
.default
))
943 return '%s(priv = %d, pub = %r)' % \
944 (_clsname(me
), _repr_secret(me
.priv
), me
.pub
)
946 _pp_kv(pp
, 'priv', me
.priv
, secretp
= True); pp
.text(','); pp
.breakable()
947 super(_BasePriv
, me
)._pp(pp
)
949 class _XDHPub (_BasePub
): pass
951 class _XDHPriv (_BasePriv
):
952 def _pubkey(me
, priv
): return me
._op(priv
, me
._BASE
)
953 def agree(me
, you
): return me
._op(me
.priv
, you
.pub
)
954 def boxkey(me
, recip
): return me
._hashkey(me
.agree(recip
))
955 def box(me
, recip
, n
, m
): return secret_box(me
.boxkey(recip
), n
, m
)
956 def unbox(me
, recip
, n
, c
): return secret_unbox(me
.boxkey(recip
), n
, c
)
958 class X25519Pub (_XDHPub
):
959 _PUBSZ
= KeySZSet(X25519_PUBSZ
)
962 class X25519Priv (_XDHPriv
, X25519Pub
):
963 _KEYSZ
= KeySZSet(X25519_KEYSZ
)
964 def _op(me
, k
, X
): return x25519(k
, X
)
965 def _hashkey(me
, z
): return hsalsa20_prf(z
, Z128
)
967 class X448Pub (_XDHPub
):
968 _PUBSZ
= KeySZSet(X448_PUBSZ
)
971 class X448Priv (_XDHPriv
, X448Pub
):
972 _KEYSZ
= KeySZSet(X448_KEYSZ
)
973 def _op(me
, k
, X
): return x448(k
, X
)
974 def _hashkey(me
, z
): return Shake256().hash(z
).done(salsa20
.keysz
.default
)
976 class _EdDSAPub (_BasePub
):
977 def beginhash(me
): return me
._HASH()
978 def endhash(me
, h
): return h
.done()
980 class _EdDSAPriv (_BasePriv
, _EdDSAPub
):
983 class Ed25519Pub (_EdDSAPub
):
984 _PUBSZ
= KeySZSet(ED25519_PUBSZ
)
986 def verify(me
, msg
, sig
, **kw
):
987 return ed25519_verify(me
.pub
, msg
, sig
, **kw
)
989 class Ed25519Priv (_EdDSAPriv
, Ed25519Pub
):
990 _KEYSZ
= KeySZAny(ED25519_KEYSZ
)
991 def _pubkey(me
, priv
): return ed25519_pubkey(priv
)
992 def sign(me
, msg
, **kw
):
993 return ed25519_sign(me
.priv
, msg
, pub
= me
.pub
, **kw
)
995 class Ed448Pub (_EdDSAPub
):
996 _PUBSZ
= KeySZSet(ED448_PUBSZ
)
998 def verify(me
, msg
, sig
, **kw
):
999 return ed448_verify(me
.pub
, msg
, sig
, **kw
)
1001 class Ed448Priv (_EdDSAPriv
, Ed448Pub
):
1002 _KEYSZ
= KeySZAny(ED448_KEYSZ
)
1003 def _pubkey(me
, priv
): return ed448_pubkey(priv
)
1004 def sign(me
, msg
, **kw
):
1005 return ed448_sign(me
.priv
, msg
, pub
= me
.pub
, **kw
)
1007 ###--------------------------------------------------------------------------
1008 ### Built-in algorithm and group tables.
1012 return '{%s}' %
', '.join(['%r: %r' % kv
for kv
in me
.iteritems()])
1013 def _repr_pretty_(me
, pp
, cyclep
):
1014 ind
= _pp_bgroup(pp
, '{ ')
1015 if cyclep
: pp
.text('...')
1016 else: _pp_dict(pp
, me
.iteritems())
1017 pp
.end_group(ind
, ' }')
1018 _augment(_base
._MiscTable
, _tmp
)
1020 ###--------------------------------------------------------------------------
1021 ### Prime number generation.
1023 class PrimeGenEventHandler (object):
1024 def pg_begin(me
, ev
):
1025 return me
.pg_try(ev
)
1026 def pg_done(me
, ev
):
1028 def pg_abort(me
, ev
):
1030 def pg_fail(me
, ev
):
1032 def pg_pass(me
, ev
):
1035 class SophieGermainStepJump (object):
1036 def pg_begin(me
, ev
):
1037 me
.lf
= PrimeFilter(ev
.x
)
1038 me
.hf
= me
.lf
.muladd(2, 1)
1044 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
1046 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
1049 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
1052 def pg_done(me
, ev
):
1056 class SophieGermainStepper (SophieGermainStepJump
):
1057 def __init__(me
, step
):
1061 me
.lf
.step(me
.lstep
)
1062 me
.hf
.step(me
.hstep
)
1064 class SophieGermainJumper (SophieGermainStepJump
):
1065 def __init__(me
, jump
):
1066 me
.ljump
= PrimeFilter(jump
);
1067 me
.hjump
= me
.ljump
.muladd(2, 0)
1069 me
.lf
.jump(me
.ljump
)
1070 me
.hf
.jump(me
.hjump
)
1071 def pg_done(me
, ev
):
1074 SophieGermainStepJump
.pg_done(me
, ev
)
1076 class SophieGermainTester (object):
1079 def pg_begin(me
, ev
):
1080 me
.lr
= RabinMiller(ev
.x
)
1081 me
.hr
= RabinMiller(2 * ev
.x
+ 1)
1083 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
1084 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
1086 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
1087 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
1089 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
1092 def pg_done(me
, ev
):
1096 class PrimitiveStepper (PrimeGenEventHandler
):
1102 def pg_begin(me
, ev
):
1103 me
.i
= iter(smallprimes
)
1104 return me
.pg_try(ev
)
1106 class PrimitiveTester (PrimeGenEventHandler
):
1107 def __init__(me
, mod
, hh
= [], exp
= None):
1108 me
.mod
= MPMont(mod
)
1113 if me
.exp
is not None:
1114 x
= me
.mod
.exp(x
, me
.exp
)
1115 if x
== 1: return PGEN_FAIL
1117 if me
.mod
.exp(x
, h
) == 1: return PGEN_FAIL
1121 class SimulStepper (PrimeGenEventHandler
):
1122 def __init__(me
, mul
= 2, add
= 1, step
= 2):
1126 def _stepfn(me
, step
):
1128 raise ValueError('step must be positive')
1130 return lambda f
: f
.step(step
)
1131 j
= PrimeFilter(step
)
1132 return lambda f
: f
.jump(j
)
1133 def pg_begin(me
, ev
):
1135 me
.lf
= PrimeFilter(x
)
1136 me
.hf
= PrimeFilter(x
* me
.mul
+ me
.add
)
1137 me
.lstep
= me
._stepfn(me
.step
)
1138 me
.hstep
= me
._stepfn(me
.step
* me
.mul
)
1139 SimulStepper
._cont(me
, ev
)
1147 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
1149 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
1152 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
1155 def pg_done(me
, ev
):
1161 class SimulTester (PrimeGenEventHandler
):
1162 def __init__(me
, mul
= 2, add
= 1):
1165 def pg_begin(me
, ev
):
1167 me
.lr
= RabinMiller(x
)
1168 me
.hr
= RabinMiller(x
* me
.mul
+ me
.add
)
1170 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
1171 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
1173 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
1174 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
1176 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
1179 def pg_done(me
, ev
):
1183 def sgprime(start
, step
= 2, name
= 'p', event
= pgen_nullev
, nsteps
= 0):
1185 return pgen(start
, name
, SimulStepper(step
= step
), SimulTester(), event
,
1186 nsteps
, RabinMiller
.iters(start
.nbits
))
1188 def findprimitive(mod
, hh
= [], exp
= None, name
= 'g', event
= pgen_nullev
):
1189 return pgen(0, name
, PrimitiveStepper(), PrimitiveTester(mod
, hh
, exp
),
1192 def kcdsaprime(pbits
, qbits
, rng
= rand
,
1193 event
= pgen_nullev
, name
= 'p', nsteps
= 0):
1194 hbits
= pbits
- qbits
1195 h
= pgen(rng
.mp(hbits
, 1), name
+ ' [h]',
1196 PrimeGenStepper(2), PrimeGenTester(),
1197 event
, nsteps
, RabinMiller
.iters(hbits
))
1198 q
= pgen(rng
.mp(qbits
, 1), name
, SimulStepper(2 * h
, 1, 2),
1199 SimulTester(2 * h
, 1), event
, nsteps
, RabinMiller
.iters(qbits
))
1203 #----- That's all, folks ----------------------------------------------------