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 ## How to fix a name back into the right identifier. Alas, the rules are not
84 ## Hyphens consistently become underscores.
85 name
= name
.replace('-', '_')
87 ## But slashes might become underscores or just vanish.
88 if name
.startswith('salsa20'): name
= name
.replace('/', '')
89 else: name
= name
.replace('/', '_')
94 ## Initialize the module. Drag in the static methods of the various
95 ## classes; create names for the various known crypto algorithms.
102 for i
in ['ByteString',
104 'ECPt', 'ECPtCurve', 'ECCurve', 'ECInfo',
105 'DHInfo', 'BinDHInfo', 'RSAPriv', 'BBSPriv',
106 'PrimeFilter', 'RabinMiller',
114 setattr(c
, j
[plen
:], classmethod(b
[j
]))
115 for i
in [gcciphers
, gcaeads
, gchashes
, gcmacs
, gcprps
]:
116 for c
in i
.itervalues():
117 d
[_fixname(c
.name
)] = c
118 for c
in gccrands
.itervalues():
119 d
[_fixname(c
.name
+ 'rand')] = c
122 ## A handy function for our work: add the methods of a named class to an
123 ## existing class. This is how we write the Python-implemented parts of our
126 for i
in cc
.__dict__
:
128 if type(a
) is _types
.MethodType
:
130 elif type(a
) not in (_types
.FunctionType
, staticmethod, classmethod):
134 ## Parsing functions tend to return the object parsed and the remainder of
135 ## the input. This checks that the remainder is input and, if so, returns
140 raise SyntaxError, 'junk at end of string'
143 ## Some pretty-printing utilities.
144 PRINT_SECRETS
= False
145 def _clsname(me
): return type(me
).__name__
146 def _repr_secret(thing
, secretp
= True):
147 if not secretp
or PRINT_SECRETS
: return repr(thing
)
148 else: return '#<SECRET>'
149 def _pp_str(me
, pp
, cyclep
): pp
.text(cyclep
and '...' or str(me
))
150 def _pp_secret(pp
, thing
, secretp
= True):
151 if not secretp
or PRINT_SECRETS
: pp
.pretty(thing
)
152 else: pp
.text('#<SECRET>')
153 def _pp_bgroup(pp
, text
):
155 pp
.begin_group(ind
, text
)
157 def _pp_bgroup_tyname(pp
, obj
, open = '('):
158 return _pp_bgroup(pp
, _clsname(obj
) + open)
159 def _pp_kv(pp
, k
, v
, secretp
= False):
160 ind
= _pp_bgroup(pp
, k
+ ' = ')
161 _pp_secret(pp
, v
, secretp
)
162 pp
.end_group(ind
, '')
163 def _pp_commas(pp
, printfn
, items
):
166 if firstp
: firstp
= False
167 else: pp
.text(','); pp
.breakable()
169 def _pp_dict(pp
, items
):
179 _pp_commas(pp
, p
, items
)
181 ###--------------------------------------------------------------------------
186 return ByteString(_unhexify(x
))
187 fromhex
= staticmethod(fromhex
)
191 return 'bytes(%r)' %
hex(me
)
192 _augment(ByteString
, _tmp
)
193 ByteString
.__hash__
= str.__hash__
194 bytes
= ByteString
.fromhex
196 ###--------------------------------------------------------------------------
197 ### Symmetric encryption.
200 def encrypt(me
, n
, m
, tsz
= None, h
= ByteString('')):
201 if tsz
is None: tsz
= me
.__class__
.tagsz
.default
202 e
= me
.enc(n
, len(h
), len(m
), tsz
)
203 if not len(h
): a
= None
204 else: a
= e
.aad().hash(h
)
206 c1
, t
= e
.done(aad
= a
)
208 def decrypt(me
, n
, c
, t
, h
= ByteString('')):
209 d
= me
.dec(n
, len(h
), len(c
), len(t
))
210 if not len(h
): a
= None
211 else: a
= d
.aad().hash(h
)
213 m
+= d
.done(t
, aad
= a
)
215 _augment(GAEKey
, _tmp
)
217 ###--------------------------------------------------------------------------
223 return ctstreq(h
, hh
)
224 _augment(GHash
, _tmp
)
225 _augment(Poly1305Hash
, _tmp
)
227 class _HashBase (object):
228 ## The standard hash methods. Assume that `hash' is defined and returns
230 def _check_range(me
, n
, max):
231 if not (0 <= n
<= max): raise OverflowError("out of range")
233 me
._check_range(n
, 0xff)
234 return me
.hash(_pack('B', n
))
236 me
._check_range(n
, 0xffff)
237 return me
.hash(_pack('<H', n
))
239 me
._check_range(n
, 0xffff)
240 return me
.hash(_pack('>H', n
))
243 me
._check_range(n
, 0xffffffff)
244 return me
.hash(_pack('<L', n
))
246 me
._check_range(n
, 0xffffffff)
247 return me
.hash(_pack('>L', n
))
250 me
._check_range(n
, 0xffffffffffffffff)
251 return me
.hash(_pack('<Q', n
))
253 me
._check_range(n
, 0xffffffffffffffff)
254 return me
.hash(_pack('>Q', n
))
256 def hashbuf8(me
, s
): return me
.hashu8(len(s
)).hash(s
)
257 def hashbuf16l(me
, s
): return me
.hashu16l(len(s
)).hash(s
)
258 def hashbuf16b(me
, s
): return me
.hashu16b(len(s
)).hash(s
)
259 hashbuf16
= hashbuf16b
260 def hashbuf32l(me
, s
): return me
.hashu32l(len(s
)).hash(s
)
261 def hashbuf32b(me
, s
): return me
.hashu32b(len(s
)).hash(s
)
262 hashbuf32
= hashbuf32b
263 def hashbuf64l(me
, s
): return me
.hashu64l(len(s
)).hash(s
)
264 def hashbuf64b(me
, s
): return me
.hashu64b(len(s
)).hash(s
)
265 hashbuf64
= hashbuf64b
266 def hashstrz(me
, s
): return me
.hash(s
).hashu8(0)
268 class _ShakeBase (_HashBase
):
270 ## Python gets really confused if I try to augment `__new__' on native
271 ## classes, so wrap and delegate. Sorry.
272 def __init__(me
, perso
= '', *args
, **kw
):
273 super(_ShakeBase
, me
).__init__(*args
, **kw
)
274 me
._h
= me
._SHAKE(perso
= perso
, func
= me
._FUNC
)
276 ## Delegate methods...
277 def copy(me
): new
= me
.__class__
._bare_new(); new
._copy(me
); return new
278 def _copy(me
, other
): me
._h
= other
._h
.copy()
279 def hash(me
, m
): me
._h
.hash(m
); return me
280 def xof(me
): me
._h
.xof(); return me
281 def get(me
, n
): return me
._h
.get(n
)
282 def mask(me
, m
): return me
._h
.mask(m
)
283 def done(me
, n
): return me
._h
.done(n
)
284 def check(me
, h
): return ctstreq(h
, me
.done(len(h
)))
286 def state(me
): return me
._h
.state
288 def buffered(me
): return me
._h
.buffered
290 def rate(me
): return me
._h
.rate
292 def _bare_new(cls
): return cls()
296 return ctstreq(h
, me
.done(len(h
)))
299 return me
.hashu8(len(nn
)).hash(nn
)
302 return me
.hash(nn
).hashu8(len(nn
))
303 def stringenc(me
, str):
304 return me
.leftenc(8*len(str)).hash(str)
305 def bytepad_before(me
):
306 return me
.leftenc(me
.rate
)
307 def bytepad_after(me
):
308 if me
.buffered
: me
.hash(me
._Z
[:me
.rate
- me
.buffered
])
315 _augment(Shake
, _tmp
)
316 _augment(_ShakeBase
, _tmp
)
317 Shake
._Z
= _ShakeBase
._Z
= ByteString
.zero(200)
319 class KMAC (_ShakeBase
):
321 def __init__(me
, k
, *arg
, **kw
):
322 super(KMAC
, me
).__init__(*arg
, **kw
)
323 with me
.bytepad(): me
.stringenc(k
)
324 def done(me
, n
= -1):
325 if n
< 0: n
= me
._TAGSZ
327 return super(KMAC
, me
).done(n
)
330 return super(KMAC
, me
).xof()
332 def _bare_new(cls
): return cls("")
334 class KMAC128 (KMAC
): _SHAKE
= Shake128
; _TAGSZ
= 16
335 class KMAC256 (KMAC
): _SHAKE
= Shake256
; _TAGSZ
= 32
337 ###--------------------------------------------------------------------------
338 ### NaCl `secretbox'.
340 def secret_box(k
, n
, m
):
341 y
, t
= salsa20_naclbox(k
).encrypt(n
, m
)
344 def secret_unbox(k
, n
, c
):
346 return salsa20_naclbox(k
).decrypt(n
, c
[tsz
:], c
[0:tsz
])
348 ###--------------------------------------------------------------------------
349 ### Multiprecision integers and binary polynomials.
352 if isinstance(x
, BaseRat
): return x
._n
, x
._d
354 class BaseRat (object):
355 """Base class implementing fields of fractions over Euclidean domains."""
356 def __new__(cls
, a
, b
):
357 a
, b
= cls
.RING(a
), cls
.RING(b
)
361 me
= super(BaseRat
, cls
).__new__(cls
)
366 def numer(me
): return me
._n
368 def denom(me
): return me
._d
369 def __str__(me
): return '%s/%s' %
(me
._n
, me
._d
)
370 def __repr__(me
): return '%s(%s, %s)' %
(_clsname(me
), me
._n
, me
._d
)
371 _repr_pretty_
= _pp_str
373 def __add__(me
, you
):
374 n
, d
= _split_rat(you
)
375 return type(me
)(me
._n
*d
+ n
*me
._d
, d
*me
._d
)
377 def __sub__(me
, you
):
378 n
, d
= _split_rat(you
)
379 return type(me
)(me
._n
*d
- n
*me
._d
, d
*me
._d
)
380 def __rsub__(me
, you
):
381 n
, d
= _split_rat(you
)
382 return type(me
)(n
*me
._d
- me
._n
*d
, d
*me
._d
)
383 def __mul__(me
, you
):
384 n
, d
= _split_rat(you
)
385 return type(me
)(me
._n
*n
, me
._d
*d
)
387 def __truediv__(me
, you
):
388 n
, d
= _split_rat(you
)
389 return type(me
)(me
._n
*d
, me
._d
*n
)
390 def __rtruediv__(me
, you
):
391 n
, d
= _split_rat(you
)
392 return type(me
)(me
._d
*n
, me
._n
*d
)
393 __div__
= __truediv__
394 __rdiv__
= __rtruediv__
395 def __cmp__(me
, you
):
396 n
, d
= _split_rat(you
)
397 return cmp(me
._n
*d
, n
*me
._d
)
398 def __rcmp__(me
, you
):
399 n
, d
= _split_rat(you
)
400 return cmp(n
*me
._d
, me
._n
*d
)
402 class IntRat (BaseRat
):
405 class GFRat (BaseRat
):
409 def negp(x
): return x
< 0
410 def posp(x
): return x
> 0
411 def zerop(x
): return x
== 0
412 def oddp(x
): return x
.testbit(0)
413 def evenp(x
): return not x
.testbit(0)
414 def mont(x
): return MPMont(x
)
415 def barrett(x
): return MPBarrett(x
)
416 def reduce(x
): return MPReduce(x
)
417 def __truediv__(me
, you
): return IntRat(me
, you
)
418 def __rtruediv__(me
, you
): return IntRat(you
, me
)
419 __div__
= __truediv__
420 __rdiv__
= __rtruediv__
421 _repr_pretty_
= _pp_str
425 def zerop(x
): return x
== 0
426 def reduce(x
): return GFReduce(x
)
427 def trace(x
, y
): return x
.reduce().trace(y
)
428 def halftrace(x
, y
): return x
.reduce().halftrace(y
)
429 def modsqrt(x
, y
): return x
.reduce().sqrt(y
)
430 def quadsolve(x
, y
): return x
.reduce().quadsolve(y
)
431 def __truediv__(me
, you
): return GFRat(me
, you
)
432 def __rtruediv__(me
, you
): return GFRat(you
, me
)
433 __div__
= __truediv__
434 __rdiv__
= __rtruediv__
435 _repr_pretty_
= _pp_str
440 'product(ITERABLE) or product(I, ...) -> PRODUCT'
441 return MPMul(*arg
).done()
442 product
= staticmethod(product
)
443 _augment(MPMul
, _tmp
)
445 ###--------------------------------------------------------------------------
449 def fromstring(str): return _checkend(Field
.parse(str))
450 fromstring
= staticmethod(fromstring
)
451 _augment(Field
, _tmp
)
454 def __repr__(me
): return '%s(%sL)' %
(_clsname(me
), me
.p
)
455 def __hash__(me
): return 0x114401de ^
hash(me
.p
)
456 def _repr_pretty_(me
, pp
, cyclep
):
457 ind
= _pp_bgroup_tyname(pp
, me
)
458 if cyclep
: pp
.text('...')
459 else: pp
.pretty(me
.p
)
460 pp
.end_group(ind
, ')')
461 def ec(me
, a
, b
): return ECPrimeProjCurve(me
, a
, b
)
462 _augment(PrimeField
, _tmp
)
465 def __repr__(me
): return '%s(%#xL)' %
(_clsname(me
), me
.p
)
466 def ec(me
, a
, b
): return ECBinProjCurve(me
, a
, b
)
467 def _repr_pretty_(me
, pp
, cyclep
):
468 ind
= _pp_bgroup_tyname(pp
, me
)
469 if cyclep
: pp
.text('...')
470 else: pp
.text('%#x' % me
.p
)
471 pp
.end_group(ind
, ')')
472 _augment(BinField
, _tmp
)
475 def __hash__(me
): return 0x23e4701c ^
hash(me
.p
)
476 _augment(BinPolyField
, _tmp
)
482 h ^
= 2*hash(me
.beta
) & 0xffffffff
484 _augment(BinNormField
, _tmp
)
487 def __str__(me
): return str(me
.value
)
488 def __repr__(me
): return '%s(%s)' %
(repr(me
.field
), repr(me
.value
))
489 _repr_pretty_
= _pp_str
492 ###--------------------------------------------------------------------------
497 return '%s(%r, %s, %s)' %
(_clsname(me
), me
.field
, me
.a
, me
.b
)
498 def _repr_pretty_(me
, pp
, cyclep
):
499 ind
= _pp_bgroup_tyname(pp
, me
)
503 pp
.pretty(me
.field
); pp
.text(','); pp
.breakable()
504 pp
.pretty(me
.a
); pp
.text(','); pp
.breakable()
506 pp
.end_group(ind
, ')')
508 return ecpt
.frombuf(me
, s
)
510 return ecpt
.fromraw(me
, s
)
513 _augment(ECCurve
, _tmp
)
519 h ^
= 2*hash(me
.a
) ^
0xffffffff
520 h ^
= 5*hash(me
.b
) ^
0xffffffff
522 _augment(ECPrimeCurve
, _tmp
)
528 h ^
= 2*hash(me
.a
) ^
0xffffffff
529 h ^
= 5*hash(me
.b
) ^
0xffffffff
531 _augment(ECBinCurve
, _tmp
)
535 if not me
: return '%s()' %
_clsname(me
)
536 return '%s(%s, %s)' %
(_clsname(me
), me
.ix
, me
.iy
)
538 if not me
: return 'inf'
539 return '(%s, %s)' %
(me
.ix
, me
.iy
)
540 def _repr_pretty_(me
, pp
, cyclep
):
546 ind
= _pp_bgroup(pp
, '(')
547 pp
.pretty(me
.ix
); pp
.text(','); pp
.breakable()
549 pp
.end_group(ind
, ')')
554 return '%s(curve = %r, G = %r, r = %s, h = %s)' % \
555 (_clsname(me
), me
.curve
, me
.G
, me
.r
, me
.h
)
556 def _repr_pretty_(me
, pp
, cyclep
):
557 ind
= _pp_bgroup_tyname(pp
, me
)
561 _pp_kv(pp
, 'curve', me
.curve
); pp
.text(','); pp
.breakable()
562 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
563 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
564 _pp_kv(pp
, 'h', me
.h
)
565 pp
.end_group(ind
, ')')
569 h ^
= 2*hash(me
.G
) & 0xffffffff
573 _augment(ECInfo
, _tmp
)
577 if not me
: return '%r()' %
(me
.curve
)
578 return '%r(%s, %s)' %
(me
.curve
, me
.x
, me
.y
)
580 if not me
: return 'inf'
581 return '(%s, %s)' %
(me
.x
, me
.y
)
582 def _repr_pretty_(me
, pp
, cyclep
):
588 ind
= _pp_bgroup(pp
, '(')
589 pp
.pretty(me
.x
); pp
.text(','); pp
.breakable()
591 pp
.end_group(ind
, ')')
592 _augment(ECPtCurve
, _tmp
)
594 ###--------------------------------------------------------------------------
598 def __repr__(me
): return '%s(%d)' %
(_clsname(me
), me
.default
)
599 def check(me
, sz
): return True
600 def best(me
, sz
): return sz
601 def pad(me
, sz
): return sz
602 _augment(KeySZAny
, _tmp
)
606 return '%s(%d, %d, %d, %d)' % \
607 (_clsname(me
), me
.default
, me
.min, me
.max, me
.mod
)
608 def _repr_pretty_(me
, pp
, cyclep
):
609 ind
= _pp_bgroup_tyname(pp
, me
)
613 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
614 pp
.pretty(me
.min); pp
.text(','); pp
.breakable()
615 pp
.pretty(me
.max); pp
.text(','); pp
.breakable()
617 pp
.end_group(ind
, ')')
618 def check(me
, sz
): return me
.min <= sz
<= me
.max and sz
%me
.mod
== 0
620 if sz
< me
.min: raise ValueError, 'key too small'
621 elif sz
> me
.max: return me
.max
622 else: return sz
- sz
%me
.mod
624 if sz
> me
.max: raise ValueError, 'key too large'
625 elif sz
< me
.min: return me
.min
626 else: sz
+= me
.mod
- 1; return sz
- sz
%me
.mod
627 _augment(KeySZRange
, _tmp
)
630 def __repr__(me
): return '%s(%d, %s)' %
(_clsname(me
), me
.default
, me
.set)
631 def _repr_pretty_(me
, pp
, cyclep
):
632 ind
= _pp_bgroup_tyname(pp
, me
)
636 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
637 ind1
= _pp_bgroup(pp
, '{')
638 _pp_commas(pp
, pp
.pretty
, me
.set)
639 pp
.end_group(ind1
, '}')
640 pp
.end_group(ind
, ')')
641 def check(me
, sz
): return sz
in me
.set
645 if found
< i
<= sz
: found
= i
646 if found
< 0: raise ValueError, 'key too small'
651 if sz
<= i
and (found
== -1 or i
< found
): found
= i
652 if found
< 0: raise ValueError, 'key too large'
654 _augment(KeySZSet
, _tmp
)
656 ###--------------------------------------------------------------------------
657 ### Key data objects.
660 def __repr__(me
): return '%s(%r)' %
(_clsname(me
), me
.name
)
661 _augment(KeyFile
, _tmp
)
664 def __repr__(me
): return '%s(%r)' %
(_clsname(me
), me
.fulltag
)
669 return '%s({%s})' %
(_clsname(me
),
670 ', '.join(['%r: %r' % kv
for kv
in me
.iteritems()]))
671 def _repr_pretty_(me
, pp
, cyclep
):
672 ind
= _pp_bgroup_tyname(pp
, me
)
673 if cyclep
: pp
.text('...')
674 else: _pp_dict(pp
, me
.iteritems())
675 pp
.end_group(ind
, ')')
676 _augment(KeyAttributes
, _tmp
)
680 return '%s(%s, %r)' %
(_clsname(me
),
681 _repr_secret(me
._guts(),
682 not (me
.flags
& KF_NONSECRET
)),
683 me
.writeflags(me
.flags
))
684 def _repr_pretty_(me
, pp
, cyclep
):
685 ind
= _pp_bgroup_tyname(pp
, me
)
689 _pp_secret(pp
, me
._guts(), not (me
.flags
& KF_NONSECRET
))
690 pp
.text(','); pp
.breakable()
691 pp
.pretty(me
.writeflags(me
.flags
))
692 pp
.end_group(ind
, ')')
693 _augment(KeyData
, _tmp
)
696 def _guts(me
): return me
.bin
697 _augment(KeyDataBinary
, _tmp
)
700 def _guts(me
): return me
.ct
701 _augment(KeyDataEncrypted
, _tmp
)
704 def _guts(me
): return me
.mp
705 _augment(KeyDataMP
, _tmp
)
708 def _guts(me
): return me
.str
709 _augment(KeyDataString
, _tmp
)
712 def _guts(me
): return me
.ecpt
713 _augment(KeyDataECPt
, _tmp
)
717 return '%s({%s})' %
(_clsname(me
),
718 ', '.join(['%r: %r' % kv
for kv
in me
.iteritems()]))
719 def _repr_pretty_(me
, pp
, cyclep
):
720 ind
= _pp_bgroup_tyname(pp
, me
, '({ ')
721 if cyclep
: pp
.text('...')
722 else: _pp_dict(pp
, me
.iteritems())
723 pp
.end_group(ind
, ' })')
724 _augment(KeyDataStructured
, _tmp
)
726 ###--------------------------------------------------------------------------
731 return '%s(p = %s, r = %s, g = %s)' %
(_clsname(me
), me
.p
, me
.r
, me
.g
)
732 def _repr_pretty_(me
, pp
, cyclep
):
733 ind
= _pp_bgroup_tyname(pp
, me
)
737 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
738 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
739 _pp_kv(pp
, 'g', me
.g
)
740 pp
.end_group(ind
, ')')
741 _augment(FGInfo
, _tmp
)
744 def group(me
): return PrimeGroup(me
)
745 _augment(DHInfo
, _tmp
)
748 def group(me
): return BinGroup(me
)
749 _augment(BinDHInfo
, _tmp
)
753 return '%s(%r)' %
(_clsname(me
), me
.info
)
754 def _repr_pretty_(me
, pp
, cyclep
):
755 ind
= _pp_bgroup_tyname(pp
, me
)
756 if cyclep
: pp
.text('...')
757 else: pp
.pretty(me
.info
)
758 pp
.end_group(ind
, ')')
759 _augment(Group
, _tmp
)
766 h ^
= 2*hash(info
.r
) & 0xffffffff
767 h ^
= 5*hash(info
.g
) & 0xffffffff
769 def _get_geval(me
, x
): return MP(x
)
770 _augment(PrimeGroup
, _tmp
)
777 h ^
= 2*hash(info
.r
) & 0xffffffff
778 h ^
= 5*hash(info
.g
) & 0xffffffff
780 def _get_geval(me
, x
): return GF(x
)
781 _augment(BinGroup
, _tmp
)
784 def __hash__(me
): return 0x0ec23dab ^
hash(me
.info
)
785 def _get_geval(me
, x
): return x
.toec()
786 _augment(ECGroup
, _tmp
)
790 return '%r(%r)' %
(me
.group
, str(me
))
791 def _repr_pretty_(me
, pp
, cyclep
):
792 pp
.pretty(type(me
)._get_geval(me
))
795 ###--------------------------------------------------------------------------
796 ### RSA encoding techniques.
798 class PKCS1Crypt (object):
799 def __init__(me
, ep
= '', rng
= rand
):
802 def encode(me
, msg
, nbits
):
803 return _base
._p1crypt_encode(msg
, nbits
, me
.ep
, me
.rng
)
804 def decode(me
, ct
, nbits
):
805 return _base
._p1crypt_decode(ct
, nbits
, me
.ep
, me
.rng
)
807 class PKCS1Sig (object):
808 def __init__(me
, ep
= '', rng
= rand
):
811 def encode(me
, msg
, nbits
):
812 return _base
._p1sig_encode(msg
, nbits
, me
.ep
, me
.rng
)
813 def decode(me
, msg
, sig
, nbits
):
814 return _base
._p1sig_decode(msg
, sig
, nbits
, me
.ep
, me
.rng
)
817 def __init__(me
, mgf
= sha_mgf
, hash = sha
, ep
= '', rng
= rand
):
822 def encode(me
, msg
, nbits
):
823 return _base
._oaep_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
824 def decode(me
, ct
, nbits
):
825 return _base
._oaep_decode(ct
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
828 def __init__(me
, mgf
= sha_mgf
, hash = sha
, saltsz
= None, rng
= rand
):
835 def encode(me
, msg
, nbits
):
836 return _base
._pss_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
837 def decode(me
, msg
, sig
, nbits
):
838 return _base
._pss_decode(msg
, sig
, nbits
,
839 me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
842 def encrypt(me
, msg
, enc
):
843 return me
.pubop(enc
.encode(msg
, me
.n
.nbits
))
844 def verify(me
, msg
, sig
, enc
):
845 if msg
is None: return enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
847 x
= enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
848 return x
is None or x
== msg
852 return '%s(n = %r, e = %r)' %
(_clsname(me
), me
.n
, me
.e
)
853 def _repr_pretty_(me
, pp
, cyclep
):
854 ind
= _pp_bgroup_tyname(pp
, me
)
858 _pp_kv(pp
, 'n', me
.n
); pp
.text(','); pp
.breakable()
859 _pp_kv(pp
, 'e', me
.e
)
860 pp
.end_group(ind
, ')')
861 _augment(RSAPub
, _tmp
)
864 def decrypt(me
, ct
, enc
): return enc
.decode(me
.privop(ct
), me
.n
.nbits
)
865 def sign(me
, msg
, enc
): return me
.privop(enc
.encode(msg
, me
.n
.nbits
))
867 return '%s(n = %r, e = %r, d = %s, ' \
868 'p = %s, q = %s, dp = %s, dq = %s, q_inv = %s)' % \
869 (_clsname(me
), me
.n
, me
.e
,
870 _repr_secret(me
.d
), _repr_secret(me
.p
), _repr_secret(me
.q
),
871 _repr_secret(me
.dp
), _repr_secret(me
.dq
), _repr_secret(me
.q_inv
))
872 def _repr_pretty_(me
, pp
, cyclep
):
873 ind
= _pp_bgroup_tyname(pp
, me
)
877 _pp_kv(pp
, 'n', me
.n
); pp
.text(','); pp
.breakable()
878 _pp_kv(pp
, 'e', me
.e
); pp
.text(','); pp
.breakable()
879 _pp_kv(pp
, 'd', me
.d
, secretp
= True); pp
.text(','); pp
.breakable()
880 _pp_kv(pp
, 'p', me
.p
, secretp
= True); pp
.text(','); pp
.breakable()
881 _pp_kv(pp
, 'q', me
.q
, secretp
= True); pp
.text(','); pp
.breakable()
882 _pp_kv(pp
, 'dp', me
.dp
, secretp
= True); pp
.text(','); pp
.breakable()
883 _pp_kv(pp
, 'dq', me
.dq
, secretp
= True); pp
.text(','); pp
.breakable()
884 _pp_kv(pp
, 'q_inv', me
.q_inv
, secretp
= True)
885 pp
.end_group(ind
, ')')
886 _augment(RSAPriv
, _tmp
)
888 ###--------------------------------------------------------------------------
889 ### DSA and related schemes.
892 def __repr__(me
): return '%s(G = %r, p = %r, hash = %r)' % \
893 (_clsname(me
), me
.G
, 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
, 'p', me
.p
); pp
.text(','); pp
.breakable()
901 _pp_kv(pp
, 'hash', me
.hash)
902 pp
.end_group(ind
, ')')
903 _augment(DSAPub
, _tmp
)
904 _augment(KCDSAPub
, _tmp
)
907 def __repr__(me
): return '%s(G = %r, u = %s, p = %r, hash = %r)' % \
908 (_clsname(me
), me
.G
, _repr_secret(me
.u
), me
.p
, me
.hash)
909 def _repr_pretty_(me
, pp
, cyclep
):
910 ind
= _pp_bgroup_tyname(pp
, me
)
914 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
915 _pp_kv(pp
, 'u', me
.u
, True); pp
.text(','); pp
.breakable()
916 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
917 _pp_kv(pp
, 'hash', me
.hash)
918 pp
.end_group(ind
, ')')
919 _augment(DSAPriv
, _tmp
)
920 _augment(KCDSAPriv
, _tmp
)
922 ###--------------------------------------------------------------------------
923 ### Bernstein's elliptic curve crypto and related schemes.
925 X25519_BASE
= MP(9).storel(32)
926 X448_BASE
= MP(5).storel(56)
928 Z128
= ByteString
.zero(16)
930 class _BasePub (object):
931 def __init__(me
, pub
, *args
, **kw
):
932 if not me
._PUBSZ
.check(len(pub
)): raise ValueError, 'bad public key'
933 super(_BasePub
, me
).__init__(*args
, **kw
)
935 def __repr__(me
): return '%s(pub = %r)' %
(_clsname(me
), me
.pub
)
936 def _pp(me
, pp
): _pp_kv(pp
, 'pub', me
.pub
)
937 def _repr_pretty_(me
, pp
, cyclep
):
938 ind
= _pp_bgroup_tyname(pp
, me
)
939 if cyclep
: pp
.text('...')
941 pp
.end_group(ind
, ')')
943 class _BasePriv (object):
944 def __init__(me
, priv
, pub
= None, *args
, **kw
):
945 if not me
._KEYSZ
.check(len(priv
)): raise ValueError, 'bad private key'
946 if pub
is None: pub
= me
._pubkey(priv
)
947 super(_BasePriv
, me
).__init__(pub
= pub
, *args
, **kw
)
950 def generate(cls
, rng
= rand
):
951 return cls(rng
.block(cls
._KEYSZ
.default
))
953 return '%s(priv = %d, pub = %r)' % \
954 (_clsname(me
), _repr_secret(me
.priv
), me
.pub
)
956 _pp_kv(pp
, 'priv', me
.priv
, secretp
= True); pp
.text(','); pp
.breakable()
957 super(_BasePriv
, me
)._pp(pp
)
959 class _XDHPub (_BasePub
): pass
961 class _XDHPriv (_BasePriv
):
962 def _pubkey(me
, priv
): return me
._op(priv
, me
._BASE
)
963 def agree(me
, you
): return me
._op(me
.priv
, you
.pub
)
964 def boxkey(me
, recip
): return me
._hashkey(me
.agree(recip
))
965 def box(me
, recip
, n
, m
): return secret_box(me
.boxkey(recip
), n
, m
)
966 def unbox(me
, recip
, n
, c
): return secret_unbox(me
.boxkey(recip
), n
, c
)
968 class X25519Pub (_XDHPub
):
969 _PUBSZ
= KeySZSet(X25519_PUBSZ
)
972 class X25519Priv (_XDHPriv
, X25519Pub
):
973 _KEYSZ
= KeySZSet(X25519_KEYSZ
)
974 def _op(me
, k
, X
): return x25519(k
, X
)
975 def _hashkey(me
, z
): return hsalsa20_prf(z
, Z128
)
977 class X448Pub (_XDHPub
):
978 _PUBSZ
= KeySZSet(X448_PUBSZ
)
981 class X448Priv (_XDHPriv
, X448Pub
):
982 _KEYSZ
= KeySZSet(X448_KEYSZ
)
983 def _op(me
, k
, X
): return x448(k
, X
)
984 def _hashkey(me
, z
): return Shake256().hash(z
).done(salsa20
.keysz
.default
)
986 class _EdDSAPub (_BasePub
):
987 def beginhash(me
): return me
._HASH()
988 def endhash(me
, h
): return h
.done()
990 class _EdDSAPriv (_BasePriv
, _EdDSAPub
):
993 class Ed25519Pub (_EdDSAPub
):
994 _PUBSZ
= KeySZSet(ED25519_PUBSZ
)
996 def verify(me
, msg
, sig
, **kw
):
997 return ed25519_verify(me
.pub
, msg
, sig
, **kw
)
999 class Ed25519Priv (_EdDSAPriv
, Ed25519Pub
):
1000 _KEYSZ
= KeySZAny(ED25519_KEYSZ
)
1001 def _pubkey(me
, priv
): return ed25519_pubkey(priv
)
1002 def sign(me
, msg
, **kw
):
1003 return ed25519_sign(me
.priv
, msg
, pub
= me
.pub
, **kw
)
1005 class Ed448Pub (_EdDSAPub
):
1006 _PUBSZ
= KeySZSet(ED448_PUBSZ
)
1008 def verify(me
, msg
, sig
, **kw
):
1009 return ed448_verify(me
.pub
, msg
, sig
, **kw
)
1011 class Ed448Priv (_EdDSAPriv
, Ed448Pub
):
1012 _KEYSZ
= KeySZAny(ED448_KEYSZ
)
1013 def _pubkey(me
, priv
): return ed448_pubkey(priv
)
1014 def sign(me
, msg
, **kw
):
1015 return ed448_sign(me
.priv
, msg
, pub
= me
.pub
, **kw
)
1017 ###--------------------------------------------------------------------------
1018 ### Built-in named curves and prime groups.
1020 class _groupmap (object):
1021 def __init__(me
, map, nth
):
1024 me
._n
= max(map.values()) + 1
1027 return '{%s}' %
', '.join(['%r: %r' % kv
for kv
in me
.iteritems()])
1028 def _repr_pretty_(me
, pp
, cyclep
):
1029 ind
= _pp_bgroup(pp
, '{ ')
1030 if cyclep
: pp
.text('...')
1031 else: _pp_dict(pp
, me
.iteritems())
1032 pp
.end_group(ind
, ' }')
1035 def __contains__(me
, k
):
1037 def __getitem__(me
, k
):
1042 def __setitem__(me
, k
, v
):
1043 raise TypeError, "immutable object"
1055 return [k
for k
in me
]
1057 return [me
[k
] for k
in me
]
1059 return [(k
, me
[k
]) for k
in me
]
1060 eccurves
= _groupmap(_base
._eccurves
, ECInfo
._curven
)
1061 primegroups
= _groupmap(_base
._pgroups
, DHInfo
._groupn
)
1062 bingroups
= _groupmap(_base
._bingroups
, BinDHInfo
._groupn
)
1064 ###--------------------------------------------------------------------------
1065 ### Prime number generation.
1067 class PrimeGenEventHandler (object):
1068 def pg_begin(me
, ev
):
1069 return me
.pg_try(ev
)
1070 def pg_done(me
, ev
):
1072 def pg_abort(me
, ev
):
1074 def pg_fail(me
, ev
):
1076 def pg_pass(me
, ev
):
1079 class SophieGermainStepJump (object):
1080 def pg_begin(me
, ev
):
1081 me
.lf
= PrimeFilter(ev
.x
)
1082 me
.hf
= me
.lf
.muladd(2, 1)
1088 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
1090 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
1093 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
1096 def pg_done(me
, ev
):
1100 class SophieGermainStepper (SophieGermainStepJump
):
1101 def __init__(me
, step
):
1105 me
.lf
.step(me
.lstep
)
1106 me
.hf
.step(me
.hstep
)
1108 class SophieGermainJumper (SophieGermainStepJump
):
1109 def __init__(me
, jump
):
1110 me
.ljump
= PrimeFilter(jump
);
1111 me
.hjump
= me
.ljump
.muladd(2, 0)
1113 me
.lf
.jump(me
.ljump
)
1114 me
.hf
.jump(me
.hjump
)
1115 def pg_done(me
, ev
):
1118 SophieGermainStepJump
.pg_done(me
, ev
)
1120 class SophieGermainTester (object):
1123 def pg_begin(me
, ev
):
1124 me
.lr
= RabinMiller(ev
.x
)
1125 me
.hr
= RabinMiller(2 * ev
.x
+ 1)
1127 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
1128 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
1130 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
1131 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
1133 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
1136 def pg_done(me
, ev
):
1140 class PrimitiveStepper (PrimeGenEventHandler
):
1146 def pg_begin(me
, ev
):
1147 me
.i
= iter(smallprimes
)
1148 return me
.pg_try(ev
)
1150 class PrimitiveTester (PrimeGenEventHandler
):
1151 def __init__(me
, mod
, hh
= [], exp
= None):
1152 me
.mod
= MPMont(mod
)
1157 if me
.exp
is not None:
1158 x
= me
.mod
.exp(x
, me
.exp
)
1159 if x
== 1: return PGEN_FAIL
1161 if me
.mod
.exp(x
, h
) == 1: return PGEN_FAIL
1165 class SimulStepper (PrimeGenEventHandler
):
1166 def __init__(me
, mul
= 2, add
= 1, step
= 2):
1170 def _stepfn(me
, step
):
1172 raise ValueError, 'step must be positive'
1174 return lambda f
: f
.step(step
)
1175 j
= PrimeFilter(step
)
1176 return lambda f
: f
.jump(j
)
1177 def pg_begin(me
, ev
):
1179 me
.lf
= PrimeFilter(x
)
1180 me
.hf
= PrimeFilter(x
* me
.mul
+ me
.add
)
1181 me
.lstep
= me
._stepfn(me
.step
)
1182 me
.hstep
= me
._stepfn(me
.step
* me
.mul
)
1183 SimulStepper
._cont(me
, ev
)
1191 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
1193 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
1196 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
1199 def pg_done(me
, ev
):
1205 class SimulTester (PrimeGenEventHandler
):
1206 def __init__(me
, mul
= 2, add
= 1):
1209 def pg_begin(me
, ev
):
1211 me
.lr
= RabinMiller(x
)
1212 me
.hr
= RabinMiller(x
* me
.mul
+ me
.add
)
1214 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
1215 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
1217 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
1218 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
1220 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
1223 def pg_done(me
, ev
):
1227 def sgprime(start
, step
= 2, name
= 'p', event
= pgen_nullev
, nsteps
= 0):
1229 return pgen(start
, name
, SimulStepper(step
= step
), SimulTester(), event
,
1230 nsteps
, RabinMiller
.iters(start
.nbits
))
1232 def findprimitive(mod
, hh
= [], exp
= None, name
= 'g', event
= pgen_nullev
):
1233 return pgen(0, name
, PrimitiveStepper(), PrimitiveTester(mod
, hh
, exp
),
1236 def kcdsaprime(pbits
, qbits
, rng
= rand
,
1237 event
= pgen_nullev
, name
= 'p', nsteps
= 0):
1238 hbits
= pbits
- qbits
1239 h
= pgen(rng
.mp(hbits
, 1), name
+ ' [h]',
1240 PrimeGenStepper(2), PrimeGenTester(),
1241 event
, nsteps
, RabinMiller
.iters(hbits
))
1242 q
= pgen(rng
.mp(qbits
, 1), name
, SimulStepper(2 * h
, 1, 2),
1243 SimulTester(2 * h
, 1), event
, nsteps
, RabinMiller
.iters(qbits
))
1247 #----- That's all, folks ----------------------------------------------------