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 from struct
import pack
as _pack
32 import types
as _types
34 ###--------------------------------------------------------------------------
35 ### Import the main C extension module.
39 ###--------------------------------------------------------------------------
42 ## For the benefit of the default keyreporter, we need the program name.
43 _base
._ego(_sys
.argv
[0])
45 ## How to fix a name back into the right identifier. Alas, the rules are not
49 ## Hyphens consistently become underscores.
50 name
= name
.replace('-', '_')
52 ## But slashes might become underscores or just vanish.
53 if name
.startswith('salsa20'): name
= name
.replace('/', '')
54 else: name
= name
.replace('/', '_')
59 ## Initialize the module. Drag in the static methods of the various
60 ## classes; create names for the various known crypto algorithms.
67 for i
in ['ByteString',
69 'ECPt', 'ECPtCurve', 'ECCurve', 'ECInfo',
70 'DHInfo', 'BinDHInfo', 'RSAPriv', 'BBSPriv',
71 'PrimeFilter', 'RabinMiller',
79 setattr(c
, j
[plen
:], classmethod(b
[j
]))
80 for i
in [gcciphers
, gchashes
, gcmacs
, gcprps
]:
81 for c
in i
.itervalues():
82 d
[_fixname(c
.name
)] = c
83 for c
in gccrands
.itervalues():
84 d
[_fixname(c
.name
+ 'rand')] = c
87 ## A handy function for our work: add the methods of a named class to an
88 ## existing class. This is how we write the Python-implemented parts of our
93 if type(a
) is _types
.MethodType
:
95 elif type(a
) not in (_types
.FunctionType
, staticmethod, classmethod):
99 ## Parsing functions tend to return the object parsed and the remainder of
100 ## the input. This checks that the remainder is input and, if so, returns
105 raise SyntaxError, 'junk at end of string'
108 ## Some pretty-printing utilities.
109 PRINT_SECRETS
= False
110 def _clsname(me
): return type(me
).__name__
111 def _repr_secret(thing
, secretp
= True):
112 if not secretp
or PRINT_SECRETS
: return repr(thing
)
113 else: return '#<SECRET>'
114 def _pp_str(me
, pp
, cyclep
): pp
.text(cyclep
and '...' or str(me
))
115 def _pp_secret(pp
, thing
, secretp
= True):
116 if not secretp
or PRINT_SECRETS
: pp
.pretty(thing
)
117 else: pp
.text('#<SECRET>')
118 def _pp_bgroup(pp
, text
):
120 pp
.begin_group(ind
, text
)
122 def _pp_bgroup_tyname(pp
, obj
, open = '('):
123 return _pp_bgroup(pp
, _clsname(obj
) + open)
124 def _pp_kv(pp
, k
, v
, secretp
= False):
125 ind
= _pp_bgroup(pp
, k
+ ' = ')
126 _pp_secret(pp
, v
, secretp
)
127 pp
.end_group(ind
, '')
128 def _pp_commas(pp
, printfn
, items
):
131 if firstp
: firstp
= False
132 else: pp
.text(','); pp
.breakable()
134 def _pp_dict(pp
, items
):
144 _pp_commas(pp
, p
, items
)
146 ###--------------------------------------------------------------------------
151 return ByteString(_unhexify(x
))
152 fromhex
= staticmethod(fromhex
)
156 return 'bytes(%r)' %
hex(me
)
157 _augment(ByteString
, _tmp
)
158 ByteString
.__hash__
= str.__hash__
159 bytes
= ByteString
.fromhex
161 ###--------------------------------------------------------------------------
167 return ctstreq(h
, hh
)
168 _augment(GHash
, _tmp
)
169 _augment(Poly1305Hash
, _tmp
)
171 class _HashBase (object):
172 ## The standard hash methods. Assume that `hash' is defined and returns
174 def hashu8(me
, n
): return me
.hash(_pack('B', n
))
175 def hashu16l(me
, n
): return me
.hash(_pack('<H', n
))
176 def hashu16b(me
, n
): return me
.hash(_pack('>H', n
))
178 def hashu32l(me
, n
): return me
.hash(_pack('<L', n
))
179 def hashu32b(me
, n
): return me
.hash(_pack('>L', n
))
181 def hashu64l(me
, n
): return me
.hash(_pack('<Q', n
))
182 def hashu64b(me
, n
): return me
.hash(_pack('>Q', n
))
184 def hashbuf8(me
, s
): return me
.hashu8(len(s
)).hash(s
)
185 def hashbuf16l(me
, s
): return me
.hashu16l(len(s
)).hash(s
)
186 def hashbuf16b(me
, s
): return me
.hashu16b(len(s
)).hash(s
)
187 hashbuf16
= hashbuf16b
188 def hashbuf32l(me
, s
): return me
.hashu32l(len(s
)).hash(s
)
189 def hashbuf32b(me
, s
): return me
.hashu32b(len(s
)).hash(s
)
190 hashbuf32
= hashbuf32b
191 def hashbuf64l(me
, s
): return me
.hashu64l(len(s
)).hash(s
)
192 def hashbuf64b(me
, s
): return me
.hashu64b(len(s
)).hash(s
)
193 hashbuf64
= hashbuf64b
194 def hashstrz(me
, s
): return me
.hash(s
).hashu8(0)
196 class _ShakeBase (_HashBase
):
198 ## Python gets really confused if I try to augment `__new__' on native
199 ## classes, so wrap and delegate. Sorry.
200 def __init__(me
, perso
= '', *args
, **kw
):
201 super(_ShakeBase
, me
).__init__(*args
, **kw
)
202 me
._h
= me
._SHAKE(perso
= perso
, func
= me
._FUNC
)
204 ## Delegate methods...
205 def copy(me
): new
= me
.__class__(); new
._copy(me
)
206 def _copy(me
, other
): me
._h
= other
._h
207 def hash(me
, m
): me
._h
.hash(m
); return me
208 def xof(me
): me
._h
.xof(); return me
209 def get(me
, n
): return me
._h
.get(n
)
210 def mask(me
, m
): return me
._h
.mask(m
)
211 def done(me
, n
): return me
._h
.done(n
)
212 def check(me
, h
): return ctstreq(h
, me
.done(len(h
)))
214 def state(me
): return me
._h
.state
216 def buffered(me
): return me
._h
.buffered
218 def rate(me
): return me
._h
.rate
222 return ctstreq(h
, me
.done(len(h
)))
225 return me
.hashu8(len(nn
)).hash(nn
)
228 return me
.hash(nn
).hashu8(len(nn
))
229 def stringenc(me
, str):
230 return me
.leftenc(8*len(str)).hash(str)
231 def bytepad_before(me
):
232 return me
.leftenc(me
.rate
)
233 def bytepad_after(me
):
234 if me
.buffered
: me
.hash(me
._Z
[:me
.rate
- me
.buffered
])
241 _augment(Shake
, _tmp
)
242 _augment(_ShakeBase
, _tmp
)
243 Shake
._Z
= _ShakeBase
._Z
= ByteString(200*'\0')
245 class KMAC (_ShakeBase
):
247 def __init__(me
, k
, *arg
, **kw
):
248 super(KMAC
, me
).__init__(*arg
, **kw
)
249 with me
.bytepad(): me
.stringenc(k
)
250 def done(me
, n
= -1):
251 if n
< 0: n
= me
._TAGSZ
253 return super(KMAC
, me
).done(n
)
256 return super(KMAC
, me
).xof()
258 class KMAC128 (KMAC
): _SHAKE
= Shake128
; _TAGSZ
= 16
259 class KMAC256 (KMAC
): _SHAKE
= Shake256
; _TAGSZ
= 32
261 ###--------------------------------------------------------------------------
262 ### NaCl `secretbox'.
264 def secret_box(k
, n
, m
):
265 E
= xsalsa20(k
).setiv(n
)
266 r
= E
.enczero(poly1305
.keysz
.default
)
267 s
= E
.enczero(poly1305
.masksz
)
269 t
= poly1305(r
)(s
).hash(y
).done()
270 return ByteString(t
+ y
)
272 def secret_unbox(k
, n
, c
):
273 E
= xsalsa20(k
).setiv(n
)
274 r
= E
.enczero(poly1305
.keysz
.default
)
275 s
= E
.enczero(poly1305
.masksz
)
276 y
= c
[poly1305
.tagsz
:]
277 if not poly1305(r
)(s
).hash(y
).check(c
[0:poly1305
.tagsz
]):
278 raise ValueError, 'decryption failed'
279 return E
.decrypt(c
[poly1305
.tagsz
:])
281 ###--------------------------------------------------------------------------
282 ### Multiprecision integers and binary polynomials.
285 if isinstance(x
, BaseRat
): return x
._n
, x
._d
287 class BaseRat (object):
288 """Base class implementing fields of fractions over Euclidean domains."""
289 def __new__(cls
, a
, b
):
290 a
, b
= cls
.RING(a
), cls
.RING(b
)
294 me
= super(BaseRat
, cls
).__new__(cls
)
299 def numer(me
): return me
._n
301 def denom(me
): return me
._d
302 def __str__(me
): return '%s/%s' %
(me
._n
, me
._d
)
303 def __repr__(me
): return '%s(%s, %s)' %
(_clsname(me
), me
._n
, me
._d
)
304 _repr_pretty_
= _pp_str
306 def __add__(me
, you
):
307 n
, d
= _split_rat(you
)
308 return type(me
)(me
._n
*d
+ n
*me
._d
, d
*me
._d
)
310 def __sub__(me
, you
):
311 n
, d
= _split_rat(you
)
312 return type(me
)(me
._n
*d
- n
*me
._d
, d
*me
._d
)
313 def __rsub__(me
, you
):
314 n
, d
= _split_rat(you
)
315 return type(me
)(n
*me
._d
- me
._n
*d
, d
*me
._d
)
316 def __mul__(me
, you
):
317 n
, d
= _split_rat(you
)
318 return type(me
)(me
._n
*n
, me
._d
*d
)
320 def __truediv__(me
, you
):
321 n
, d
= _split_rat(you
)
322 return type(me
)(me
._n
*d
, me
._d
*n
)
323 def __rtruediv__(me
, you
):
324 n
, d
= _split_rat(you
)
325 return type(me
)(me
._d
*n
, me
._n
*d
)
326 __div__
= __truediv__
327 __rdiv__
= __rtruediv__
328 def __cmp__(me
, you
):
329 n
, d
= _split_rat(you
)
330 return cmp(me
._n
*d
, n
*me
._d
)
331 def __rcmp__(me
, you
):
332 n
, d
= _split_rat(you
)
333 return cmp(n
*me
._d
, me
._n
*d
)
335 class IntRat (BaseRat
):
338 class GFRat (BaseRat
):
342 def negp(x
): return x
< 0
343 def posp(x
): return x
> 0
344 def zerop(x
): return x
== 0
345 def oddp(x
): return x
.testbit(0)
346 def evenp(x
): return not x
.testbit(0)
347 def mont(x
): return MPMont(x
)
348 def barrett(x
): return MPBarrett(x
)
349 def reduce(x
): return MPReduce(x
)
350 def __truediv__(me
, you
): return IntRat(me
, you
)
351 def __rtruediv__(me
, you
): return IntRat(you
, me
)
352 __div__
= __truediv__
353 __rdiv__
= __rtruediv__
354 _repr_pretty_
= _pp_str
358 def zerop(x
): return x
== 0
359 def reduce(x
): return GFReduce(x
)
360 def trace(x
, y
): return x
.reduce().trace(y
)
361 def halftrace(x
, y
): return x
.reduce().halftrace(y
)
362 def modsqrt(x
, y
): return x
.reduce().sqrt(y
)
363 def quadsolve(x
, y
): return x
.reduce().quadsolve(y
)
364 def __truediv__(me
, you
): return GFRat(me
, you
)
365 def __rtruediv__(me
, you
): return GFRat(you
, me
)
366 __div__
= __truediv__
367 __rdiv__
= __rtruediv__
368 _repr_pretty_
= _pp_str
373 'product(ITERABLE) or product(I, ...) -> PRODUCT'
374 return MPMul(*arg
).done()
375 product
= staticmethod(product
)
376 _augment(MPMul
, _tmp
)
378 ###--------------------------------------------------------------------------
382 def fromstring(str): return _checkend(Field
.parse(str))
383 fromstring
= staticmethod(fromstring
)
384 _augment(Field
, _tmp
)
387 def __repr__(me
): return '%s(%sL)' %
(_clsname(me
), me
.p
)
388 def __hash__(me
): return 0x114401de ^
hash(me
.p
)
389 def _repr_pretty_(me
, pp
, cyclep
):
390 ind
= _pp_bgroup_tyname(pp
, me
)
391 if cyclep
: pp
.text('...')
392 else: pp
.pretty(me
.p
)
393 pp
.end_group(ind
, ')')
394 def ec(me
, a
, b
): return ECPrimeProjCurve(me
, a
, b
)
395 _augment(PrimeField
, _tmp
)
398 def __repr__(me
): return '%s(%#xL)' %
(_clsname(me
), me
.p
)
399 def ec(me
, a
, b
): return ECBinProjCurve(me
, a
, b
)
400 def _repr_pretty_(me
, pp
, cyclep
):
401 ind
= _pp_bgroup_tyname(pp
, me
)
402 if cyclep
: pp
.text('...')
403 else: pp
.text('%#x' % me
.p
)
404 pp
.end_group(ind
, ')')
405 _augment(BinField
, _tmp
)
408 def __hash__(me
): return 0x23e4701c ^
hash(me
.p
)
409 _augment(BinPolyField
, _tmp
)
415 h ^
= 2*hash(me
.beta
) & 0xffffffff
417 _augment(BinNormField
, _tmp
)
420 def __str__(me
): return str(me
.value
)
421 def __repr__(me
): return '%s(%s)' %
(repr(me
.field
), repr(me
.value
))
422 _repr_pretty_
= _pp_str
425 ###--------------------------------------------------------------------------
430 return '%s(%r, %s, %s)' %
(_clsname(me
), me
.field
, me
.a
, me
.b
)
431 def _repr_pretty_(me
, pp
, cyclep
):
432 ind
= _pp_bgroup_tyname(pp
, me
)
436 pp
.pretty(me
.field
); pp
.text(','); pp
.breakable()
437 pp
.pretty(me
.a
); pp
.text(','); pp
.breakable()
439 pp
.end_group(ind
, ')')
441 return ecpt
.frombuf(me
, s
)
443 return ecpt
.fromraw(me
, s
)
446 _augment(ECCurve
, _tmp
)
452 h ^
= 2*hash(me
.a
) ^
0xffffffff
453 h ^
= 5*hash(me
.b
) ^
0xffffffff
455 _augment(ECPrimeCurve
, _tmp
)
461 h ^
= 2*hash(me
.a
) ^
0xffffffff
462 h ^
= 5*hash(me
.b
) ^
0xffffffff
464 _augment(ECBinCurve
, _tmp
)
468 if not me
: return '%s()' %
_clsname(me
)
469 return '%s(%s, %s)' %
(_clsname(me
), me
.ix
, me
.iy
)
471 if not me
: return 'inf'
472 return '(%s, %s)' %
(me
.ix
, me
.iy
)
473 def _repr_pretty_(me
, pp
, cyclep
):
479 ind
= _pp_bgroup(pp
, '(')
480 pp
.pretty(me
.ix
); pp
.text(','); pp
.breakable()
482 pp
.end_group(ind
, ')')
487 return '%s(curve = %r, G = %r, r = %s, h = %s)' % \
488 (_clsname(me
), me
.curve
, me
.G
, me
.r
, me
.h
)
489 def _repr_pretty_(me
, pp
, cyclep
):
490 ind
= _pp_bgroup_tyname(pp
, me
)
494 _pp_kv(pp
, 'curve', me
.curve
); pp
.text(','); pp
.breakable()
495 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
496 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
497 _pp_kv(pp
, 'h', me
.h
)
498 pp
.end_group(ind
, ')')
502 h ^
= 2*hash(me
.G
) & 0xffffffff
506 _augment(ECInfo
, _tmp
)
510 if not me
: return '%r()' %
(me
.curve
)
511 return '%r(%s, %s)' %
(me
.curve
, me
.x
, me
.y
)
513 if not me
: return 'inf'
514 return '(%s, %s)' %
(me
.x
, me
.y
)
515 def _repr_pretty_(me
, pp
, cyclep
):
521 ind
= _pp_bgroup(pp
, '(')
522 pp
.pretty(me
.x
); pp
.text(','); pp
.breakable()
524 pp
.end_group(ind
, ')')
525 _augment(ECPtCurve
, _tmp
)
527 ###--------------------------------------------------------------------------
531 def __repr__(me
): return '%s(%d)' %
(_clsname(me
), me
.default
)
532 def check(me
, sz
): return True
533 def best(me
, sz
): return sz
534 _augment(KeySZAny
, _tmp
)
538 return '%s(%d, %d, %d, %d)' % \
539 (_clsname(me
), me
.default
, me
.min, me
.max, me
.mod
)
540 def _repr_pretty_(me
, pp
, cyclep
):
541 ind
= _pp_bgroup_tyname(pp
, me
)
545 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
546 pp
.pretty(me
.min); pp
.text(','); pp
.breakable()
547 pp
.pretty(me
.max); pp
.text(','); pp
.breakable()
549 pp
.end_group(ind
, ')')
550 def check(me
, sz
): return me
.min <= sz
<= me
.max and sz % me
.mod
== 0
552 if sz
< me
.min: raise ValueError, 'key too small'
553 elif sz
> me
.max: return me
.max
554 else: return sz
- (sz % me
.mod
)
555 _augment(KeySZRange
, _tmp
)
558 def __repr__(me
): return '%s(%d, %s)' %
(_clsname(me
), me
.default
, me
.set)
559 def _repr_pretty_(me
, pp
, cyclep
):
560 ind
= _pp_bgroup_tyname(pp
, me
)
564 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
565 ind1
= _pp_bgroup(pp
, '{')
566 _pp_commas(pp
, pp
.pretty
, me
.set)
567 pp
.end_group(ind1
, '}')
568 pp
.end_group(ind
, ')')
569 def check(me
, sz
): return sz
in me
.set
573 if found
< i
<= sz
: found
= i
574 if found
< 0: raise ValueError, 'key too small'
576 _augment(KeySZSet
, _tmp
)
578 ###--------------------------------------------------------------------------
579 ### Key data objects.
582 def __repr__(me
): return '%s(%r)' %
(_clsname(me
), me
.name
)
583 _augment(KeyFile
, _tmp
)
586 def __repr__(me
): return '%s(%r)' %
(_clsname(me
), me
.fulltag
)
591 return '%s({%s})' %
(_clsname(me
),
592 ', '.join(['%r: %r' % kv
for kv
in me
.iteritems()]))
593 def _repr_pretty_(me
, pp
, cyclep
):
594 ind
= _pp_bgroup_tyname(pp
, me
)
595 if cyclep
: pp
.text('...')
596 else: _pp_dict(pp
, me
.iteritems())
597 pp
.end_group(ind
, ')')
598 _augment(KeyAttributes
, _tmp
)
602 return '%s(%s, %r)' %
(_clsname(me
),
603 _repr_secret(me
._guts(),
604 not (me
.flags
& KF_NONSECRET
)),
605 me
.writeflags(me
.flags
))
606 def _repr_pretty_(me
, pp
, cyclep
):
607 ind
= _pp_bgroup_tyname(pp
, me
)
611 _pp_secret(pp
, me
._guts(), not (me
.flags
& KF_NONSECRET
))
612 pp
.text(','); pp
.breakable()
613 pp
.pretty(me
.writeflags(me
.flags
))
614 pp
.end_group(ind
, ')')
615 _augment(KeyData
, _tmp
)
618 def _guts(me
): return me
.bin
619 _augment(KeyDataBinary
, _tmp
)
622 def _guts(me
): return me
.ct
623 _augment(KeyDataEncrypted
, _tmp
)
626 def _guts(me
): return me
.mp
627 _augment(KeyDataMP
, _tmp
)
630 def _guts(me
): return me
.str
631 _augment(KeyDataString
, _tmp
)
634 def _guts(me
): return me
.ecpt
635 _augment(KeyDataECPt
, _tmp
)
639 return '%s({%s})' %
(_clsname(me
),
640 ', '.join(['%r: %r' % kv
for kv
in me
.iteritems()]))
641 def _repr_pretty_(me
, pp
, cyclep
):
642 ind
= _pp_bgroup_tyname(pp
, me
, '({ ')
643 if cyclep
: pp
.text('...')
644 else: _pp_dict(pp
, me
.iteritems())
645 pp
.end_group(ind
, ' })')
646 _augment(KeyDataStructured
, _tmp
)
648 ###--------------------------------------------------------------------------
653 return '%s(p = %s, r = %s, g = %s)' %
(_clsname(me
), me
.p
, me
.r
, me
.g
)
654 def _repr_pretty_(me
, pp
, cyclep
):
655 ind
= _pp_bgroup_tyname(pp
, me
)
659 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
660 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
661 _pp_kv(pp
, 'g', me
.g
)
662 pp
.end_group(ind
, ')')
663 _augment(FGInfo
, _tmp
)
666 def group(me
): return PrimeGroup(me
)
667 _augment(DHInfo
, _tmp
)
670 def group(me
): return BinGroup(me
)
671 _augment(BinDHInfo
, _tmp
)
675 return '%s(%r)' %
(_clsname(me
), me
.info
)
676 def _repr_pretty_(me
, pp
, cyclep
):
677 ind
= _pp_bgroup_tyname(pp
, me
)
678 if cyclep
: pp
.text('...')
679 else: pp
.pretty(me
.info
)
680 pp
.end_group(ind
, ')')
681 _augment(Group
, _tmp
)
688 h ^
= 2*hash(info
.r
) & 0xffffffff
689 h ^
= 5*hash(info
.g
) & 0xffffffff
691 def _get_geval(me
, x
): return MP(x
)
692 _augment(PrimeGroup
, _tmp
)
699 h ^
= 2*hash(info
.r
) & 0xffffffff
700 h ^
= 5*hash(info
.g
) & 0xffffffff
702 def _get_geval(me
, x
): return GF(x
)
703 _augment(BinGroup
, _tmp
)
706 def __hash__(me
): return 0x0ec23dab ^
hash(me
.info
)
707 def _get_geval(me
, x
): return x
.toec()
708 _augment(ECGroup
, _tmp
)
712 return '%r(%r)' %
(me
.group
, str(me
))
713 def _repr_pretty_(me
, pp
, cyclep
):
714 pp
.pretty(type(me
)._get_geval(me
))
717 ###--------------------------------------------------------------------------
718 ### RSA encoding techniques.
720 class PKCS1Crypt (object):
721 def __init__(me
, ep
= '', rng
= rand
):
724 def encode(me
, msg
, nbits
):
725 return _base
._p1crypt_encode(msg
, nbits
, me
.ep
, me
.rng
)
726 def decode(me
, ct
, nbits
):
727 return _base
._p1crypt_decode(ct
, nbits
, me
.ep
, me
.rng
)
729 class PKCS1Sig (object):
730 def __init__(me
, ep
= '', rng
= rand
):
733 def encode(me
, msg
, nbits
):
734 return _base
._p1sig_encode(msg
, nbits
, me
.ep
, me
.rng
)
735 def decode(me
, msg
, sig
, nbits
):
736 return _base
._p1sig_decode(msg
, sig
, nbits
, me
.ep
, me
.rng
)
739 def __init__(me
, mgf
= sha_mgf
, hash = sha
, ep
= '', rng
= rand
):
744 def encode(me
, msg
, nbits
):
745 return _base
._oaep_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
746 def decode(me
, ct
, nbits
):
747 return _base
._oaep_decode(ct
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
750 def __init__(me
, mgf
= sha_mgf
, hash = sha
, saltsz
= None, rng
= rand
):
757 def encode(me
, msg
, nbits
):
758 return _base
._pss_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
759 def decode(me
, msg
, sig
, nbits
):
760 return _base
._pss_decode(msg
, sig
, nbits
,
761 me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
764 def encrypt(me
, msg
, enc
):
765 return me
.pubop(enc
.encode(msg
, me
.n
.nbits
))
766 def verify(me
, msg
, sig
, enc
):
767 if msg
is None: return enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
769 x
= enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
770 return x
is None or x
== msg
774 return '%s(n = %r, e = %r)' %
(_clsname(me
), me
.n
, me
.e
)
775 def _repr_pretty_(me
, pp
, cyclep
):
776 ind
= _pp_bgroup_tyname(pp
, me
)
780 _pp_kv(pp
, 'n', me
.n
); pp
.text(','); pp
.breakable()
781 _pp_kv(pp
, 'e', me
.e
)
782 pp
.end_group(ind
, ')')
783 _augment(RSAPub
, _tmp
)
786 def decrypt(me
, ct
, enc
): return enc
.decode(me
.privop(ct
), me
.n
.nbits
)
787 def sign(me
, msg
, enc
): return me
.privop(enc
.encode(msg
, me
.n
.nbits
))
789 return '%s(n = %r, e = %r, d = %s, ' \
790 'p = %s, q = %s, dp = %s, dq = %s, q_inv = %s)' % \
791 (_clsname(me
), me
.n
, me
.e
,
792 _repr_secret(me
.d
), _repr_secret(me
.p
), _repr_secret(me
.q
),
793 _repr_secret(me
.dp
), _repr_secret(me
.dq
), _repr_secret(me
.q_inv
))
794 def _repr_pretty_(me
, pp
, cyclep
):
795 ind
= _pp_bgroup_tyname(pp
, me
)
799 _pp_kv(pp
, 'n', me
.n
); pp
.text(','); pp
.breakable()
800 _pp_kv(pp
, 'e', me
.e
); pp
.text(','); pp
.breakable()
801 _pp_kv(pp
, 'd', me
.d
, secretp
= True); pp
.text(','); pp
.breakable()
802 _pp_kv(pp
, 'p', me
.p
, secretp
= True); pp
.text(','); pp
.breakable()
803 _pp_kv(pp
, 'q', me
.q
, secretp
= True); pp
.text(','); pp
.breakable()
804 _pp_kv(pp
, 'dp', me
.dp
, secretp
= True); pp
.text(','); pp
.breakable()
805 _pp_kv(pp
, 'dq', me
.dq
, secretp
= True); pp
.text(','); pp
.breakable()
806 _pp_kv(pp
, 'q_inv', me
.q_inv
, secretp
= True)
807 pp
.end_group(ind
, ')')
808 _augment(RSAPriv
, _tmp
)
810 ###--------------------------------------------------------------------------
811 ### DSA and related schemes.
814 def __repr__(me
): return '%s(G = %r, p = %r)' %
(_clsname(me
), me
.G
, me
.p
)
815 def _repr_pretty_(me
, pp
, cyclep
):
816 ind
= _pp_bgroup_tyname(pp
, me
)
820 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
821 _pp_kv(pp
, 'p', me
.p
)
822 pp
.end_group(ind
, ')')
823 _augment(DSAPub
, _tmp
)
824 _augment(KCDSAPub
, _tmp
)
827 def __repr__(me
): return '%s(G = %r, u = %s, p = %r)' % \
828 (_clsname(me
), me
.G
, _repr_secret(me
.u
), me
.p
)
829 def _repr_pretty_(me
, pp
, cyclep
):
830 ind
= _pp_bgroup_tyname(pp
, me
)
834 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
835 _pp_kv(pp
, 'u', me
.u
, True); pp
.text(','); pp
.breakable()
836 _pp_kv(pp
, 'p', me
.p
)
837 pp
.end_group(ind
, ')')
838 _augment(DSAPriv
, _tmp
)
839 _augment(KCDSAPriv
, _tmp
)
841 ###--------------------------------------------------------------------------
842 ### Bernstein's elliptic curve crypto and related schemes.
844 X25519_BASE
= MP(9).storel(32)
845 X448_BASE
= MP(5).storel(56)
847 Z128
= ByteString
.zero(16)
849 class _BasePub (object):
850 def __init__(me
, pub
, *args
, **kw
):
851 if not me
._PUBSZ
.check(len(pub
)): raise ValueError, 'bad public key'
852 super(_BasePub
, me
).__init__(*args
, **kw
)
854 def __repr__(me
): return '%s(pub = %r)' %
(_clsname(me
), me
.pub
)
855 def _pp(me
, pp
): _pp_kv(pp
, 'pub', me
.pub
)
856 def _repr_pretty_(me
, pp
, cyclep
):
857 ind
= _pp_bgroup_tyname(pp
, me
)
858 if cyclep
: pp
.text('...')
860 pp
.end_group(ind
, ')')
862 class _BasePriv (object):
863 def __init__(me
, priv
, pub
= None, *args
, **kw
):
864 if not me
._KEYSZ
.check(len(priv
)): raise ValueError, 'bad private key'
865 if pub
is None: pub
= me
._pubkey(priv
)
866 super(_BasePriv
, me
).__init__(pub
= pub
, *args
, **kw
)
869 def generate(cls
, rng
= rand
):
870 return cls(rng
.block(cls
._KEYSZ
.default
))
872 return '%s(priv = %d, pub = %r)' % \
873 (_clsname(me
), _repr_secret(me
.priv
), me
.pub
)
875 _pp_kv(pp
, 'priv', me
.priv
, secretp
= True); pp
.text(','); pp
.breakable()
876 super(_BasePriv
, me
)._pp(pp
)
878 class _XDHPub (_BasePub
): pass
880 class _XDHPriv (_BasePriv
):
881 def _pubkey(me
, priv
): return me
._op(priv
, me
._BASE
)
882 def agree(me
, you
): return me
._op(me
.priv
, you
.pub
)
883 def boxkey(me
, recip
): return me
._hashkey(me
.agree(recip
))
884 def box(me
, recip
, n
, m
): return secret_box(me
.boxkey(recip
), n
, m
)
885 def unbox(me
, recip
, n
, c
): return secret_unbox(me
.boxkey(recip
), n
, c
)
887 class X25519Pub (_XDHPub
):
888 _PUBSZ
= KeySZSet(X25519_PUBSZ
)
891 class X25519Priv (_XDHPriv
, X25519Pub
):
892 _KEYSZ
= KeySZSet(X25519_KEYSZ
)
893 def _op(me
, k
, X
): return x25519(k
, X
)
894 def _hashkey(me
, z
): return hsalsa20_prf(z
, Z128
)
896 class X448Pub (_XDHPub
):
897 _PUBSZ
= KeySZSet(X448_PUBSZ
)
900 class X448Priv (_XDHPriv
, X448Pub
):
901 _KEYSZ
= KeySZSet(X448_KEYSZ
)
902 def _op(me
, k
, X
): return x448(k
, X
)
903 def _hashkey(me
, z
): return Shake256().hash(z
).done(salsa20
.keysz
.default
)
905 class _EdDSAPub (_BasePub
):
906 def beginhash(me
): return me
._HASH()
907 def endhash(me
, h
): return h
.done()
909 class _EdDSAPriv (_BasePriv
, _EdDSAPub
):
912 class Ed25519Pub (_EdDSAPub
):
913 _PUBSZ
= KeySZSet(ED25519_PUBSZ
)
915 def verify(me
, msg
, sig
, **kw
):
916 return ed25519_verify(me
.pub
, msg
, sig
, **kw
)
918 class Ed25519Priv (_EdDSAPriv
, Ed25519Pub
):
919 _KEYSZ
= KeySZAny(ED25519_KEYSZ
)
920 def _pubkey(me
, priv
): return ed25519_pubkey(priv
)
921 def sign(me
, msg
, **kw
):
922 return ed25519_sign(me
.priv
, msg
, pub
= me
.pub
, **kw
)
924 class Ed448Pub (_EdDSAPub
):
925 _PUBSZ
= KeySZSet(ED448_PUBSZ
)
927 def verify(me
, msg
, sig
, **kw
):
928 return ed448_verify(me
.pub
, msg
, sig
, **kw
)
930 class Ed448Priv (_EdDSAPriv
, Ed448Pub
):
931 _KEYSZ
= KeySZAny(ED448_KEYSZ
)
932 def _pubkey(me
, priv
): return ed448_pubkey(priv
)
933 def sign(me
, msg
, **kw
):
934 return ed448_sign(me
.priv
, msg
, pub
= me
.pub
, **kw
)
936 ###--------------------------------------------------------------------------
937 ### Built-in named curves and prime groups.
939 class _groupmap (object):
940 def __init__(me
, map, nth
):
943 me
._n
= max(map.values()) + 1
946 return '{%s}' %
', '.join(['%r: %r' % kv
for kv
in me
.iteritems()])
947 def _repr_pretty_(me
, pp
, cyclep
):
948 ind
= _pp_bgroup(pp
, '{ ')
949 if cyclep
: pp
.text('...')
950 else: _pp_dict(pp
, me
.iteritems())
951 pp
.end_group(ind
, ' }')
954 def __contains__(me
, k
):
956 def __getitem__(me
, k
):
961 def __setitem__(me
, k
, v
):
962 raise TypeError, "immutable object"
974 return [k
for k
in me
]
976 return [me
[k
] for k
in me
]
978 return [(k
, me
[k
]) for k
in me
]
979 eccurves
= _groupmap(_base
._eccurves
, ECInfo
._curven
)
980 primegroups
= _groupmap(_base
._pgroups
, DHInfo
._groupn
)
981 bingroups
= _groupmap(_base
._bingroups
, BinDHInfo
._groupn
)
983 ###--------------------------------------------------------------------------
984 ### Prime number generation.
986 class PrimeGenEventHandler (object):
987 def pg_begin(me
, ev
):
991 def pg_abort(me
, ev
):
998 class SophieGermainStepJump (object):
999 def pg_begin(me
, ev
):
1000 me
.lf
= PrimeFilter(ev
.x
)
1001 me
.hf
= me
.lf
.muladd(2, 1)
1007 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
1009 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
1012 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
1015 def pg_done(me
, ev
):
1019 class SophieGermainStepper (SophieGermainStepJump
):
1020 def __init__(me
, step
):
1024 me
.lf
.step(me
.lstep
)
1025 me
.hf
.step(me
.hstep
)
1027 class SophieGermainJumper (SophieGermainStepJump
):
1028 def __init__(me
, jump
):
1029 me
.ljump
= PrimeFilter(jump
);
1030 me
.hjump
= me
.ljump
.muladd(2, 0)
1032 me
.lf
.jump(me
.ljump
)
1033 me
.hf
.jump(me
.hjump
)
1034 def pg_done(me
, ev
):
1037 SophieGermainStepJump
.pg_done(me
, ev
)
1039 class SophieGermainTester (object):
1042 def pg_begin(me
, ev
):
1043 me
.lr
= RabinMiller(ev
.x
)
1044 me
.hr
= RabinMiller(2 * ev
.x
+ 1)
1046 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
1047 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
1049 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
1050 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
1052 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
1055 def pg_done(me
, ev
):
1059 class PrimitiveStepper (PrimeGenEventHandler
):
1065 def pg_begin(me
, ev
):
1066 me
.i
= iter(smallprimes
)
1067 return me
.pg_try(ev
)
1069 class PrimitiveTester (PrimeGenEventHandler
):
1070 def __init__(me
, mod
, hh
= [], exp
= None):
1071 me
.mod
= MPMont(mod
)
1076 if me
.exp
is not None:
1077 x
= me
.mod
.exp(x
, me
.exp
)
1078 if x
== 1: return PGEN_FAIL
1080 if me
.mod
.exp(x
, h
) == 1: return PGEN_FAIL
1084 class SimulStepper (PrimeGenEventHandler
):
1085 def __init__(me
, mul
= 2, add
= 1, step
= 2):
1089 def _stepfn(me
, step
):
1091 raise ValueError, 'step must be positive'
1093 return lambda f
: f
.step(step
)
1094 j
= PrimeFilter(step
)
1095 return lambda f
: f
.jump(j
)
1096 def pg_begin(me
, ev
):
1098 me
.lf
= PrimeFilter(x
)
1099 me
.hf
= PrimeFilter(x
* me
.mul
+ me
.add
)
1100 me
.lstep
= me
._stepfn(me
.step
)
1101 me
.hstep
= me
._stepfn(me
.step
* me
.mul
)
1102 SimulStepper
._cont(me
, ev
)
1110 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
1112 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
1115 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
1118 def pg_done(me
, ev
):
1124 class SimulTester (PrimeGenEventHandler
):
1125 def __init__(me
, mul
= 2, add
= 1):
1128 def pg_begin(me
, ev
):
1130 me
.lr
= RabinMiller(x
)
1131 me
.hr
= RabinMiller(x
* me
.mul
+ me
.add
)
1133 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
1134 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
1136 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
1137 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
1139 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
1142 def pg_done(me
, ev
):
1146 def sgprime(start
, step
= 2, name
= 'p', event
= pgen_nullev
, nsteps
= 0):
1148 return pgen(start
, name
, SimulStepper(step
= step
), SimulTester(), event
,
1149 nsteps
, RabinMiller
.iters(start
.nbits
))
1151 def findprimitive(mod
, hh
= [], exp
= None, name
= 'g', event
= pgen_nullev
):
1152 return pgen(0, name
, PrimitiveStepper(), PrimitiveTester(mod
, hh
, exp
),
1155 def kcdsaprime(pbits
, qbits
, rng
= rand
,
1156 event
= pgen_nullev
, name
= 'p', nsteps
= 0):
1157 hbits
= pbits
- qbits
1158 h
= pgen(rng
.mp(hbits
, 1), name
+ ' [h]',
1159 PrimeGenStepper(2), PrimeGenTester(),
1160 event
, nsteps
, RabinMiller
.iters(hbits
))
1161 q
= pgen(rng
.mp(qbits
, 1), name
, SimulStepper(2 * h
, 1, 2),
1162 SimulTester(2 * h
, 1), event
, nsteps
, RabinMiller
.iters(qbits
))
1166 #----- That's all, folks ----------------------------------------------------