c0cb1abaea1f0d17374271817690e87bb48b6661
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
29 import types
as _types
30 from binascii
import hexlify
as _hexify
, unhexlify
as _unhexify
31 from contextlib
import contextmanager
as _ctxmgr
32 from sys
import argv
as _argv
33 from struct
import pack
as _pack
35 ###--------------------------------------------------------------------------
38 ## For the benefit of the default keyreporter, we need the program na,e.
41 ## How to fix a name back into the right identifier. Alas, the rules are not
45 ## Hyphens consistently become underscores.
46 name
= name
.replace('-', '_')
48 ## But slashes might become underscores or just vanish.
49 if name
.startswith('salsa20'): name
= name
.replace('/', '')
50 else: name
= name
.replace('/', '_')
55 ## Initialize the module. Drag in the static methods of the various
56 ## classes; create names for the various known crypto algorithms.
63 for i
in ['ByteString',
65 'ECPt', 'ECPtCurve', 'ECCurve', 'ECInfo',
66 'DHInfo', 'BinDHInfo', 'RSAPriv', 'BBSPriv',
67 'PrimeFilter', 'RabinMiller',
75 setattr(c
, j
[plen
:], classmethod(b
[j
]))
76 for i
in [gcciphers
, gchashes
, gcmacs
, gcprps
]:
77 for c
in i
.itervalues():
78 d
[_fixname(c
.name
)] = c
79 for c
in gccrands
.itervalues():
80 d
[_fixname(c
.name
+ 'rand')] = c
83 ## A handy function for our work: add the methods of a named class to an
84 ## existing class. This is how we write the Python-implemented parts of our
89 if type(a
) is _types
.MethodType
:
91 elif type(a
) not in (_types
.FunctionType
, staticmethod, classmethod):
95 ## Parsing functions tend to return the object parsed and the remainder of
96 ## the input. This checks that the remainder is input and, if so, returns
101 raise SyntaxError, 'junk at end of string'
104 ## Some pretty-printing utilities.
105 PRINT_SECRETS
= False
106 def _clsname(me
): return type(me
).__name__
107 def _repr_secret(thing
, secretp
= True):
108 if not secretp
or PRINT_SECRETS
: return repr(thing
)
109 else: return '#<SECRET>'
110 def _pp_str(me
, pp
, cyclep
): pp
.text(cyclep
and '...' or str(me
))
111 def _pp_secret(pp
, thing
, secretp
= True):
112 if not secretp
or PRINT_SECRETS
: pp
.pretty(thing
)
113 else: pp
.text('#<SECRET>')
114 def _pp_bgroup(pp
, text
):
116 pp
.begin_group(ind
, text
)
118 def _pp_bgroup_tyname(pp
, obj
, open = '('):
119 return _pp_bgroup(pp
, _clsname(obj
) + open)
120 def _pp_kv(pp
, k
, v
, secretp
= False):
121 ind
= _pp_bgroup(pp
, k
+ ' = ')
122 _pp_secret(pp
, v
, secretp
)
123 pp
.end_group(ind
, '')
124 def _pp_commas(pp
, printfn
, items
):
127 if firstp
: firstp
= False
128 else: pp
.text(','); pp
.breakable()
130 def _pp_dict(pp
, items
):
140 _pp_commas(pp
, p
, items
)
142 ###--------------------------------------------------------------------------
147 return ByteString(_unhexify(x
))
148 fromhex
= staticmethod(fromhex
)
152 return 'bytes(%r)' %
hex(me
)
153 _augment(ByteString
, _tmp
)
154 ByteString
.__hash__
= str.__hash__
155 bytes
= ByteString
.fromhex
157 ###--------------------------------------------------------------------------
163 return ctstreq(h
, hh
)
164 _augment(GHash
, _tmp
)
165 _augment(Poly1305Hash
, _tmp
)
167 class _HashBase (object):
168 ## The standard hash methods. Assume that `hash' is defined and returns
170 def hashu8(me
, n
): return me
.hash(_pack('B', n
))
171 def hashu16l(me
, n
): return me
.hash(_pack('<H', n
))
172 def hashu16b(me
, n
): return me
.hash(_pack('>H', n
))
174 def hashu32l(me
, n
): return me
.hash(_pack('<L', n
))
175 def hashu32b(me
, n
): return me
.hash(_pack('>L', n
))
177 def hashu64l(me
, n
): return me
.hash(_pack('<Q', n
))
178 def hashu64b(me
, n
): return me
.hash(_pack('>Q', n
))
180 def hashbuf8(me
, s
): return me
.hashu8(len(s
)).hash(s
)
181 def hashbuf16l(me
, s
): return me
.hashu16l(len(s
)).hash(s
)
182 def hashbuf16b(me
, s
): return me
.hashu16b(len(s
)).hash(s
)
183 hashbuf16
= hashbuf16b
184 def hashbuf32l(me
, s
): return me
.hashu32l(len(s
)).hash(s
)
185 def hashbuf32b(me
, s
): return me
.hashu32b(len(s
)).hash(s
)
186 hashbuf32
= hashbuf32b
187 def hashbuf64l(me
, s
): return me
.hashu64l(len(s
)).hash(s
)
188 def hashbuf64b(me
, s
): return me
.hashu64b(len(s
)).hash(s
)
189 hashbuf64
= hashbuf64b
190 def hashstrz(me
, s
): return me
.hash(s
).hashu8(0)
192 class _ShakeBase (_HashBase
):
194 ## Python gets really confused if I try to augment `__new__' on native
195 ## classes, so wrap and delegate. Sorry.
196 def __init__(me
, perso
= '', *args
, **kw
):
197 super(_ShakeBase
, me
).__init__(*args
, **kw
)
198 me
._h
= me
._SHAKE(perso
= perso
, func
= me
._FUNC
)
200 ## Delegate methods...
201 def copy(me
): new
= me
.__class__(); new
._copy(me
)
202 def _copy(me
, other
): me
._h
= other
._h
203 def hash(me
, m
): me
._h
.hash(m
); return me
204 def xof(me
): me
._h
.xof(); return me
205 def get(me
, n
): return me
._h
.get(n
)
206 def mask(me
, m
): return me
._h
.mask(m
)
207 def done(me
, n
): return me
._h
.done(n
)
208 def check(me
, h
): return ctstreq(h
, me
.done(len(h
)))
210 def state(me
): return me
._h
.state
212 def buffered(me
): return me
._h
.buffered
214 def rate(me
): return me
._h
.rate
218 return ctstreq(h
, me
.done(len(h
)))
221 return me
.hashu8(len(nn
)).hash(nn
)
224 return me
.hash(nn
).hashu8(len(nn
))
225 def stringenc(me
, str):
226 return me
.leftenc(8*len(str)).hash(str)
227 def bytepad_before(me
):
228 return me
.leftenc(me
.rate
)
229 def bytepad_after(me
):
230 if me
.buffered
: me
.hash(me
._Z
[:me
.rate
- me
.buffered
])
237 _augment(Shake
, _tmp
)
238 _augment(_ShakeBase
, _tmp
)
239 Shake
._Z
= _ShakeBase
._Z
= ByteString(200*'\0')
241 class KMAC (_ShakeBase
):
243 def __init__(me
, k
, *arg
, **kw
):
244 super(KMAC
, me
).__init__(*arg
, **kw
)
245 with me
.bytepad(): me
.stringenc(k
)
246 def done(me
, n
= -1):
247 if n
< 0: n
= me
._TAGSZ
249 return super(KMAC
, me
).done(n
)
252 return super(KMAC
, me
).xof()
254 class KMAC128 (KMAC
): _SHAKE
= Shake128
; _TAGSZ
= 16
255 class KMAC256 (KMAC
): _SHAKE
= Shake256
; _TAGSZ
= 32
257 ###--------------------------------------------------------------------------
258 ### NaCl `secretbox'.
260 def secret_box(k
, n
, m
):
261 E
= xsalsa20(k
).setiv(n
)
262 r
= E
.enczero(poly1305
.keysz
.default
)
263 s
= E
.enczero(poly1305
.masksz
)
265 t
= poly1305(r
)(s
).hash(y
).done()
266 return ByteString(t
+ y
)
268 def secret_unbox(k
, n
, c
):
269 E
= xsalsa20(k
).setiv(n
)
270 r
= E
.enczero(poly1305
.keysz
.default
)
271 s
= E
.enczero(poly1305
.masksz
)
272 y
= c
[poly1305
.tagsz
:]
273 if not poly1305(r
)(s
).hash(y
).check(c
[0:poly1305
.tagsz
]):
274 raise ValueError, 'decryption failed'
275 return E
.decrypt(c
[poly1305
.tagsz
:])
277 ###--------------------------------------------------------------------------
278 ### Multiprecision integers and binary polynomials.
281 if isinstance(x
, BaseRat
): return x
._n
, x
._d
283 class BaseRat (object):
284 """Base class implementing fields of fractions over Euclidean domains."""
285 def __new__(cls
, a
, b
):
286 a
, b
= cls
.RING(a
), cls
.RING(b
)
290 me
= super(BaseRat
, cls
).__new__(cls
)
295 def numer(me
): return me
._n
297 def denom(me
): return me
._d
298 def __str__(me
): return '%s/%s' %
(me
._n
, me
._d
)
299 def __repr__(me
): return '%s(%s, %s)' %
(_clsname(me
), me
._n
, me
._d
)
300 _repr_pretty_
= _pp_str
302 def __add__(me
, you
):
303 n
, d
= _split_rat(you
)
304 return type(me
)(me
._n
*d
+ n
*me
._d
, d
*me
._d
)
306 def __sub__(me
, you
):
307 n
, d
= _split_rat(you
)
308 return type(me
)(me
._n
*d
- n
*me
._d
, d
*me
._d
)
309 def __rsub__(me
, you
):
310 n
, d
= _split_rat(you
)
311 return type(me
)(n
*me
._d
- me
._n
*d
, d
*me
._d
)
312 def __mul__(me
, you
):
313 n
, d
= _split_rat(you
)
314 return type(me
)(me
._n
*n
, me
._d
*d
)
315 def __div__(me
, you
):
316 n
, d
= _split_rat(you
)
317 return type(me
)(me
._n
*d
, me
._d
*n
)
318 def __rdiv__(me
, you
):
319 n
, d
= _split_rat(you
)
320 return type(me
)(me
._d
*n
, me
._n
*d
)
321 def __cmp__(me
, you
):
322 n
, d
= _split_rat(you
)
323 return cmp(me
._n
*d
, n
*me
._d
)
324 def __rcmp__(me
, you
):
325 n
, d
= _split_rat(you
)
326 return cmp(n
*me
._d
, me
._n
*d
)
328 class IntRat (BaseRat
):
331 class GFRat (BaseRat
):
335 def negp(x
): return x
< 0
336 def posp(x
): return x
> 0
337 def zerop(x
): return x
== 0
338 def oddp(x
): return x
.testbit(0)
339 def evenp(x
): return not x
.testbit(0)
340 def mont(x
): return MPMont(x
)
341 def barrett(x
): return MPBarrett(x
)
342 def reduce(x
): return MPReduce(x
)
343 def __div__(me
, you
): return IntRat(me
, you
)
344 def __rdiv__(me
, you
): return IntRat(you
, me
)
345 _repr_pretty_
= _pp_str
349 def zerop(x
): return x
== 0
350 def reduce(x
): return GFReduce(x
)
351 def trace(x
, y
): return x
.reduce().trace(y
)
352 def halftrace(x
, y
): return x
.reduce().halftrace(y
)
353 def modsqrt(x
, y
): return x
.reduce().sqrt(y
)
354 def quadsolve(x
, y
): return x
.reduce().quadsolve(y
)
355 def __div__(me
, you
): return GFRat(me
, you
)
356 def __rdiv__(me
, you
): return GFRat(you
, me
)
357 _repr_pretty_
= _pp_str
362 'product(ITERABLE) or product(I, ...) -> PRODUCT'
363 return MPMul(*arg
).done()
364 product
= staticmethod(product
)
365 _augment(MPMul
, _tmp
)
367 ###--------------------------------------------------------------------------
371 def fromstring(str): return _checkend(Field
.parse(str))
372 fromstring
= staticmethod(fromstring
)
373 _augment(Field
, _tmp
)
376 def __repr__(me
): return '%s(%sL)' %
(_clsname(me
), me
.p
)
377 def __hash__(me
): return 0x114401de ^
hash(me
.p
)
378 def _repr_pretty_(me
, pp
, cyclep
):
379 ind
= _pp_bgroup_tyname(pp
, me
)
380 if cyclep
: pp
.text('...')
381 else: pp
.pretty(me
.p
)
382 pp
.end_group(ind
, ')')
383 def ec(me
, a
, b
): return ECPrimeProjCurve(me
, a
, b
)
384 _augment(PrimeField
, _tmp
)
387 def __repr__(me
): return '%s(%#xL)' %
(_clsname(me
), me
.p
)
388 def ec(me
, a
, b
): return ECBinProjCurve(me
, a
, b
)
389 def _repr_pretty_(me
, pp
, cyclep
):
390 ind
= _pp_bgroup_tyname(pp
, me
)
391 if cyclep
: pp
.text('...')
392 else: pp
.text('%#x' % me
.p
)
393 pp
.end_group(ind
, ')')
394 _augment(BinField
, _tmp
)
397 def __hash__(me
): return 0x23e4701c ^
hash(me
.p
)
398 _augment(BinPolyField
, _tmp
)
404 h ^
= 2*hash(me
.beta
) & 0xffffffff
406 _augment(BinNormField
, _tmp
)
409 def __str__(me
): return str(me
.value
)
410 def __repr__(me
): return '%s(%s)' %
(repr(me
.field
), repr(me
.value
))
411 _repr_pretty_
= _pp_str
414 ###--------------------------------------------------------------------------
419 return '%s(%r, %s, %s)' %
(_clsname(me
), me
.field
, me
.a
, me
.b
)
420 def _repr_pretty_(me
, pp
, cyclep
):
421 ind
= _pp_bgroup_tyname(pp
, me
)
425 pp
.pretty(me
.field
); pp
.text(','); pp
.breakable()
426 pp
.pretty(me
.a
); pp
.text(','); pp
.breakable()
428 pp
.end_group(ind
, ')')
430 return ecpt
.frombuf(me
, s
)
432 return ecpt
.fromraw(me
, s
)
435 _augment(ECCurve
, _tmp
)
441 h ^
= 2*hash(me
.a
) ^
0xffffffff
442 h ^
= 5*hash(me
.b
) ^
0xffffffff
444 _augment(ECPrimeCurve
, _tmp
)
450 h ^
= 2*hash(me
.a
) ^
0xffffffff
451 h ^
= 5*hash(me
.b
) ^
0xffffffff
453 _augment(ECBinCurve
, _tmp
)
457 if not me
: return '%s()' %
_clsname(me
)
458 return '%s(%s, %s)' %
(_clsname(me
), me
.ix
, me
.iy
)
460 if not me
: return 'inf'
461 return '(%s, %s)' %
(me
.ix
, me
.iy
)
462 def _repr_pretty_(me
, pp
, cyclep
):
468 ind
= _pp_bgroup(pp
, '(')
469 pp
.pretty(me
.ix
); pp
.text(','); pp
.breakable()
471 pp
.end_group(ind
, ')')
476 return '%s(curve = %r, G = %r, r = %s, h = %s)' % \
477 (_clsname(me
), me
.curve
, me
.G
, me
.r
, me
.h
)
478 def _repr_pretty_(me
, pp
, cyclep
):
479 ind
= _pp_bgroup_tyname(pp
, me
)
483 _pp_kv(pp
, 'curve', me
.curve
); pp
.text(','); pp
.breakable()
484 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
485 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
486 _pp_kv(pp
, 'h', me
.h
)
487 pp
.end_group(ind
, ')')
491 h ^
= 2*hash(me
.G
) & 0xffffffff
495 _augment(ECInfo
, _tmp
)
499 if not me
: return '%r()' %
(me
.curve
)
500 return '%r(%s, %s)' %
(me
.curve
, me
.x
, me
.y
)
502 if not me
: return 'inf'
503 return '(%s, %s)' %
(me
.x
, me
.y
)
504 def _repr_pretty_(me
, pp
, cyclep
):
510 ind
= _pp_bgroup(pp
, '(')
511 pp
.pretty(me
.x
); pp
.text(','); pp
.breakable()
513 pp
.end_group(ind
, ')')
514 _augment(ECPtCurve
, _tmp
)
516 ###--------------------------------------------------------------------------
520 def __repr__(me
): return '%s(%d)' %
(_clsname(me
), me
.default
)
521 def check(me
, sz
): return True
522 def best(me
, sz
): return sz
523 _augment(KeySZAny
, _tmp
)
527 return '%s(%d, %d, %d, %d)' % \
528 (_clsname(me
), me
.default
, me
.min, me
.max, me
.mod
)
529 def _repr_pretty_(me
, pp
, cyclep
):
530 ind
= _pp_bgroup_tyname(pp
, me
)
534 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
535 pp
.pretty(me
.min); pp
.text(','); pp
.breakable()
536 pp
.pretty(me
.max); pp
.text(','); pp
.breakable()
538 pp
.end_group(ind
, ')')
539 def check(me
, sz
): return me
.min <= sz
<= me
.max and sz % me
.mod
== 0
541 if sz
< me
.min: raise ValueError, 'key too small'
542 elif sz
> me
.max: return me
.max
543 else: return sz
- (sz % me
.mod
)
544 _augment(KeySZRange
, _tmp
)
547 def __repr__(me
): return '%s(%d, %s)' %
(_clsname(me
), me
.default
, me
.set)
548 def _repr_pretty_(me
, pp
, cyclep
):
549 ind
= _pp_bgroup_tyname(pp
, me
)
553 pp
.pretty(me
.default
); pp
.text(','); pp
.breakable()
554 ind1
= _pp_bgroup(pp
, '{')
555 _pp_commas(pp
, pp
.pretty
, me
.set)
556 pp
.end_group(ind1
, '}')
557 pp
.end_group(ind
, ')')
558 def check(me
, sz
): return sz
in me
.set
562 if found
< i
<= sz
: found
= i
563 if found
< 0: raise ValueError, 'key too small'
565 _augment(KeySZSet
, _tmp
)
567 ###--------------------------------------------------------------------------
568 ### Key data objects.
571 def __repr__(me
): return '%s(%r)' %
(_clsname(me
), me
.name
)
572 _augment(KeyFile
, _tmp
)
575 def __repr__(me
): return '%s(%r)' %
(_clsname(me
), me
.fulltag
)
580 return '%s({%s})' %
(_clsname(me
),
581 ', '.join(['%r: %r' % kv
for kv
in me
.iteritems()]))
582 def _repr_pretty_(me
, pp
, cyclep
):
583 ind
= _pp_bgroup_tyname(pp
, me
)
584 if cyclep
: pp
.text('...')
585 else: _pp_dict(pp
, me
.iteritems())
586 pp
.end_group(ind
, ')')
587 _augment(KeyAttributes
, _tmp
)
591 return '%s(%s, %r)' %
(_clsname(me
),
592 _repr_secret(me
._guts(),
593 not (me
.flags
& KF_NONSECRET
)),
594 me
.writeflags(me
.flags
))
595 def _repr_pretty_(me
, pp
, cyclep
):
596 ind
= _pp_bgroup_tyname(pp
, me
)
600 _pp_secret(pp
, me
._guts(), not (me
.flags
& KF_NONSECRET
))
601 pp
.text(','); pp
.breakable()
602 pp
.pretty(me
.writeflags(me
.flags
))
603 pp
.end_group(ind
, ')')
604 _augment(KeyData
, _tmp
)
607 def _guts(me
): return me
.bin
608 _augment(KeyDataBinary
, _tmp
)
611 def _guts(me
): return me
.ct
612 _augment(KeyDataEncrypted
, _tmp
)
615 def _guts(me
): return me
.mp
616 _augment(KeyDataMP
, _tmp
)
619 def _guts(me
): return me
.str
620 _augment(KeyDataString
, _tmp
)
623 def _guts(me
): return me
.ecpt
624 _augment(KeyDataECPt
, _tmp
)
628 return '%s({%s})' %
(_clsname(me
),
629 ', '.join(['%r: %r' % kv
for kv
in me
.iteritems()]))
630 def _repr_pretty_(me
, pp
, cyclep
):
631 ind
= _pp_bgroup_tyname(pp
, me
, '({ ')
632 if cyclep
: pp
.text('...')
633 else: _pp_dict(pp
, me
.iteritems())
634 pp
.end_group(ind
, ' })')
635 _augment(KeyDataStructured
, _tmp
)
637 ###--------------------------------------------------------------------------
642 return '%s(p = %s, r = %s, g = %s)' %
(_clsname(me
), me
.p
, me
.r
, me
.g
)
643 def _repr_pretty_(me
, pp
, cyclep
):
644 ind
= _pp_bgroup_tyname(pp
, me
)
648 _pp_kv(pp
, 'p', me
.p
); pp
.text(','); pp
.breakable()
649 _pp_kv(pp
, 'r', me
.r
); pp
.text(','); pp
.breakable()
650 _pp_kv(pp
, 'g', me
.g
)
651 pp
.end_group(ind
, ')')
652 _augment(FGInfo
, _tmp
)
655 def group(me
): return PrimeGroup(me
)
656 _augment(DHInfo
, _tmp
)
659 def group(me
): return BinGroup(me
)
660 _augment(BinDHInfo
, _tmp
)
664 return '%s(%r)' %
(_clsname(me
), me
.info
)
665 def _repr_pretty_(me
, pp
, cyclep
):
666 ind
= _pp_bgroup_tyname(pp
, me
)
667 if cyclep
: pp
.text('...')
668 else: pp
.pretty(me
.info
)
669 pp
.end_group(ind
, ')')
670 _augment(Group
, _tmp
)
677 h ^
= 2*hash(info
.r
) & 0xffffffff
678 h ^
= 5*hash(info
.g
) & 0xffffffff
680 def _get_geval(me
, x
): return MP(x
)
681 _augment(PrimeGroup
, _tmp
)
688 h ^
= 2*hash(info
.r
) & 0xffffffff
689 h ^
= 5*hash(info
.g
) & 0xffffffff
691 def _get_geval(me
, x
): return GF(x
)
692 _augment(BinGroup
, _tmp
)
695 def __hash__(me
): return 0x0ec23dab ^
hash(me
.info
)
696 def _get_geval(me
, x
): return x
.toec()
697 _augment(ECGroup
, _tmp
)
701 return '%r(%r)' %
(me
.group
, str(me
))
702 def _repr_pretty_(me
, pp
, cyclep
):
703 pp
.pretty(type(me
)._get_geval(me
))
706 ###--------------------------------------------------------------------------
707 ### RSA encoding techniques.
709 class PKCS1Crypt (object):
710 def __init__(me
, ep
= '', rng
= rand
):
713 def encode(me
, msg
, nbits
):
714 return _base
._p1crypt_encode(msg
, nbits
, me
.ep
, me
.rng
)
715 def decode(me
, ct
, nbits
):
716 return _base
._p1crypt_decode(ct
, nbits
, me
.ep
, me
.rng
)
718 class PKCS1Sig (object):
719 def __init__(me
, ep
= '', rng
= rand
):
722 def encode(me
, msg
, nbits
):
723 return _base
._p1sig_encode(msg
, nbits
, me
.ep
, me
.rng
)
724 def decode(me
, msg
, sig
, nbits
):
725 return _base
._p1sig_decode(msg
, sig
, nbits
, me
.ep
, me
.rng
)
728 def __init__(me
, mgf
= sha_mgf
, hash = sha
, ep
= '', rng
= rand
):
733 def encode(me
, msg
, nbits
):
734 return _base
._oaep_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
735 def decode(me
, ct
, nbits
):
736 return _base
._oaep_decode(ct
, nbits
, me
.mgf
, me
.hash, me
.ep
, me
.rng
)
739 def __init__(me
, mgf
= sha_mgf
, hash = sha
, saltsz
= None, rng
= rand
):
746 def encode(me
, msg
, nbits
):
747 return _base
._pss_encode(msg
, nbits
, me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
748 def decode(me
, msg
, sig
, nbits
):
749 return _base
._pss_decode(msg
, sig
, nbits
,
750 me
.mgf
, me
.hash, me
.saltsz
, me
.rng
)
753 def encrypt(me
, msg
, enc
):
754 return me
.pubop(enc
.encode(msg
, me
.n
.nbits
))
755 def verify(me
, msg
, sig
, enc
):
756 if msg
is None: return enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
758 x
= enc
.decode(msg
, me
.pubop(sig
), me
.n
.nbits
)
759 return x
is None or x
== msg
763 return '%s(n = %r, e = %r)' %
(_clsname(me
), me
.n
, me
.e
)
764 def _repr_pretty_(me
, pp
, cyclep
):
765 ind
= _pp_bgroup_tyname(pp
, me
)
769 _pp_kv(pp
, 'n', me
.n
); pp
.text(','); pp
.breakable()
770 _pp_kv(pp
, 'e', me
.e
)
771 pp
.end_group(ind
, ')')
772 _augment(RSAPub
, _tmp
)
775 def decrypt(me
, ct
, enc
): return enc
.decode(me
.privop(ct
), me
.n
.nbits
)
776 def sign(me
, msg
, enc
): return me
.privop(enc
.encode(msg
, me
.n
.nbits
))
778 return '%s(n = %r, e = %r, d = %s, ' \
779 'p = %s, q = %s, dp = %s, dq = %s, q_inv = %s)' % \
780 (_clsname(me
), me
.n
, me
.e
,
781 _repr_secret(me
.d
), _repr_secret(me
.p
), _repr_secret(me
.q
),
782 _repr_secret(me
.dp
), _repr_secret(me
.dq
), _repr_secret(me
.q_inv
))
783 def _repr_pretty_(me
, pp
, cyclep
):
784 ind
= _pp_bgroup_tyname(pp
, me
)
788 _pp_kv(pp
, 'n', me
.n
); pp
.text(','); pp
.breakable()
789 _pp_kv(pp
, 'e', me
.e
); pp
.text(','); pp
.breakable()
790 _pp_kv(pp
, 'd', me
.d
, secretp
= True); pp
.text(','); pp
.breakable()
791 _pp_kv(pp
, 'p', me
.p
, secretp
= True); pp
.text(','); pp
.breakable()
792 _pp_kv(pp
, 'q', me
.q
, secretp
= True); pp
.text(','); pp
.breakable()
793 _pp_kv(pp
, 'dp', me
.dp
, secretp
= True); pp
.text(','); pp
.breakable()
794 _pp_kv(pp
, 'dq', me
.dq
, secretp
= True); pp
.text(','); pp
.breakable()
795 _pp_kv(pp
, 'q_inv', me
.q_inv
, secretp
= True)
796 pp
.end_group(ind
, ')')
797 _augment(RSAPriv
, _tmp
)
799 ###--------------------------------------------------------------------------
800 ### DSA and related schemes.
803 def __repr__(me
): return '%s(G = %r, p = %r)' %
(_clsname(me
), me
.G
, me
.p
)
804 def _repr_pretty_(me
, pp
, cyclep
):
805 ind
= _pp_bgroup_tyname(pp
, me
)
809 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
810 _pp_kv(pp
, 'p', me
.p
)
811 pp
.end_group(ind
, ')')
812 _augment(DSAPub
, _tmp
)
813 _augment(KCDSAPub
, _tmp
)
816 def __repr__(me
): return '%s(G = %r, u = %s, p = %r)' % \
817 (_clsname(me
), me
.G
, _repr_secret(me
.u
), me
.p
)
818 def _repr_pretty_(me
, pp
, cyclep
):
819 ind
= _pp_bgroup_tyname(pp
, me
)
823 _pp_kv(pp
, 'G', me
.G
); pp
.text(','); pp
.breakable()
824 _pp_kv(pp
, 'u', me
.u
, True); pp
.text(','); pp
.breakable()
825 _pp_kv(pp
, 'p', me
.p
)
826 pp
.end_group(ind
, ')')
827 _augment(DSAPriv
, _tmp
)
828 _augment(KCDSAPriv
, _tmp
)
830 ###--------------------------------------------------------------------------
831 ### Bernstein's elliptic curve crypto and related schemes.
833 X25519_BASE
= MP(9).storel(32)
834 X448_BASE
= MP(5).storel(56)
836 Z128
= ByteString
.zero(16)
838 class _BasePub (object):
839 def __init__(me
, pub
, *args
, **kw
):
840 if not me
._PUBSZ
.check(len(pub
)): raise ValueError, 'bad public key'
841 super(_BasePub
, me
).__init__(*args
, **kw
)
843 def __repr__(me
): return '%s(pub = %r)' %
(_clsname(me
), me
.pub
)
844 def _pp(me
, pp
): _pp_kv(pp
, 'pub', me
.pub
)
845 def _repr_pretty_(me
, pp
, cyclep
):
846 ind
= _pp_bgroup_tyname(pp
, me
)
847 if cyclep
: pp
.text('...')
849 pp
.end_group(ind
, ')')
851 class _BasePriv (object):
852 def __init__(me
, priv
, pub
= None, *args
, **kw
):
853 if not me
._KEYSZ
.check(len(priv
)): raise ValueError, 'bad private key'
854 if pub
is None: pub
= me
._pubkey(priv
)
855 super(_BasePriv
, me
).__init__(pub
= pub
, *args
, **kw
)
858 def generate(cls
, rng
= rand
):
859 return cls(rng
.block(cls
._KEYSZ
.default
))
861 return '%s(priv = %d, pub = %r)' % \
862 (_clsname(me
), _repr_secret(me
.priv
), me
.pub
)
864 _pp_kv(pp
, 'priv', me
.priv
, secretp
= True); pp
.text(','); pp
.breakable()
865 super(_BasePriv
, me
)._pp(pp
)
867 class _XDHPub (_BasePub
): pass
869 class _XDHPriv (_BasePriv
):
870 def _pubkey(me
, priv
): return me
._op(priv
, me
._BASE
)
871 def agree(me
, you
): return me
._op(me
.priv
, you
.pub
)
872 def boxkey(me
, recip
): return me
._hashkey(me
.agree(recip
))
873 def box(me
, recip
, n
, m
): return secret_box(me
.boxkey(recip
), n
, m
)
874 def unbox(me
, recip
, n
, c
): return secret_unbox(me
.boxkey(recip
), n
, c
)
876 class X25519Pub (_XDHPub
):
877 _PUBSZ
= KeySZSet(X25519_PUBSZ
)
880 class X25519Priv (_XDHPriv
, X25519Pub
):
881 _KEYSZ
= KeySZSet(X25519_KEYSZ
)
882 def _op(me
, k
, X
): return x25519(k
, X
)
883 def _hashkey(me
, z
): return hsalsa20_prf(z
, Z128
)
885 class X448Pub (_XDHPub
):
886 _PUBSZ
= KeySZSet(X448_PUBSZ
)
889 class X448Priv (_XDHPriv
, X448Pub
):
890 _KEYSZ
= KeySZSet(X448_KEYSZ
)
891 def _op(me
, k
, X
): return x448(k
, X
)
892 def _hashkey(me
, z
): return Shake256().hash(z
).done(salsa20
.keysz
.default
)
894 class _EdDSAPub (_BasePub
):
895 def beginhash(me
): return me
._HASH()
896 def endhash(me
, h
): return h
.done()
898 class _EdDSAPriv (_BasePriv
, _EdDSAPub
):
901 class Ed25519Pub (_EdDSAPub
):
902 _PUBSZ
= KeySZSet(ED25519_PUBSZ
)
904 def verify(me
, msg
, sig
, **kw
):
905 return ed25519_verify(me
.pub
, msg
, sig
, **kw
)
907 class Ed25519Priv (_EdDSAPriv
, Ed25519Pub
):
908 _KEYSZ
= KeySZAny(ED25519_KEYSZ
)
909 def _pubkey(me
, priv
): return ed25519_pubkey(priv
)
910 def sign(me
, msg
, **kw
):
911 return ed25519_sign(me
.priv
, msg
, pub
= me
.pub
, **kw
)
913 class Ed448Pub (_EdDSAPub
):
914 _PUBSZ
= KeySZSet(ED448_PUBSZ
)
916 def verify(me
, msg
, sig
, **kw
):
917 return ed448_verify(me
.pub
, msg
, sig
, **kw
)
919 class Ed448Priv (_EdDSAPriv
, Ed448Pub
):
920 _KEYSZ
= KeySZAny(ED448_KEYSZ
)
921 def _pubkey(me
, priv
): return ed448_pubkey(priv
)
922 def sign(me
, msg
, **kw
):
923 return ed448_sign(me
.priv
, msg
, pub
= me
.pub
, **kw
)
925 ###--------------------------------------------------------------------------
926 ### Built-in named curves and prime groups.
928 class _groupmap (object):
929 def __init__(me
, map, nth
):
932 me
._n
= max(map.values()) + 1
935 return '{%s}' %
', '.join(['%r: %r' % kv
for kv
in me
.iteritems()])
936 def _repr_pretty_(me
, pp
, cyclep
):
937 ind
= _pp_bgroup(pp
, '{ ')
938 if cyclep
: pp
.text('...')
939 else: _pp_dict(pp
, me
.iteritems())
940 pp
.end_group(ind
, ' }')
943 def __contains__(me
, k
):
945 def __getitem__(me
, k
):
950 def __setitem__(me
, k
, v
):
951 raise TypeError, "immutable object"
963 return [k
for k
in me
]
965 return [me
[k
] for k
in me
]
967 return [(k
, me
[k
]) for k
in me
]
968 eccurves
= _groupmap(_base
._eccurves
, ECInfo
._curven
)
969 primegroups
= _groupmap(_base
._pgroups
, DHInfo
._groupn
)
970 bingroups
= _groupmap(_base
._bingroups
, BinDHInfo
._groupn
)
972 ###--------------------------------------------------------------------------
973 ### Prime number generation.
975 class PrimeGenEventHandler (object):
976 def pg_begin(me
, ev
):
980 def pg_abort(me
, ev
):
987 class SophieGermainStepJump (object):
988 def pg_begin(me
, ev
):
989 me
.lf
= PrimeFilter(ev
.x
)
990 me
.hf
= me
.lf
.muladd(2, 1)
996 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
998 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
1001 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
1004 def pg_done(me
, ev
):
1008 class SophieGermainStepper (SophieGermainStepJump
):
1009 def __init__(me
, step
):
1013 me
.lf
.step(me
.lstep
)
1014 me
.hf
.step(me
.hstep
)
1016 class SophieGermainJumper (SophieGermainStepJump
):
1017 def __init__(me
, jump
):
1018 me
.ljump
= PrimeFilter(jump
);
1019 me
.hjump
= me
.ljump
.muladd(2, 0)
1021 me
.lf
.jump(me
.ljump
)
1022 me
.hf
.jump(me
.hjump
)
1023 def pg_done(me
, ev
):
1026 SophieGermainStepJump
.pg_done(me
, ev
)
1028 class SophieGermainTester (object):
1031 def pg_begin(me
, ev
):
1032 me
.lr
= RabinMiller(ev
.x
)
1033 me
.hr
= RabinMiller(2 * ev
.x
+ 1)
1035 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
1036 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
1038 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
1039 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
1041 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
1044 def pg_done(me
, ev
):
1048 class PrimitiveStepper (PrimeGenEventHandler
):
1054 def pg_begin(me
, ev
):
1055 me
.i
= iter(smallprimes
)
1056 return me
.pg_try(ev
)
1058 class PrimitiveTester (PrimeGenEventHandler
):
1059 def __init__(me
, mod
, hh
= [], exp
= None):
1060 me
.mod
= MPMont(mod
)
1065 if me
.exp
is not None:
1066 x
= me
.mod
.exp(x
, me
.exp
)
1067 if x
== 1: return PGEN_FAIL
1069 if me
.mod
.exp(x
, h
) == 1: return PGEN_FAIL
1073 class SimulStepper (PrimeGenEventHandler
):
1074 def __init__(me
, mul
= 2, add
= 1, step
= 2):
1078 def _stepfn(me
, step
):
1080 raise ValueError, 'step must be positive'
1082 return lambda f
: f
.step(step
)
1083 j
= PrimeFilter(step
)
1084 return lambda f
: f
.jump(j
)
1085 def pg_begin(me
, ev
):
1087 me
.lf
= PrimeFilter(x
)
1088 me
.hf
= PrimeFilter(x
* me
.mul
+ me
.add
)
1089 me
.lstep
= me
._stepfn(me
.step
)
1090 me
.hstep
= me
._stepfn(me
.step
* me
.mul
)
1091 SimulStepper
._cont(me
, ev
)
1099 while me
.lf
.status
== PGEN_FAIL
or me
.hf
.status
== PGEN_FAIL
:
1101 if me
.lf
.status
== PGEN_ABORT
or me
.hf
.status
== PGEN_ABORT
:
1104 if me
.lf
.status
== PGEN_DONE
and me
.hf
.status
== PGEN_DONE
:
1107 def pg_done(me
, ev
):
1113 class SimulTester (PrimeGenEventHandler
):
1114 def __init__(me
, mul
= 2, add
= 1):
1117 def pg_begin(me
, ev
):
1119 me
.lr
= RabinMiller(x
)
1120 me
.hr
= RabinMiller(x
* me
.mul
+ me
.add
)
1122 lst
= me
.lr
.test(ev
.rng
.range(me
.lr
.x
))
1123 if lst
!= PGEN_PASS
and lst
!= PGEN_DONE
:
1125 rst
= me
.hr
.test(ev
.rng
.range(me
.hr
.x
))
1126 if rst
!= PGEN_PASS
and rst
!= PGEN_DONE
:
1128 if lst
== PGEN_DONE
and rst
== PGEN_DONE
:
1131 def pg_done(me
, ev
):
1135 def sgprime(start
, step
= 2, name
= 'p', event
= pgen_nullev
, nsteps
= 0):
1137 return pgen(start
, name
, SimulStepper(step
= step
), SimulTester(), event
,
1138 nsteps
, RabinMiller
.iters(start
.nbits
))
1140 def findprimitive(mod
, hh
= [], exp
= None, name
= 'g', event
= pgen_nullev
):
1141 return pgen(0, name
, PrimitiveStepper(), PrimitiveTester(mod
, hh
, exp
),
1144 def kcdsaprime(pbits
, qbits
, rng
= rand
,
1145 event
= pgen_nullev
, name
= 'p', nsteps
= 0):
1146 hbits
= pbits
- qbits
1147 h
= pgen(rng
.mp(hbits
, 1), name
+ ' [h]',
1148 PrimeGenStepper(2), PrimeGenTester(),
1149 event
, nsteps
, RabinMiller
.iters(hbits
))
1150 q
= pgen(rng
.mp(qbits
, 1), name
, SimulStepper(2 * h
, 1, 2),
1151 SimulTester(2 * h
, 1), event
, nsteps
, RabinMiller
.iters(qbits
))
1155 #----- That's all, folks ----------------------------------------------------