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 import DLFCN
as _dlfcn
32 from struct
import pack
as _pack
34 import types
as _types
36 ###--------------------------------------------------------------------------
37 ### Import the main C extension module.
40 _dlflags
= _odlflags
= _sys
.getdlopenflags()
41 except AttributeError:
42 _dlflags
= _odlflags
= -1
44 ## Set the `deep binding' flag. Python has its own different MD5
45 ## implementation, and some distributions export `md5_init' and friends so
46 ## they override our versions, which doesn't end well. Figure out how to
47 ## turn this flag on so we don't have the problem.
49 try: _dlflags |
= _dlfcn
.RTLD_DEEPBIND
50 except AttributeError:
51 try: _dlflags |
= _os
.RTLD_DEEPBIND
52 except AttributeError:
53 if _os
.uname()[0] == 'Linux': _dlflags |
= 8 # magic knowledge
54 else: pass # can't do this.
55 _sys
.setdlopenflags(_dlflags
)
60 _sys
.setdlopenflags(_odlflags
)
62 del _dlflags
, _odlflags
64 ###--------------------------------------------------------------------------
67 ## For the benefit of the default keyreporter, we need the program name.
68 _base
._ego(_sys
.argv
[0])
70 ## How to fix a name back into the right identifier. Alas, the rules are not
74 ## Hyphens consistently become underscores.
75 name
= name
.replace('-', '_')
77 ## But slashes might become underscores or just vanish.
78 if name
.startswith('salsa20'): name
= name
.translate(None, '/')
79 else: name
= name
.replace('/', '_')
84 ## Initialize the module. Drag in the static methods of the various
85 ## classes; create names for the various known crypto algorithms.
92 for i
in ['ByteString',
94 'ECPt', 'ECPtCurve', 'ECCurve', 'ECInfo',
95 'DHInfo', 'BinDHInfo', 'RSAPriv', 'BBSPriv',
96 'PrimeFilter', 'RabinMiller',
104 setattr(c
, j
[plen
:], classmethod(b
[j
]))
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 hashu8(me
, n
): return me
.hash(_pack('B', n
))
221 def hashu16l(me
, n
): return me
.hash(_pack('<H', n
))
222 def hashu16b(me
, n
): return me
.hash(_pack('>H', n
))
224 def hashu32l(me
, n
): return me
.hash(_pack('<L', n
))
225 def hashu32b(me
, n
): return me
.hash(_pack('>L', n
))
227 def hashu64l(me
, n
): return me
.hash(_pack('<Q', n
))
228 def hashu64b(me
, n
): return me
.hash(_pack('>Q', n
))
230 def hashbuf8(me
, s
): return me
.hashu8(len(s
)).hash(s
)
231 def hashbuf16l(me
, s
): return me
.hashu16l(len(s
)).hash(s
)
232 def hashbuf16b(me
, s
): return me
.hashu16b(len(s
)).hash(s
)
233 hashbuf16
= hashbuf16b
234 def hashbuf32l(me
, s
): return me
.hashu32l(len(s
)).hash(s
)
235 def hashbuf32b(me
, s
): return me
.hashu32b(len(s
)).hash(s
)
236 hashbuf32
= hashbuf32b
237 def hashbuf64l(me
, s
): return me
.hashu64l(len(s
)).hash(s
)
238 def hashbuf64b(me
, s
): return me
.hashu64b(len(s
)).hash(s
)
239 hashbuf64
= hashbuf64b
240 def hashstrz(me
, s
): return me
.hash(s
).hashu8(0)
242 class _ShakeBase (_HashBase
):
244 ## Python gets really confused if I try to augment `__new__' on native
245 ## classes, so wrap and delegate. Sorry.
246 def __init__(me
, perso
= '', *args
, **kw
):
247 super(_ShakeBase
, me
).__init__(*args
, **kw
)
248 me
._h
= me
._SHAKE(perso
= perso
, func
= me
._FUNC
)
250 ## Delegate methods...
251 def copy(me
): new
= me
.__class__(); new
._copy(me
)
252 def _copy(me
, other
): me
._h
= other
._h
253 def hash(me
, m
): me
._h
.hash(m
); return me
254 def xof(me
): me
._h
.xof(); return me
255 def get(me
, n
): return me
._h
.get(n
)
256 def mask(me
, m
): return me
._h
.mask(m
)
257 def done(me
, n
): return me
._h
.done(n
)
258 def check(me
, h
): return ctstreq(h
, me
.done(len(h
)))
260 def state(me
): return me
._h
.state
262 def buffered(me
): return me
._h
.buffered
264 def rate(me
): return me
._h
.rate
268 return ctstreq(h
, me
.done(len(h
)))
271 return me
.hashu8(len(nn
)).hash(nn
)
274 return me
.hash(nn
).hashu8(len(nn
))
275 def stringenc(me
, str):
276 return me
.leftenc(8*len(str)).hash(str)
277 def bytepad_before(me
):
278 return me
.leftenc(me
.rate
)
279 def bytepad_after(me
):
280 if me
.buffered
: me
.hash(me
._Z
[:me
.rate
- me
.buffered
])
287 _augment(Shake
, _tmp
)
288 _augment(_ShakeBase
, _tmp
)
289 Shake
._Z
= _ShakeBase
._Z
= ByteString
.zero(200)
291 class KMAC (_ShakeBase
):
293 def __init__(me
, k
, *arg
, **kw
):
294 super(KMAC
, me
).__init__(*arg
, **kw
)
295 with me
.bytepad(): me
.stringenc(k
)
296 def done(me
, n
= -1):
297 if n
< 0: n
= me
._TAGSZ
299 return super(KMAC
, me
).done(n
)
302 return super(KMAC
, me
).xof()
304 class KMAC128 (KMAC
): _SHAKE
= Shake128
; _TAGSZ
= 16
305 class KMAC256 (KMAC
): _SHAKE
= Shake256
; _TAGSZ
= 32
307 ###--------------------------------------------------------------------------
308 ### NaCl `secretbox'.
310 def secret_box(k
, n
, m
):
311 y
, t
= salsa20_naclbox(k
).encrypt(n
, m
)
314 def secret_unbox(k
, n
, c
):
316 return salsa20_naclbox(k
).decrypt(n
, c
[tsz
:], c
[0:tsz
])
318 ###--------------------------------------------------------------------------
319 ### Multiprecision integers and binary polynomials.
322 if isinstance(x
, BaseRat
): return x
._n
, x
._d
324 class BaseRat (object):
325 """Base class implementing fields of fractions over Euclidean domains."""
326 def __new__(cls
, a
, b
):
327 a
, b
= cls
.RING(a
), cls
.RING(b
)
331 me
= super(BaseRat
, cls
).__new__(cls
)
336 def numer(me
): return me
._n
338 def denom(me
): return me
._d
339 def __str__(me
): return '%s/%s' %
(me
._n
, me
._d
)
340 def __repr__(me
): return '%s(%s, %s)' %
(_clsname(me
), me
._n
, me
._d
)
341 _repr_pretty_
= _pp_str
343 def __add__(me
, you
):
344 n
, d
= _split_rat(you
)
345 return type(me
)(me
._n
*d
+ n
*me
._d
, d
*me
._d
)
347 def __sub__(me
, you
):
348 n
, d
= _split_rat(you
)
349 return type(me
)(me
._n
*d
- n
*me
._d
, d
*me
._d
)
350 def __rsub__(me
, you
):
351 n
, d
= _split_rat(you
)
352 return type(me
)(n
*me
._d
- me
._n
*d
, d
*me
._d
)
353 def __mul__(me
, you
):
354 n
, d
= _split_rat(you
)
355 return type(me
)(me
._n
*n
, me
._d
*d
)
356 def __div__(me
, you
):
357 n
, d
= _split_rat(you
)
358 return type(me
)(me
._n
*d
, me
._d
*n
)
359 def __rdiv__(me
, you
):
360 n
, d
= _split_rat(you
)
361 return type(me
)(me
._d
*n
, me
._n
*d
)
362 def __cmp__(me
, you
):
363 n
, d
= _split_rat(you
)
364 return type(me
)(me
._n
*d
, n
*me
._d
)
365 def __rcmp__(me
, you
):
366 n
, d
= _split_rat(you
)
367 return cmp(n
*me
._d
, me
._n
*d
)
369 class IntRat (BaseRat
):
372 class GFRat (BaseRat
):
376 def negp(x
): return x
< 0
377 def posp(x
): return x
> 0
378 def zerop(x
): return x
== 0
379 def oddp(x
): return x
.testbit(0)
380 def evenp(x
): return not x
.testbit(0)
381 def mont(x
): return MPMont(x
)
382 def barrett(x
): return MPBarrett(x
)
383 def reduce(x
): return MPReduce(x
)
384 def __div__(me
, you
): return IntRat(me
, you
)
385 def __rdiv__(me
, you
): return IntRat(you
, me
)
386 _repr_pretty_
= _pp_str
390 def zerop(x
): return x
== 0
391 def reduce(x
): return GFReduce(x
)
392 def trace(x
, y
): return x
.reduce().trace(y
)
393 def halftrace(x
, y
): return x
.reduce().halftrace(y
)
394 def modsqrt(x
, y
): return x
.reduce().sqrt(y
)
395 def quadsolve(x
, y
): return x
.reduce().quadsolve(y
)
396 def __div__(me
, you
): return GFRat(me
, you
)
397 def __rdiv__(me
, you
): return GFRat(you
, me
)
398 _repr_pretty_
= _pp_str
403 'product(ITERABLE) or product(I, ...) -> PRODUCT'
404 return MPMul(*arg
).done()
405 product
= staticmethod(product
)
406 _augment(MPMul
, _tmp
)
408 ###--------------------------------------------------------------------------
412 def fromstring(str): return _checkend(Field
.parse(str))
413 fromstring
= staticmethod(fromstring
)
414 _augment(Field
, _tmp
)
417 def __repr__(me
): return '%s(%sL)' %
(_clsname(me
), me
.p
)
418 def __hash__(me
): return 0x114401de ^
hash(me
.p
)
419 def _repr_pretty_(me
, pp
, cyclep
):
420 ind
= _pp_bgroup_tyname(pp
, me
)
421 if cyclep
: pp
.text('...')
422 else: pp
.pretty(me
.p
)
423 pp
.end_group(ind
, ')')
424 def ec(me
, a
, b
): return ECPrimeProjCurve(me
, a
, b
)
425 _augment(PrimeField
, _tmp
)
428 def __repr__(me
): return '%s(%#xL)' %
(_clsname(me
), me
.p
)
429 def ec(me
, a
, b
): return ECBinProjCurve(me
, a
, b
)
430 def _repr_pretty_(me
, pp
, cyclep
):
431 ind
= _pp_bgroup_tyname(pp
, me
)
432 if cyclep
: pp
.text('...')
433 else: pp
.text('%#x' % me
.p
)
434 pp
.end_group(ind
, ')')
435 _augment(BinField
, _tmp
)
438 def __hash__(me
): return 0x23e4701c ^
hash(me
.p
)
439 _augment(BinPolyField
, _tmp
)
445 h ^
= 2*hash(me
.beta
) & 0xffffffff
447 _augment(BinNormField
, _tmp
)
450 def __str__(me
): return str(me
.value
)
451 def __repr__(me
): return '%s(%s)' %
(repr(me
.field
), repr(me
.value
))
452 _repr_pretty_
= _pp_str
455 ###--------------------------------------------------------------------------
460 return '%s(%r, %s, %s)' %
(_clsname(me
), me
.field
, me
.a
, me
.b
)
461 def _repr_pretty_(me
, pp
, cyclep
):
462 ind
= _pp_bgroup_tyname(pp
, me
)
466 pp
.pretty(me
.field
); pp
.text(','); pp
.breakable()
467 pp
.pretty(me
.a
); pp
.text(','); pp
.breakable()
469 pp
.end_group(ind
, ')')
471 return ecpt
.frombuf(me
, s
)
473 return ecpt
.fromraw(me
, s
)
476 _augment(ECCurve
, _tmp
)
482 h ^
= 2*hash(me
.a
) ^
0xffffffff
483 h ^
= 5*hash(me
.b
) ^
0xffffffff
485 _augment(ECPrimeCurve
, _tmp
)
491 h ^
= 2*hash(me
.a
) ^
0xffffffff
492 h ^
= 5*hash(me
.b
) ^
0xffffffff
494 _augment(ECBinCurve
, _tmp
)
498 if not me
: return '%s()' %
_clsname(me
)
499 return '%s(%s, %s)' %
(_clsname(me
), me
.ix
, me
.iy
)
501 if not me
: return 'inf'
502 return '(%s, %s)' %
(me
.ix
, me
.iy
)
503 def _repr_pretty_(me
, pp
, cyclep
):
509 ind
= _pp_bgroup(pp
, '(')
510 pp
.pretty(me
.ix
); pp
.text(','); pp
.breakable()
512 pp
.end_group(ind
, ')')
517 return '%s(curve = %r, G = %r, r = %s, h = %s)' % \
518 (_clsname(me
), me
.curve
, me
.G
, me
.r
, me
.h
)
519 def _repr_pretty_(me
, pp
, cyclep
):
520 ind
= _pp_bgroup_tyname(pp
, me
)
524 _pp_kv(pp
, 'curve', me
.curve
); pp
.text(','); pp
.breakable()
525 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
526 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
527 _pp_kv(pp
, 'h', me
.h
)
528 pp
.end_group(ind
, ')')
532 h ^
= 2*hash(me
.G
) & 0xffffffff
536 _augment(ECInfo
, _tmp
)
540 if not me
: return '%r()' %
(me
.curve
)
541 return '%r(%s, %s)' %
(me
.curve
, me
.x
, me
.y
)
543 if not me
: return 'inf'
544 return '(%s, %s)' %
(me
.x
, me
.y
)
545 def _repr_pretty_(me
, pp
, cyclep
):
551 ind
= _pp_bgroup(pp
, '(')
552 pp
.pretty(me
.x
); pp
.text(','); pp
.breakable()
554 pp
.end_group(ind
, ')')
555 _augment(ECPtCurve
, _tmp
)
557 ###--------------------------------------------------------------------------
561 def __repr__(me
): return '%s(%d)' %
(_clsname(me
), me
.default
)
562 def check(me
, sz
): return True
563 def best(me
, sz
): return sz
564 def pad(me
, sz
): return sz
565 _augment(KeySZAny
, _tmp
)
569 return '%s(%d, %d, %d, %d)' % \
570 (_clsname(me
), me
.default
, me
.min, me
.max, me
.mod
)
571 def _repr_pretty_(me
, pp
, cyclep
):
572 ind
= _pp_bgroup_tyname(pp
, me
)
576 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
577 pp
.pretty(me
.min); pp
.text(','); pp
.breakable()
578 pp
.pretty(me
.max); pp
.text(','); pp
.breakable()
580 pp
.end_group(ind
, ')')
581 def check(me
, sz
): return me
.min <= sz
<= me
.max and sz
%me
.mod
== 0
583 if sz
< me
.min: raise ValueError, 'key too small'
584 elif sz
> me
.max: return me
.max
585 else: return sz
- sz
%me
.mod
587 if sz
> me
.max: raise ValueError, 'key too large'
588 elif sz
< me
.min: return me
.min
589 else: sz
+= me
.mod
; return sz
- sz
%me
.mod
590 _augment(KeySZRange
, _tmp
)
593 def __repr__(me
): return '%s(%d, %s)' %
(_clsname(me
), me
.default
, me
.set)
594 def _repr_pretty_(me
, pp
, cyclep
):
595 ind
= _pp_bgroup_tyname(pp
, me
)
599 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
600 ind1
= _pp_bgroup(pp
, '{')
601 _pp_commas(pp
, pp
.pretty
, me
.set)
602 pp
.end_group(ind1
, '}')
603 pp
.end_group(ind
, ')')
604 def check(me
, sz
): return sz
in me
.set
608 if found
< i
<= sz
: found
= i
609 if found
< 0: raise ValueError, 'key too small'
614 if sz
<= i
and (found
== -1 or i
< found
): found
= i
615 if found
< 0: raise ValueError, 'key too large'
617 _augment(KeySZSet
, _tmp
)
619 ###--------------------------------------------------------------------------
620 ### Key data objects.
623 def __repr__(me
): return '%s(%r)' %
(_clsname(me
), me
.name
)
624 _augment(KeyFile
, _tmp
)
627 def __repr__(me
): return '%s(%r)' %
(_clsname(me
), me
.fulltag
)
632 return '%s({%s})' %
(_clsname(me
),
633 ', '.join(['%r: %r' % kv
for kv
in me
.iteritems()]))
634 def _repr_pretty_(me
, pp
, cyclep
):
635 ind
= _pp_bgroup_tyname(pp
, me
)
636 if cyclep
: pp
.text('...')
637 else: _pp_dict(pp
, me
.iteritems())
638 pp
.end_group(ind
, ')')
639 _augment(KeyAttributes
, _tmp
)
643 return '%s(%s, %r)' %
(_clsname(me
),
644 _repr_secret(me
._guts(),
645 not (me
.flags
& KF_NONSECRET
)),
646 me
.writeflags(me
.flags
))
647 def _repr_pretty_(me
, pp
, cyclep
):
648 ind
= _pp_bgroup_tyname(pp
, me
)
652 _pp_secret(pp
, me
._guts(), not (me
.flags
& KF_NONSECRET
))
653 pp
.text(','); pp
.breakable()
654 pp
.pretty(me
.writeflags(me
.flags
))
655 pp
.end_group(ind
, ')')
656 _augment(KeyData
, _tmp
)
659 def _guts(me
): return me
.bin
660 _augment(KeyDataBinary
, _tmp
)
663 def _guts(me
): return me
.ct
664 _augment(KeyDataEncrypted
, _tmp
)
667 def _guts(me
): return me
.mp
668 _augment(KeyDataMP
, _tmp
)
671 def _guts(me
): return me
.str
672 _augment(KeyDataString
, _tmp
)
675 def _guts(me
): return me
.ecpt
676 _augment(KeyDataECPt
, _tmp
)
680 return '%s({%s})' %
(_clsname(me
),
681 ', '.join(['%r: %r' % kv
for kv
in me
.iteritems()]))
682 def _repr_pretty_(me
, pp
, cyclep
):
683 ind
= _pp_bgroup_tyname(pp
, me
, '({ ')
684 if cyclep
: pp
.text('...')
685 else: _pp_dict(pp
, me
.iteritems())
686 pp
.end_group(ind
, ' })')
687 _augment(KeyDataStructured
, _tmp
)
689 ###--------------------------------------------------------------------------
694 return '%s(p = %s, r = %s, g = %s)' %
(_clsname(me
), me
.p
, me
.r
, me
.g
)
695 def _repr_pretty_(me
, pp
, cyclep
):
696 ind
= _pp_bgroup_tyname(pp
, me
)
700 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
701 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
702 _pp_kv(pp
, 'g', me
.g
)
703 pp
.end_group(ind
, ')')
704 _augment(FGInfo
, _tmp
)
707 def group(me
): return PrimeGroup(me
)
708 _augment(DHInfo
, _tmp
)
711 def group(me
): return BinGroup(me
)
712 _augment(BinDHInfo
, _tmp
)
716 return '%s(%r)' %
(_clsname(me
), me
.info
)
717 def _repr_pretty_(me
, pp
, cyclep
):
718 ind
= _pp_bgroup_tyname(pp
, me
)
719 if cyclep
: pp
.text('...')
720 else: pp
.pretty(me
.info
)
721 pp
.end_group(ind
, ')')
722 _augment(Group
, _tmp
)
729 h ^
= 2*hash(info
.r
) & 0xffffffff
730 h ^
= 5*hash(info
.g
) & 0xffffffff
732 def _get_geval(me
, x
): return MP(x
)
733 _augment(PrimeGroup
, _tmp
)
740 h ^
= 2*hash(info
.r
) & 0xffffffff
741 h ^
= 5*hash(info
.g
) & 0xffffffff
743 def _get_geval(me
, x
): return GF(x
)
744 _augment(BinGroup
, _tmp
)
747 def __hash__(me
): return 0x0ec23dab ^
hash(me
.info
)
748 def _get_geval(me
, x
): return x
.toec()
749 _augment(ECGroup
, _tmp
)
753 return '%r(%r)' %
(me
.group
, str(me
))
754 def _repr_pretty_(me
, pp
, cyclep
):
755 pp
.pretty(type(me
)._get_geval(me
))
758 ###--------------------------------------------------------------------------
759 ### RSA encoding techniques.
761 class PKCS1Crypt (object):
762 def __init__(me
, ep
= '', rng
= rand
):
765 def encode(me
, msg
, nbits
):
766 return _base
._p1crypt_encode(msg
, nbits
, me
.ep
, me
.rng
)
767 def decode(me
, ct
, nbits
):
768 return _base
._p1crypt_decode(ct
, nbits
, me
.ep
, me
.rng
)
770 class PKCS1Sig (object):
771 def __init__(me
, ep
= '', rng
= rand
):
774 def encode(me
, msg
, nbits
):
775 return _base
._p1sig_encode(msg
, nbits
, me
.ep
, me
.rng
)
776 def decode(me
, msg
, sig
, nbits
):
777 return _base
._p1sig_decode(msg
, sig
, nbits
, me
.ep
, me
.rng
)
780 def __init__(me
, mgf
= sha_mgf
, hash = sha
, ep
= '', rng
= rand
):
785 def encode(me
, msg
, nbits
):
786 return _base
._oaep_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
787 def decode(me
, ct
, nbits
):
788 return _base
._oaep_decode(ct
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
791 def __init__(me
, mgf
= sha_mgf
, hash = sha
, saltsz
= None, rng
= rand
):
798 def encode(me
, msg
, nbits
):
799 return _base
._pss_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
800 def decode(me
, msg
, sig
, nbits
):
801 return _base
._pss_decode(msg
, sig
, nbits
,
802 me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
805 def encrypt(me
, msg
, enc
):
806 return me
.pubop(enc
.encode(msg
, me
.n
.nbits
))
807 def verify(me
, msg
, sig
, enc
):
808 if msg
is None: return enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
810 x
= enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
811 return x
is None or x
== msg
815 return '%s(n = %r, e = %r)' %
(_clsname(me
), me
.n
, me
.e
)
816 def _repr_pretty_(me
, pp
, cyclep
):
817 ind
= _pp_bgroup_tyname(pp
, me
)
821 _pp_kv(pp
, 'n', me
.n
); pp
.text(','); pp
.breakable()
822 _pp_kv(pp
, 'e', me
.e
)
823 pp
.end_group(ind
, ')')
824 _augment(RSAPub
, _tmp
)
827 def decrypt(me
, ct
, enc
): return enc
.decode(me
.privop(ct
), me
.n
.nbits
)
828 def sign(me
, msg
, enc
): return me
.privop(enc
.encode(msg
, me
.n
.nbits
))
830 return '%s(n = %r, e = %r, d = %s, ' \
831 'p = %s, q = %s, dp = %s, dq = %s, q_inv = %s)' % \
832 (_clsname(me
), me
.n
, me
.e
,
833 _repr_secret(me
.d
), _repr_secret(me
.p
), _repr_secret(me
.q
),
834 _repr_secret(me
.dp
), _repr_secret(me
.dq
), _repr_secret(me
.q_inv
))
835 def _repr_pretty_(me
, pp
, cyclep
):
836 ind
= _pp_bgroup_tyname(pp
, me
)
840 _pp_kv(pp
, 'n', me
.n
); pp
.text(','); pp
.breakable()
841 _pp_kv(pp
, 'e', me
.e
); pp
.text(','); pp
.breakable()
842 _pp_kv(pp
, 'd', me
.d
, secretp
= True); pp
.text(','); pp
.breakable()
843 _pp_kv(pp
, 'p', me
.p
, secretp
= True); pp
.text(','); pp
.breakable()
844 _pp_kv(pp
, 'q', me
.q
, secretp
= True); pp
.text(','); pp
.breakable()
845 _pp_kv(pp
, 'dp', me
.dp
, secretp
= True); pp
.text(','); pp
.breakable()
846 _pp_kv(pp
, 'dq', me
.dq
, secretp
= True); pp
.text(','); pp
.breakable()
847 _pp_kv(pp
, 'q_inv', me
.q_inv
, secretp
= True)
848 pp
.end_group(ind
, ')')
849 _augment(RSAPriv
, _tmp
)
851 ###--------------------------------------------------------------------------
852 ### DSA and related schemes.
855 def __repr__(me
): return '%s(G = %r, p = %r, hash = %r)' % \
856 (_clsname(me
), me
.G
, me
.p
, me
.hash)
857 def _repr_pretty_(me
, pp
, cyclep
):
858 ind
= _pp_bgroup_tyname(pp
, me
)
862 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
863 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
864 _pp_kv(pp
, 'hash', me
.hash)
865 pp
.end_group(ind
, ')')
866 _augment(DSAPub
, _tmp
)
867 _augment(KCDSAPub
, _tmp
)
870 def __repr__(me
): return '%s(G = %r, u = %s, p = %r, hash = %r)' % \
871 (_clsname(me
), me
.G
, _repr_secret(me
.u
), me
.p
, me
.hash)
872 def _repr_pretty_(me
, pp
, cyclep
):
873 ind
= _pp_bgroup_tyname(pp
, me
)
877 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
878 _pp_kv(pp
, 'u', me
.u
, True); 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(DSAPriv
, _tmp
)
883 _augment(KCDSAPriv
, _tmp
)
885 ###--------------------------------------------------------------------------
886 ### Bernstein's elliptic curve crypto and related schemes.
888 X25519_BASE
= MP(9).storel(32)
889 X448_BASE
= MP(5).storel(56)
891 Z128
= ByteString
.zero(16)
893 class _BasePub (object):
894 def __init__(me
, pub
, *args
, **kw
):
895 if not me
._PUBSZ
.check(len(pub
)): raise ValueError, 'bad public key'
896 super(_BasePub
, me
).__init__(*args
, **kw
)
898 def __repr__(me
): return '%s(pub = %r)' %
(_clsname(me
), me
.pub
)
899 def _pp(me
, pp
): _pp_kv(pp
, 'pub', me
.pub
)
900 def _repr_pretty_(me
, pp
, cyclep
):
901 ind
= _pp_bgroup_tyname(pp
, me
)
902 if cyclep
: pp
.text('...')
904 pp
.end_group(ind
, ')')
906 class _BasePriv (object):
907 def __init__(me
, priv
, pub
= None, *args
, **kw
):
908 if not me
._KEYSZ
.check(len(priv
)): raise ValueError, 'bad private key'
909 if pub
is None: pub
= me
._pubkey(priv
)
910 super(_BasePriv
, me
).__init__(pub
= pub
, *args
, **kw
)
913 def generate(cls
, rng
= rand
):
914 return cls(rng
.block(cls
._KEYSZ
.default
))
916 return '%s(priv = %d, pub = %r)' % \
917 (_clsname(me
), _repr_secret(me
.priv
), me
.pub
)
919 _pp_kv(pp
, 'priv', me
.priv
, secretp
= True); pp
.text(','); pp
.breakable()
920 super(_BasePriv
, me
)._pp(pp
)
922 class _XDHPub (_BasePub
): pass
924 class _XDHPriv (_BasePriv
):
925 def _pubkey(me
, priv
): return me
._op(priv
, me
._BASE
)
926 def agree(me
, you
): return me
._op(me
.priv
, you
.pub
)
927 def boxkey(me
, recip
): return me
._hashkey(me
.agree(recip
))
928 def box(me
, recip
, n
, m
): return secret_box(me
.boxkey(recip
), n
, m
)
929 def unbox(me
, recip
, n
, c
): return secret_unbox(me
.boxkey(recip
), n
, c
)
931 class X25519Pub (_XDHPub
):
932 _PUBSZ
= KeySZSet(X25519_PUBSZ
)
935 class X25519Priv (_XDHPriv
, X25519Pub
):
936 _KEYSZ
= KeySZSet(X25519_KEYSZ
)
937 def _op(me
, k
, X
): return x25519(k
, X
)
938 def _hashkey(me
, z
): return hsalsa20_prf(z
, Z128
)
940 class X448Pub (_XDHPub
):
941 _PUBSZ
= KeySZSet(X448_PUBSZ
)
944 class X448Priv (_XDHPriv
, X448Pub
):
945 _KEYSZ
= KeySZSet(X448_KEYSZ
)
946 def _op(me
, k
, X
): return x448(k
, X
)
947 def _hashkey(me
, z
): return Shake256().hash(z
).done(salsa20
.keysz
.default
)
949 class _EdDSAPub (_BasePub
):
950 def beginhash(me
): return me
._HASH()
951 def endhash(me
, h
): return h
.done()
953 class _EdDSAPriv (_BasePriv
, _EdDSAPub
):
956 class Ed25519Pub (_EdDSAPub
):
957 _PUBSZ
= KeySZSet(ED25519_PUBSZ
)
959 def verify(me
, msg
, sig
, **kw
):
960 return ed25519_verify(me
.pub
, msg
, sig
, **kw
)
962 class Ed25519Priv (_EdDSAPriv
, Ed25519Pub
):
963 _KEYSZ
= KeySZAny(ED25519_KEYSZ
)
964 def _pubkey(me
, priv
): return ed25519_pubkey(priv
)
965 def sign(me
, msg
, **kw
):
966 return ed25519_sign(me
.priv
, msg
, pub
= me
.pub
, **kw
)
968 class Ed448Pub (_EdDSAPub
):
969 _PUBSZ
= KeySZSet(ED448_PUBSZ
)
971 def verify(me
, msg
, sig
, **kw
):
972 return ed448_verify(me
.pub
, msg
, sig
, **kw
)
974 class Ed448Priv (_EdDSAPriv
, Ed448Pub
):
975 _KEYSZ
= KeySZAny(ED448_KEYSZ
)
976 def _pubkey(me
, priv
): return ed448_pubkey(priv
)
977 def sign(me
, msg
, **kw
):
978 return ed448_sign(me
.priv
, msg
, pub
= me
.pub
, **kw
)
980 ###--------------------------------------------------------------------------
981 ### Built-in named curves and prime groups.
983 class _groupmap (object):
984 def __init__(me
, map, nth
):
987 me
._n
= max(map.values()) + 1
990 return '{%s}' %
', '.join(['%r: %r' % kv
for kv
in me
.iteritems()])
991 def _repr_pretty_(me
, pp
, cyclep
):
992 ind
= _pp_bgroup(pp
, '{ ')
993 if cyclep
: pp
.text('...')
994 else: _pp_dict(pp
, me
.iteritems())
995 pp
.end_group(ind
, ' }')
998 def __contains__(me
, k
):
1000 def __getitem__(me
, k
):
1005 def __setitem__(me
, k
, v
):
1006 raise TypeError, "immutable object"
1018 return [k
for k
in me
]
1020 return [me
[k
] for k
in me
]
1022 return [(k
, me
[k
]) for k
in me
]
1023 eccurves
= _groupmap(_base
._eccurves
, ECInfo
._curven
)
1024 primegroups
= _groupmap(_base
._pgroups
, DHInfo
._groupn
)
1025 bingroups
= _groupmap(_base
._bingroups
, BinDHInfo
._groupn
)
1027 ###--------------------------------------------------------------------------
1028 ### Prime number generation.
1030 class PrimeGenEventHandler (object):
1031 def pg_begin(me
, ev
):
1032 return me
.pg_try(ev
)
1033 def pg_done(me
, ev
):
1035 def pg_abort(me
, ev
):
1037 def pg_fail(me
, ev
):
1039 def pg_pass(me
, ev
):
1042 class SophieGermainStepJump (object):
1043 def pg_begin(me
, ev
):
1044 me
.lf
= PrimeFilter(ev
.x
)
1045 me
.hf
= me
.lf
.muladd(2, 1)
1051 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
1053 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
1056 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
1059 def pg_done(me
, ev
):
1063 class SophieGermainStepper (SophieGermainStepJump
):
1064 def __init__(me
, step
):
1068 me
.lf
.step(me
.lstep
)
1069 me
.hf
.step(me
.hstep
)
1071 class SophieGermainJumper (SophieGermainStepJump
):
1072 def __init__(me
, jump
):
1073 me
.ljump
= PrimeFilter(jump
);
1074 me
.hjump
= me
.ljump
.muladd(2, 0)
1076 me
.lf
.jump(me
.ljump
)
1077 me
.hf
.jump(me
.hjump
)
1078 def pg_done(me
, ev
):
1081 SophieGermainStepJump
.pg_done(me
, ev
)
1083 class SophieGermainTester (object):
1086 def pg_begin(me
, ev
):
1087 me
.lr
= RabinMiller(ev
.x
)
1088 me
.hr
= RabinMiller(2 * ev
.x
+ 1)
1090 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
1091 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
1093 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
1094 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
1096 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
1099 def pg_done(me
, ev
):
1103 class PrimitiveStepper (PrimeGenEventHandler
):
1109 def pg_begin(me
, ev
):
1110 me
.i
= iter(smallprimes
)
1111 return me
.pg_try(ev
)
1113 class PrimitiveTester (PrimeGenEventHandler
):
1114 def __init__(me
, mod
, hh
= [], exp
= None):
1115 me
.mod
= MPMont(mod
)
1120 if me
.exp
is not None:
1121 x
= me
.mod
.exp(x
, me
.exp
)
1122 if x
== 1: return PGEN_FAIL
1124 if me
.mod
.exp(x
, h
) == 1: return PGEN_FAIL
1128 class SimulStepper (PrimeGenEventHandler
):
1129 def __init__(me
, mul
= 2, add
= 1, step
= 2):
1133 def _stepfn(me
, step
):
1135 raise ValueError, 'step must be positive'
1137 return lambda f
: f
.step(step
)
1138 j
= PrimeFilter(step
)
1139 return lambda f
: f
.jump(j
)
1140 def pg_begin(me
, ev
):
1142 me
.lf
= PrimeFilter(x
)
1143 me
.hf
= PrimeFilter(x
* me
.mul
+ me
.add
)
1144 me
.lstep
= me
._stepfn(me
.step
)
1145 me
.hstep
= me
._stepfn(me
.step
* me
.mul
)
1146 SimulStepper
._cont(me
, ev
)
1154 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
1156 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
1159 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
1162 def pg_done(me
, ev
):
1168 class SimulTester (PrimeGenEventHandler
):
1169 def __init__(me
, mul
= 2, add
= 1):
1172 def pg_begin(me
, ev
):
1174 me
.lr
= RabinMiller(x
)
1175 me
.hr
= RabinMiller(x
* me
.mul
+ me
.add
)
1177 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
1178 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
1180 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
1181 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
1183 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
1186 def pg_done(me
, ev
):
1190 def sgprime(start
, step
= 2, name
= 'p', event
= pgen_nullev
, nsteps
= 0):
1192 return pgen(start
, name
, SimulStepper(step
= step
), SimulTester(), event
,
1193 nsteps
, RabinMiller
.iters(start
.nbits
))
1195 def findprimitive(mod
, hh
= [], exp
= None, name
= 'g', event
= pgen_nullev
):
1196 return pgen(0, name
, PrimitiveStepper(), PrimitiveTester(mod
, hh
, exp
),
1199 def kcdsaprime(pbits
, qbits
, rng
= rand
,
1200 event
= pgen_nullev
, name
= 'p', nsteps
= 0):
1201 hbits
= pbits
- qbits
1202 h
= pgen(rng
.mp(hbits
, 1), name
+ ' [h]',
1203 PrimeGenStepper(2), PrimeGenTester(),
1204 event
, nsteps
, RabinMiller
.iters(hbits
))
1205 q
= pgen(rng
.mp(qbits
, 1), name
, SimulStepper(2 * h
, 1, 2),
1206 SimulTester(2 * h
, 1), event
, nsteps
, RabinMiller
.iters(qbits
))
1210 #----- That's all, folks ----------------------------------------------------