Commit | Line | Data |
---|---|---|
00401529 MW |
1 | ### -*-python-*- |
2 | ### | |
3 | ### Setup for Catacomb/Python bindings | |
4 | ### | |
5 | ### (c) 2004 Straylight/Edgeware | |
6 | ### | |
7 | ||
8 | ###----- Licensing notice --------------------------------------------------- | |
9 | ### | |
10 | ### This file is part of the Python interface to Catacomb. | |
11 | ### | |
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. | |
16 | ### | |
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. | |
21 | ### | |
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. | |
ed8cc62d | 25 | |
6bd22b53 MW |
26 | from __future__ import with_statement |
27 | ||
d7ab1bab | 28 | from binascii import hexlify as _hexify, unhexlify as _unhexify |
6bd22b53 | 29 | from contextlib import contextmanager as _ctxmgr |
8854bd74 MW |
30 | try: import DLFCN as _dlfcn |
31 | except ImportError: _dlfcn = None | |
32 | import os as _os | |
6bd22b53 | 33 | from struct import pack as _pack |
ed7fea3d MW |
34 | import sys as _sys |
35 | import types as _types | |
36 | ||
37 | ###-------------------------------------------------------------------------- | |
38 | ### Import the main C extension module. | |
39 | ||
8854bd74 MW |
40 | try: |
41 | _dlflags = _odlflags = _sys.getdlopenflags() | |
42 | except AttributeError: | |
43 | _dlflags = _odlflags = -1 | |
44 | ||
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. | |
49 | if _dlflags >= 0: | |
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) | |
57 | ||
ed7fea3d | 58 | import _base |
46e6ad89 | 59 | |
8854bd74 MW |
60 | if _odlflags >= 0: |
61 | _sys.setdlopenflags(_odlflags) | |
62 | ||
63 | del _dlflags, _odlflags | |
64 | ||
00401529 MW |
65 | ###-------------------------------------------------------------------------- |
66 | ### Basic stuff. | |
ed8cc62d | 67 | |
cb46f06b MW |
68 | ## For the benefit of the default keyreporter, we need the program name. |
69 | _base._ego(_sys.argv[0]) | |
d7ab1bab | 70 | |
930d78e3 MW |
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 | |
79 | ||
837fa485 MW |
80 | ## How to fix a name back into the right identifier. Alas, the rules are not |
81 | ## consistent. | |
82 | def _fixname(name): | |
83 | ||
84 | ## Hyphens consistently become underscores. | |
85 | name = name.replace('-', '_') | |
86 | ||
87 | ## But slashes might become underscores or just vanish. | |
3e80d327 | 88 | if name.startswith('salsa20'): name = name.replace('/', '') |
837fa485 MW |
89 | else: name = name.replace('/', '_') |
90 | ||
91 | ## Done. | |
92 | return name | |
93 | ||
ed8cc62d MW |
94 | ## Initialize the module. Drag in the static methods of the various |
95 | ## classes; create names for the various known crypto algorithms. | |
d7ab1bab | 96 | def _init(): |
97 | d = globals() | |
98 | b = _base.__dict__; | |
99 | for i in b: | |
100 | if i[0] != '_': | |
101 | d[i] = b[i]; | |
5a8b43b3 MW |
102 | for i in ['ByteString', |
103 | 'MP', 'GF', 'Field', | |
00401529 MW |
104 | 'ECPt', 'ECPtCurve', 'ECCurve', 'ECInfo', |
105 | 'DHInfo', 'BinDHInfo', 'RSAPriv', 'BBSPriv', | |
106 | 'PrimeFilter', 'RabinMiller', | |
107 | 'Group', 'GE', | |
89157adc | 108 | 'KeySZ', 'KeyData']: |
d7ab1bab | 109 | c = d[i] |
110 | pre = '_' + i + '_' | |
111 | plen = len(pre) | |
112 | for j in b: | |
113 | if j[:plen] == pre: | |
00401529 | 114 | setattr(c, j[plen:], classmethod(b[j])) |
ed8cc62d MW |
115 | for i in [gcciphers, gchashes, gcmacs, gcprps]: |
116 | for c in i.itervalues(): | |
837fa485 | 117 | d[_fixname(c.name)] = c |
ed8cc62d | 118 | for c in gccrands.itervalues(): |
837fa485 | 119 | d[_fixname(c.name + 'rand')] = c |
d7ab1bab | 120 | _init() |
121 | ||
ed8cc62d MW |
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 | |
124 | ## mostly-C types. | |
d7ab1bab | 125 | def _augment(c, cc): |
126 | for i in cc.__dict__: | |
127 | a = cc.__dict__[i] | |
128 | if type(a) is _types.MethodType: | |
129 | a = a.im_func | |
130 | elif type(a) not in (_types.FunctionType, staticmethod, classmethod): | |
131 | continue | |
132 | setattr(c, i, a) | |
133 | ||
ed8cc62d MW |
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 | |
136 | ## just the object. | |
137 | def _checkend(r): | |
138 | x, rest = r | |
139 | if rest != '': | |
140 | raise SyntaxError, 'junk at end of string' | |
141 | return x | |
142 | ||
96d7ed6c | 143 | ## Some pretty-printing utilities. |
652e16ea | 144 | PRINT_SECRETS = False |
330e6a74 | 145 | def _clsname(me): return type(me).__name__ |
652e16ea MW |
146 | def _repr_secret(thing, secretp = True): |
147 | if not secretp or PRINT_SECRETS: return repr(thing) | |
148 | else: return '#<SECRET>' | |
96d7ed6c | 149 | def _pp_str(me, pp, cyclep): pp.text(cyclep and '...' or str(me)) |
652e16ea MW |
150 | def _pp_secret(pp, thing, secretp = True): |
151 | if not secretp or PRINT_SECRETS: pp.pretty(thing) | |
152 | else: pp.text('#<SECRET>') | |
582568f1 MW |
153 | def _pp_bgroup(pp, text): |
154 | ind = len(text) | |
155 | pp.begin_group(ind, text) | |
156 | return ind | |
157 | def _pp_bgroup_tyname(pp, obj, open = '('): | |
330e6a74 | 158 | return _pp_bgroup(pp, _clsname(obj) + open) |
652e16ea | 159 | def _pp_kv(pp, k, v, secretp = False): |
582568f1 | 160 | ind = _pp_bgroup(pp, k + ' = ') |
652e16ea | 161 | _pp_secret(pp, v, secretp) |
96d7ed6c MW |
162 | pp.end_group(ind, '') |
163 | def _pp_commas(pp, printfn, items): | |
164 | firstp = True | |
165 | for i in items: | |
166 | if firstp: firstp = False | |
167 | else: pp.text(','); pp.breakable() | |
168 | printfn(i) | |
169 | def _pp_dict(pp, items): | |
170 | def p((k, v)): | |
582568f1 | 171 | pp.begin_group(0) |
96d7ed6c MW |
172 | pp.pretty(k) |
173 | pp.text(':') | |
582568f1 | 174 | pp.begin_group(2) |
96d7ed6c MW |
175 | pp.breakable() |
176 | pp.pretty(v) | |
582568f1 MW |
177 | pp.end_group(2) |
178 | pp.end_group(0) | |
96d7ed6c MW |
179 | _pp_commas(pp, p, items) |
180 | ||
00401529 MW |
181 | ###-------------------------------------------------------------------------- |
182 | ### Bytestrings. | |
ed8cc62d | 183 | |
d7ab1bab | 184 | class _tmp: |
185 | def fromhex(x): | |
186 | return ByteString(_unhexify(x)) | |
187 | fromhex = staticmethod(fromhex) | |
188 | def __hex__(me): | |
189 | return _hexify(me) | |
190 | def __repr__(me): | |
191 | return 'bytes(%r)' % hex(me) | |
192 | _augment(ByteString, _tmp) | |
bfb450cc | 193 | ByteString.__hash__ = str.__hash__ |
d7ab1bab | 194 | bytes = ByteString.fromhex |
195 | ||
00401529 | 196 | ###-------------------------------------------------------------------------- |
bfb450cc MW |
197 | ### Hashing. |
198 | ||
199 | class _tmp: | |
200 | def check(me, h): | |
201 | hh = me.done() | |
202 | return ctstreq(h, hh) | |
203 | _augment(GHash, _tmp) | |
204 | _augment(Poly1305Hash, _tmp) | |
205 | ||
6bd22b53 MW |
206 | class _HashBase (object): |
207 | ## The standard hash methods. Assume that `hash' is defined and returns | |
208 | ## the receiver. | |
209 | def hashu8(me, n): return me.hash(_pack('B', n)) | |
210 | def hashu16l(me, n): return me.hash(_pack('<H', n)) | |
211 | def hashu16b(me, n): return me.hash(_pack('>H', n)) | |
212 | hashu16 = hashu16b | |
213 | def hashu32l(me, n): return me.hash(_pack('<L', n)) | |
214 | def hashu32b(me, n): return me.hash(_pack('>L', n)) | |
215 | hashu32 = hashu32b | |
216 | def hashu64l(me, n): return me.hash(_pack('<Q', n)) | |
217 | def hashu64b(me, n): return me.hash(_pack('>Q', n)) | |
218 | hashu64 = hashu64b | |
219 | def hashbuf8(me, s): return me.hashu8(len(s)).hash(s) | |
220 | def hashbuf16l(me, s): return me.hashu16l(len(s)).hash(s) | |
221 | def hashbuf16b(me, s): return me.hashu16b(len(s)).hash(s) | |
222 | hashbuf16 = hashbuf16b | |
223 | def hashbuf32l(me, s): return me.hashu32l(len(s)).hash(s) | |
224 | def hashbuf32b(me, s): return me.hashu32b(len(s)).hash(s) | |
225 | hashbuf32 = hashbuf32b | |
226 | def hashbuf64l(me, s): return me.hashu64l(len(s)).hash(s) | |
227 | def hashbuf64b(me, s): return me.hashu64b(len(s)).hash(s) | |
228 | hashbuf64 = hashbuf64b | |
229 | def hashstrz(me, s): return me.hash(s).hashu8(0) | |
230 | ||
231 | class _ShakeBase (_HashBase): | |
232 | ||
233 | ## Python gets really confused if I try to augment `__new__' on native | |
234 | ## classes, so wrap and delegate. Sorry. | |
235 | def __init__(me, perso = '', *args, **kw): | |
236 | super(_ShakeBase, me).__init__(*args, **kw) | |
237 | me._h = me._SHAKE(perso = perso, func = me._FUNC) | |
238 | ||
239 | ## Delegate methods... | |
688625b6 | 240 | def copy(me): new = me.__class__._bare_new(); new._copy(me); return new |
614c3bbf | 241 | def _copy(me, other): me._h = other._h.copy() |
6bd22b53 MW |
242 | def hash(me, m): me._h.hash(m); return me |
243 | def xof(me): me._h.xof(); return me | |
244 | def get(me, n): return me._h.get(n) | |
245 | def mask(me, m): return me._h.mask(m) | |
246 | def done(me, n): return me._h.done(n) | |
247 | def check(me, h): return ctstreq(h, me.done(len(h))) | |
248 | @property | |
249 | def state(me): return me._h.state | |
250 | @property | |
251 | def buffered(me): return me._h.buffered | |
252 | @property | |
253 | def rate(me): return me._h.rate | |
688625b6 MW |
254 | @classmethod |
255 | def _bare_new(cls): return cls() | |
6bd22b53 MW |
256 | |
257 | class _tmp: | |
258 | def check(me, h): | |
259 | return ctstreq(h, me.done(len(h))) | |
260 | def leftenc(me, n): | |
261 | nn = MP(n).storeb() | |
262 | return me.hashu8(len(nn)).hash(nn) | |
263 | def rightenc(me, n): | |
264 | nn = MP(n).storeb() | |
265 | return me.hash(nn).hashu8(len(nn)) | |
266 | def stringenc(me, str): | |
267 | return me.leftenc(8*len(str)).hash(str) | |
268 | def bytepad_before(me): | |
269 | return me.leftenc(me.rate) | |
270 | def bytepad_after(me): | |
271 | if me.buffered: me.hash(me._Z[:me.rate - me.buffered]) | |
272 | return me | |
273 | @_ctxmgr | |
274 | def bytepad(me): | |
275 | me.bytepad_before() | |
276 | yield me | |
277 | me.bytepad_after() | |
278 | _augment(Shake, _tmp) | |
279 | _augment(_ShakeBase, _tmp) | |
280 | Shake._Z = _ShakeBase._Z = ByteString(200*'\0') | |
281 | ||
282 | class KMAC (_ShakeBase): | |
283 | _FUNC = 'KMAC' | |
284 | def __init__(me, k, *arg, **kw): | |
285 | super(KMAC, me).__init__(*arg, **kw) | |
286 | with me.bytepad(): me.stringenc(k) | |
287 | def done(me, n = -1): | |
288 | if n < 0: n = me._TAGSZ | |
289 | me.rightenc(8*n) | |
290 | return super(KMAC, me).done(n) | |
291 | def xof(me): | |
292 | me.rightenc(0) | |
293 | return super(KMAC, me).xof() | |
688625b6 MW |
294 | @classmethod |
295 | def _bare_new(cls): return cls("") | |
6bd22b53 MW |
296 | |
297 | class KMAC128 (KMAC): _SHAKE = Shake128; _TAGSZ = 16 | |
298 | class KMAC256 (KMAC): _SHAKE = Shake256; _TAGSZ = 32 | |
299 | ||
bfb450cc | 300 | ###-------------------------------------------------------------------------- |
ce0340b6 MW |
301 | ### NaCl `secretbox'. |
302 | ||
303 | def secret_box(k, n, m): | |
304 | E = xsalsa20(k).setiv(n) | |
305 | r = E.enczero(poly1305.keysz.default) | |
306 | s = E.enczero(poly1305.masksz) | |
307 | y = E.encrypt(m) | |
308 | t = poly1305(r)(s).hash(y).done() | |
309 | return ByteString(t + y) | |
310 | ||
311 | def secret_unbox(k, n, c): | |
312 | E = xsalsa20(k).setiv(n) | |
313 | r = E.enczero(poly1305.keysz.default) | |
314 | s = E.enczero(poly1305.masksz) | |
315 | y = c[poly1305.tagsz:] | |
316 | if not poly1305(r)(s).hash(y).check(c[0:poly1305.tagsz]): | |
317 | raise ValueError, 'decryption failed' | |
318 | return E.decrypt(c[poly1305.tagsz:]) | |
319 | ||
320 | ###-------------------------------------------------------------------------- | |
00401529 | 321 | ### Multiprecision integers and binary polynomials. |
ed8cc62d | 322 | |
2ef393b5 | 323 | def _split_rat(x): |
83c77564 | 324 | if isinstance(x, BaseRat): return x._n, x._d |
2ef393b5 | 325 | else: return x, 1 |
83c77564 MW |
326 | class BaseRat (object): |
327 | """Base class implementing fields of fractions over Euclidean domains.""" | |
2ef393b5 | 328 | def __new__(cls, a, b): |
83c77564 | 329 | a, b = cls.RING(a), cls.RING(b) |
2ef393b5 MW |
330 | q, r = divmod(a, b) |
331 | if r == 0: return q | |
332 | g = b.gcd(r) | |
83c77564 | 333 | me = super(BaseRat, cls).__new__(cls) |
2ef393b5 MW |
334 | me._n = a//g |
335 | me._d = b//g | |
336 | return me | |
337 | @property | |
338 | def numer(me): return me._n | |
339 | @property | |
340 | def denom(me): return me._d | |
341 | def __str__(me): return '%s/%s' % (me._n, me._d) | |
330e6a74 | 342 | def __repr__(me): return '%s(%s, %s)' % (_clsname(me), me._n, me._d) |
96d7ed6c | 343 | _repr_pretty_ = _pp_str |
2ef393b5 MW |
344 | |
345 | def __add__(me, you): | |
346 | n, d = _split_rat(you) | |
83c77564 | 347 | return type(me)(me._n*d + n*me._d, d*me._d) |
2ef393b5 MW |
348 | __radd__ = __add__ |
349 | def __sub__(me, you): | |
350 | n, d = _split_rat(you) | |
83c77564 | 351 | return type(me)(me._n*d - n*me._d, d*me._d) |
2ef393b5 MW |
352 | def __rsub__(me, you): |
353 | n, d = _split_rat(you) | |
83c77564 | 354 | return type(me)(n*me._d - me._n*d, d*me._d) |
2ef393b5 MW |
355 | def __mul__(me, you): |
356 | n, d = _split_rat(you) | |
83c77564 | 357 | return type(me)(me._n*n, me._d*d) |
08041ebb | 358 | __rmul__ = __mul__ |
b47818ea | 359 | def __truediv__(me, you): |
2ef393b5 | 360 | n, d = _split_rat(you) |
83c77564 | 361 | return type(me)(me._n*d, me._d*n) |
b47818ea | 362 | def __rtruediv__(me, you): |
2ef393b5 | 363 | n, d = _split_rat(you) |
83c77564 | 364 | return type(me)(me._d*n, me._n*d) |
b47818ea MW |
365 | __div__ = __truediv__ |
366 | __rdiv__ = __rtruediv__ | |
2ef393b5 MW |
367 | def __cmp__(me, you): |
368 | n, d = _split_rat(you) | |
7051e349 | 369 | return cmp(me._n*d, n*me._d) |
2ef393b5 MW |
370 | def __rcmp__(me, you): |
371 | n, d = _split_rat(you) | |
372 | return cmp(n*me._d, me._n*d) | |
373 | ||
83c77564 MW |
374 | class IntRat (BaseRat): |
375 | RING = MP | |
376 | ||
377 | class GFRat (BaseRat): | |
378 | RING = GF | |
379 | ||
d7ab1bab | 380 | class _tmp: |
381 | def negp(x): return x < 0 | |
382 | def posp(x): return x > 0 | |
383 | def zerop(x): return x == 0 | |
384 | def oddp(x): return x.testbit(0) | |
385 | def evenp(x): return not x.testbit(0) | |
386 | def mont(x): return MPMont(x) | |
387 | def barrett(x): return MPBarrett(x) | |
388 | def reduce(x): return MPReduce(x) | |
b47818ea MW |
389 | def __truediv__(me, you): return IntRat(me, you) |
390 | def __rtruediv__(me, you): return IntRat(you, me) | |
391 | __div__ = __truediv__ | |
392 | __rdiv__ = __rtruediv__ | |
96d7ed6c | 393 | _repr_pretty_ = _pp_str |
d7ab1bab | 394 | _augment(MP, _tmp) |
395 | ||
d7ab1bab | 396 | class _tmp: |
fbc145f3 | 397 | def zerop(x): return x == 0 |
ed8cc62d | 398 | def reduce(x): return GFReduce(x) |
fbc145f3 MW |
399 | def trace(x, y): return x.reduce().trace(y) |
400 | def halftrace(x, y): return x.reduce().halftrace(y) | |
401 | def modsqrt(x, y): return x.reduce().sqrt(y) | |
402 | def quadsolve(x, y): return x.reduce().quadsolve(y) | |
b47818ea MW |
403 | def __truediv__(me, you): return GFRat(me, you) |
404 | def __rtruediv__(me, you): return GFRat(you, me) | |
405 | __div__ = __truediv__ | |
406 | __rdiv__ = __rtruediv__ | |
96d7ed6c | 407 | _repr_pretty_ = _pp_str |
d7ab1bab | 408 | _augment(GF, _tmp) |
409 | ||
410 | class _tmp: | |
ed8cc62d MW |
411 | def product(*arg): |
412 | 'product(ITERABLE) or product(I, ...) -> PRODUCT' | |
413 | return MPMul(*arg).done() | |
414 | product = staticmethod(product) | |
415 | _augment(MPMul, _tmp) | |
416 | ||
00401529 MW |
417 | ###-------------------------------------------------------------------------- |
418 | ### Abstract fields. | |
ed8cc62d MW |
419 | |
420 | class _tmp: | |
d7ab1bab | 421 | def fromstring(str): return _checkend(Field.parse(str)) |
422 | fromstring = staticmethod(fromstring) | |
423 | _augment(Field, _tmp) | |
424 | ||
425 | class _tmp: | |
330e6a74 | 426 | def __repr__(me): return '%s(%sL)' % (_clsname(me), me.p) |
6d481bc6 | 427 | def __hash__(me): return 0x114401de ^ hash(me.p) |
96d7ed6c | 428 | def _repr_pretty_(me, pp, cyclep): |
582568f1 MW |
429 | ind = _pp_bgroup_tyname(pp, me) |
430 | if cyclep: pp.text('...') | |
431 | else: pp.pretty(me.p) | |
432 | pp.end_group(ind, ')') | |
d7ab1bab | 433 | def ec(me, a, b): return ECPrimeProjCurve(me, a, b) |
434 | _augment(PrimeField, _tmp) | |
435 | ||
436 | class _tmp: | |
330e6a74 | 437 | def __repr__(me): return '%s(%#xL)' % (_clsname(me), me.p) |
d7ab1bab | 438 | def ec(me, a, b): return ECBinProjCurve(me, a, b) |
96d7ed6c | 439 | def _repr_pretty_(me, pp, cyclep): |
582568f1 MW |
440 | ind = _pp_bgroup_tyname(pp, me) |
441 | if cyclep: pp.text('...') | |
442 | else: pp.text('%#x' % me.p) | |
443 | pp.end_group(ind, ')') | |
d7ab1bab | 444 | _augment(BinField, _tmp) |
445 | ||
446 | class _tmp: | |
6d481bc6 MW |
447 | def __hash__(me): return 0x23e4701c ^ hash(me.p) |
448 | _augment(BinPolyField, _tmp) | |
449 | ||
450 | class _tmp: | |
451 | def __hash__(me): | |
452 | h = 0x9a7d6240 | |
453 | h ^= hash(me.p) | |
454 | h ^= 2*hash(me.beta) & 0xffffffff | |
455 | return h | |
456 | _augment(BinNormField, _tmp) | |
457 | ||
458 | class _tmp: | |
d7ab1bab | 459 | def __str__(me): return str(me.value) |
460 | def __repr__(me): return '%s(%s)' % (repr(me.field), repr(me.value)) | |
96d7ed6c | 461 | _repr_pretty_ = _pp_str |
d7ab1bab | 462 | _augment(FE, _tmp) |
463 | ||
00401529 MW |
464 | ###-------------------------------------------------------------------------- |
465 | ### Elliptic curves. | |
d7ab1bab | 466 | |
467 | class _tmp: | |
468 | def __repr__(me): | |
330e6a74 | 469 | return '%s(%r, %s, %s)' % (_clsname(me), me.field, me.a, me.b) |
96d7ed6c | 470 | def _repr_pretty_(me, pp, cyclep): |
582568f1 | 471 | ind = _pp_bgroup_tyname(pp, me) |
96d7ed6c | 472 | if cyclep: |
582568f1 | 473 | pp.text('...') |
96d7ed6c | 474 | else: |
96d7ed6c MW |
475 | pp.pretty(me.field); pp.text(','); pp.breakable() |
476 | pp.pretty(me.a); pp.text(','); pp.breakable() | |
477 | pp.pretty(me.b) | |
582568f1 | 478 | pp.end_group(ind, ')') |
d7ab1bab | 479 | def frombuf(me, s): |
480 | return ecpt.frombuf(me, s) | |
481 | def fromraw(me, s): | |
482 | return ecpt.fromraw(me, s) | |
483 | def pt(me, *args): | |
5f959e50 | 484 | return me(*args) |
d7ab1bab | 485 | _augment(ECCurve, _tmp) |
486 | ||
487 | class _tmp: | |
6d481bc6 MW |
488 | def __hash__(me): |
489 | h = 0x6751d341 | |
490 | h ^= hash(me.field) | |
491 | h ^= 2*hash(me.a) ^ 0xffffffff | |
492 | h ^= 5*hash(me.b) ^ 0xffffffff | |
493 | return h | |
494 | _augment(ECPrimeCurve, _tmp) | |
495 | ||
496 | class _tmp: | |
497 | def __hash__(me): | |
498 | h = 0x2ac203c5 | |
499 | h ^= hash(me.field) | |
500 | h ^= 2*hash(me.a) ^ 0xffffffff | |
501 | h ^= 5*hash(me.b) ^ 0xffffffff | |
502 | return h | |
503 | _augment(ECBinCurve, _tmp) | |
504 | ||
505 | class _tmp: | |
d7ab1bab | 506 | def __repr__(me): |
330e6a74 MW |
507 | if not me: return '%s()' % _clsname(me) |
508 | return '%s(%s, %s)' % (_clsname(me), me.ix, me.iy) | |
d7ab1bab | 509 | def __str__(me): |
510 | if not me: return 'inf' | |
511 | return '(%s, %s)' % (me.ix, me.iy) | |
96d7ed6c MW |
512 | def _repr_pretty_(me, pp, cyclep): |
513 | if cyclep: | |
514 | pp.text('...') | |
515 | elif not me: | |
516 | pp.text('inf') | |
517 | else: | |
582568f1 | 518 | ind = _pp_bgroup(pp, '(') |
96d7ed6c MW |
519 | pp.pretty(me.ix); pp.text(','); pp.breakable() |
520 | pp.pretty(me.iy) | |
582568f1 | 521 | pp.end_group(ind, ')') |
d7ab1bab | 522 | _augment(ECPt, _tmp) |
523 | ||
524 | class _tmp: | |
525 | def __repr__(me): | |
330e6a74 MW |
526 | return '%s(curve = %r, G = %r, r = %s, h = %s)' % \ |
527 | (_clsname(me), me.curve, me.G, me.r, me.h) | |
96d7ed6c | 528 | def _repr_pretty_(me, pp, cyclep): |
582568f1 | 529 | ind = _pp_bgroup_tyname(pp, me) |
96d7ed6c | 530 | if cyclep: |
582568f1 | 531 | pp.text('...') |
96d7ed6c | 532 | else: |
96d7ed6c MW |
533 | _pp_kv(pp, 'curve', me.curve); pp.text(','); pp.breakable() |
534 | _pp_kv(pp, 'G', me.G); pp.text(','); pp.breakable() | |
535 | _pp_kv(pp, 'r', me.r); pp.text(','); pp.breakable() | |
536 | _pp_kv(pp, 'h', me.h) | |
582568f1 | 537 | pp.end_group(ind, ')') |
6d481bc6 MW |
538 | def __hash__(me): |
539 | h = 0x9bedb8de | |
540 | h ^= hash(me.curve) | |
541 | h ^= 2*hash(me.G) & 0xffffffff | |
542 | return h | |
d7ab1bab | 543 | def group(me): |
544 | return ECGroup(me) | |
545 | _augment(ECInfo, _tmp) | |
546 | ||
547 | class _tmp: | |
548 | def __repr__(me): | |
549 | if not me: return '%r()' % (me.curve) | |
550 | return '%r(%s, %s)' % (me.curve, me.x, me.y) | |
551 | def __str__(me): | |
552 | if not me: return 'inf' | |
553 | return '(%s, %s)' % (me.x, me.y) | |
7a7aa30e MW |
554 | def _repr_pretty_(me, pp, cyclep): |
555 | if cyclep: | |
556 | pp.text('...') | |
557 | elif not me: | |
558 | pp.text('inf') | |
559 | else: | |
560 | ind = _pp_bgroup(pp, '(') | |
561 | pp.pretty(me.x); pp.text(','); pp.breakable() | |
562 | pp.pretty(me.y) | |
563 | pp.end_group(ind, ')') | |
d7ab1bab | 564 | _augment(ECPtCurve, _tmp) |
565 | ||
00401529 MW |
566 | ###-------------------------------------------------------------------------- |
567 | ### Key sizes. | |
ed8cc62d | 568 | |
d7ab1bab | 569 | class _tmp: |
330e6a74 | 570 | def __repr__(me): return '%s(%d)' % (_clsname(me), me.default) |
d7ab1bab | 571 | def check(me, sz): return True |
572 | def best(me, sz): return sz | |
573 | _augment(KeySZAny, _tmp) | |
574 | ||
575 | class _tmp: | |
576 | def __repr__(me): | |
330e6a74 MW |
577 | return '%s(%d, %d, %d, %d)' % \ |
578 | (_clsname(me), me.default, me.min, me.max, me.mod) | |
96d7ed6c | 579 | def _repr_pretty_(me, pp, cyclep): |
582568f1 | 580 | ind = _pp_bgroup_tyname(pp, me) |
96d7ed6c | 581 | if cyclep: |
582568f1 | 582 | pp.text('...') |
96d7ed6c | 583 | else: |
96d7ed6c MW |
584 | pp.pretty(me.default); pp.text(','); pp.breakable() |
585 | pp.pretty(me.min); pp.text(','); pp.breakable() | |
586 | pp.pretty(me.max); pp.text(','); pp.breakable() | |
587 | pp.pretty(me.mod) | |
582568f1 | 588 | pp.end_group(ind, ')') |
d7ab1bab | 589 | def check(me, sz): return me.min <= sz <= me.max and sz % me.mod == 0 |
590 | def best(me, sz): | |
591 | if sz < me.min: raise ValueError, 'key too small' | |
592 | elif sz > me.max: return me.max | |
593 | else: return sz - (sz % me.mod) | |
594 | _augment(KeySZRange, _tmp) | |
595 | ||
596 | class _tmp: | |
330e6a74 | 597 | def __repr__(me): return '%s(%d, %s)' % (_clsname(me), me.default, me.set) |
96d7ed6c | 598 | def _repr_pretty_(me, pp, cyclep): |
582568f1 | 599 | ind = _pp_bgroup_tyname(pp, me) |
96d7ed6c | 600 | if cyclep: |
582568f1 | 601 | pp.text('...') |
96d7ed6c | 602 | else: |
96d7ed6c | 603 | pp.pretty(me.default); pp.text(','); pp.breakable() |
582568f1 | 604 | ind1 = _pp_bgroup(pp, '{') |
96d7ed6c | 605 | _pp_commas(pp, pp.pretty, me.set) |
582568f1 MW |
606 | pp.end_group(ind1, '}') |
607 | pp.end_group(ind, ')') | |
d7ab1bab | 608 | def check(me, sz): return sz in me.set |
609 | def best(me, sz): | |
610 | found = -1 | |
611 | for i in me.set: | |
612 | if found < i <= sz: found = i | |
613 | if found < 0: raise ValueError, 'key too small' | |
614 | return found | |
615 | _augment(KeySZSet, _tmp) | |
616 | ||
00401529 | 617 | ###-------------------------------------------------------------------------- |
96d7ed6c MW |
618 | ### Key data objects. |
619 | ||
620 | class _tmp: | |
330e6a74 | 621 | def __repr__(me): return '%s(%r)' % (_clsname(me), me.name) |
96d7ed6c MW |
622 | _augment(KeyFile, _tmp) |
623 | ||
624 | class _tmp: | |
330e6a74 | 625 | def __repr__(me): return '%s(%r)' % (_clsname(me), me.fulltag) |
96d7ed6c MW |
626 | _augment(Key, _tmp) |
627 | ||
628 | class _tmp: | |
629 | def __repr__(me): | |
330e6a74 MW |
630 | return '%s({%s})' % (_clsname(me), |
631 | ', '.join(['%r: %r' % kv for kv in me.iteritems()])) | |
96d7ed6c | 632 | def _repr_pretty_(me, pp, cyclep): |
582568f1 | 633 | ind = _pp_bgroup_tyname(pp, me) |
96d7ed6c MW |
634 | if cyclep: pp.text('...') |
635 | else: _pp_dict(pp, me.iteritems()) | |
582568f1 | 636 | pp.end_group(ind, ')') |
96d7ed6c MW |
637 | _augment(KeyAttributes, _tmp) |
638 | ||
639 | class _tmp: | |
849e8a20 | 640 | def __repr__(me): |
652e16ea MW |
641 | return '%s(%s, %r)' % (_clsname(me), |
642 | _repr_secret(me._guts(), | |
643 | not (me.flags & KF_NONSECRET)), | |
644 | me.writeflags(me.flags)) | |
96d7ed6c | 645 | def _repr_pretty_(me, pp, cyclep): |
582568f1 | 646 | ind = _pp_bgroup_tyname(pp, me) |
96d7ed6c | 647 | if cyclep: |
582568f1 | 648 | pp.text('...') |
96d7ed6c | 649 | else: |
652e16ea MW |
650 | _pp_secret(pp, me._guts(), not (me.flags & KF_NONSECRET)) |
651 | pp.text(','); pp.breakable() | |
96d7ed6c | 652 | pp.pretty(me.writeflags(me.flags)) |
582568f1 | 653 | pp.end_group(ind, ')') |
849e8a20 MW |
654 | _augment(KeyData, _tmp) |
655 | ||
656 | class _tmp: | |
657 | def _guts(me): return me.bin | |
96d7ed6c MW |
658 | _augment(KeyDataBinary, _tmp) |
659 | ||
660 | class _tmp: | |
849e8a20 | 661 | def _guts(me): return me.ct |
96d7ed6c MW |
662 | _augment(KeyDataEncrypted, _tmp) |
663 | ||
664 | class _tmp: | |
849e8a20 | 665 | def _guts(me): return me.mp |
96d7ed6c MW |
666 | _augment(KeyDataMP, _tmp) |
667 | ||
668 | class _tmp: | |
849e8a20 | 669 | def _guts(me): return me.str |
96d7ed6c MW |
670 | _augment(KeyDataString, _tmp) |
671 | ||
672 | class _tmp: | |
849e8a20 | 673 | def _guts(me): return me.ecpt |
96d7ed6c MW |
674 | _augment(KeyDataECPt, _tmp) |
675 | ||
676 | class _tmp: | |
677 | def __repr__(me): | |
330e6a74 MW |
678 | return '%s({%s})' % (_clsname(me), |
679 | ', '.join(['%r: %r' % kv for kv in me.iteritems()])) | |
96d7ed6c | 680 | def _repr_pretty_(me, pp, cyclep): |
582568f1 | 681 | ind = _pp_bgroup_tyname(pp, me, '({ ') |
96d7ed6c MW |
682 | if cyclep: pp.text('...') |
683 | else: _pp_dict(pp, me.iteritems()) | |
582568f1 | 684 | pp.end_group(ind, ' })') |
96d7ed6c MW |
685 | _augment(KeyDataStructured, _tmp) |
686 | ||
687 | ###-------------------------------------------------------------------------- | |
00401529 | 688 | ### Abstract groups. |
ed8cc62d | 689 | |
d7ab1bab | 690 | class _tmp: |
691 | def __repr__(me): | |
330e6a74 | 692 | return '%s(p = %s, r = %s, g = %s)' % (_clsname(me), me.p, me.r, me.g) |
96d7ed6c | 693 | def _repr_pretty_(me, pp, cyclep): |
582568f1 | 694 | ind = _pp_bgroup_tyname(pp, me) |
96d7ed6c | 695 | if cyclep: |
582568f1 | 696 | pp.text('...') |
96d7ed6c | 697 | else: |
96d7ed6c MW |
698 | _pp_kv(pp, 'p', me.p); pp.text(','); pp.breakable() |
699 | _pp_kv(pp, 'r', me.r); pp.text(','); pp.breakable() | |
700 | _pp_kv(pp, 'g', me.g) | |
582568f1 | 701 | pp.end_group(ind, ')') |
d7ab1bab | 702 | _augment(FGInfo, _tmp) |
703 | ||
704 | class _tmp: | |
705 | def group(me): return PrimeGroup(me) | |
706 | _augment(DHInfo, _tmp) | |
707 | ||
708 | class _tmp: | |
709 | def group(me): return BinGroup(me) | |
710 | _augment(BinDHInfo, _tmp) | |
711 | ||
712 | class _tmp: | |
713 | def __repr__(me): | |
330e6a74 | 714 | return '%s(%r)' % (_clsname(me), me.info) |
99d932fe MW |
715 | def _repr_pretty_(me, pp, cyclep): |
716 | ind = _pp_bgroup_tyname(pp, me) | |
717 | if cyclep: pp.text('...') | |
718 | else: pp.pretty(me.info) | |
719 | pp.end_group(ind, ')') | |
d7ab1bab | 720 | _augment(Group, _tmp) |
721 | ||
722 | class _tmp: | |
6d481bc6 MW |
723 | def __hash__(me): |
724 | info = me.info | |
725 | h = 0xbce3cfe6 | |
726 | h ^= hash(info.p) | |
727 | h ^= 2*hash(info.r) & 0xffffffff | |
728 | h ^= 5*hash(info.g) & 0xffffffff | |
729 | return h | |
d7012c2b | 730 | def _get_geval(me, x): return MP(x) |
6d481bc6 MW |
731 | _augment(PrimeGroup, _tmp) |
732 | ||
733 | class _tmp: | |
734 | def __hash__(me): | |
735 | info = me.info | |
736 | h = 0x80695949 | |
737 | h ^= hash(info.p) | |
738 | h ^= 2*hash(info.r) & 0xffffffff | |
739 | h ^= 5*hash(info.g) & 0xffffffff | |
740 | return h | |
d7012c2b | 741 | def _get_geval(me, x): return GF(x) |
6d481bc6 MW |
742 | _augment(BinGroup, _tmp) |
743 | ||
744 | class _tmp: | |
745 | def __hash__(me): return 0x0ec23dab ^ hash(me.info) | |
d7012c2b | 746 | def _get_geval(me, x): return x.toec() |
6d481bc6 MW |
747 | _augment(ECGroup, _tmp) |
748 | ||
749 | class _tmp: | |
d7ab1bab | 750 | def __repr__(me): |
751 | return '%r(%r)' % (me.group, str(me)) | |
d7012c2b MW |
752 | def _repr_pretty_(me, pp, cyclep): |
753 | pp.pretty(type(me)._get_geval(me)) | |
d7ab1bab | 754 | _augment(GE, _tmp) |
755 | ||
00401529 MW |
756 | ###-------------------------------------------------------------------------- |
757 | ### RSA encoding techniques. | |
ed8cc62d MW |
758 | |
759 | class PKCS1Crypt (object): | |
d7ab1bab | 760 | def __init__(me, ep = '', rng = rand): |
761 | me.ep = ep | |
762 | me.rng = rng | |
763 | def encode(me, msg, nbits): | |
764 | return _base._p1crypt_encode(msg, nbits, me.ep, me.rng) | |
765 | def decode(me, ct, nbits): | |
766 | return _base._p1crypt_decode(ct, nbits, me.ep, me.rng) | |
767 | ||
ed8cc62d | 768 | class PKCS1Sig (object): |
d7ab1bab | 769 | def __init__(me, ep = '', rng = rand): |
770 | me.ep = ep | |
771 | me.rng = rng | |
772 | def encode(me, msg, nbits): | |
773 | return _base._p1sig_encode(msg, nbits, me.ep, me.rng) | |
774 | def decode(me, msg, sig, nbits): | |
775 | return _base._p1sig_decode(msg, sig, nbits, me.ep, me.rng) | |
776 | ||
ed8cc62d | 777 | class OAEP (object): |
d7ab1bab | 778 | def __init__(me, mgf = sha_mgf, hash = sha, ep = '', rng = rand): |
779 | me.mgf = mgf | |
780 | me.hash = hash | |
781 | me.ep = ep | |
782 | me.rng = rng | |
783 | def encode(me, msg, nbits): | |
784 | return _base._oaep_encode(msg, nbits, me.mgf, me.hash, me.ep, me.rng) | |
785 | def decode(me, ct, nbits): | |
786 | return _base._oaep_decode(ct, nbits, me.mgf, me.hash, me.ep, me.rng) | |
787 | ||
ed8cc62d | 788 | class PSS (object): |
d7ab1bab | 789 | def __init__(me, mgf = sha_mgf, hash = sha, saltsz = None, rng = rand): |
790 | me.mgf = mgf | |
791 | me.hash = hash | |
792 | if saltsz is None: | |
793 | saltsz = hash.hashsz | |
794 | me.saltsz = saltsz | |
795 | me.rng = rng | |
796 | def encode(me, msg, nbits): | |
797 | return _base._pss_encode(msg, nbits, me.mgf, me.hash, me.saltsz, me.rng) | |
798 | def decode(me, msg, sig, nbits): | |
799 | return _base._pss_decode(msg, sig, nbits, | |
00401529 | 800 | me.mgf, me.hash, me.saltsz, me.rng) |
d7ab1bab | 801 | |
802 | class _tmp: | |
803 | def encrypt(me, msg, enc): | |
804 | return me.pubop(enc.encode(msg, me.n.nbits)) | |
805 | def verify(me, msg, sig, enc): | |
806 | if msg is None: return enc.decode(msg, me.pubop(sig), me.n.nbits) | |
807 | try: | |
808 | x = enc.decode(msg, me.pubop(sig), me.n.nbits) | |
809 | return x is None or x == msg | |
810 | except ValueError: | |
b2687a0a | 811 | return False |
bbd94558 MW |
812 | def __repr__(me): |
813 | return '%s(n = %r, e = %r)' % (_clsname(me), me.n, me.e) | |
814 | def _repr_pretty_(me, pp, cyclep): | |
815 | ind = _pp_bgroup_tyname(pp, me) | |
816 | if cyclep: | |
817 | pp.text('...') | |
818 | else: | |
819 | _pp_kv(pp, 'n', me.n); pp.text(','); pp.breakable() | |
820 | _pp_kv(pp, 'e', me.e) | |
821 | pp.end_group(ind, ')') | |
d7ab1bab | 822 | _augment(RSAPub, _tmp) |
823 | ||
824 | class _tmp: | |
825 | def decrypt(me, ct, enc): return enc.decode(me.privop(ct), me.n.nbits) | |
826 | def sign(me, msg, enc): return me.privop(enc.encode(msg, me.n.nbits)) | |
bbd94558 MW |
827 | def __repr__(me): |
828 | return '%s(n = %r, e = %r, d = %s, ' \ | |
829 | 'p = %s, q = %s, dp = %s, dq = %s, q_inv = %s)' % \ | |
830 | (_clsname(me), me.n, me.e, | |
831 | _repr_secret(me.d), _repr_secret(me.p), _repr_secret(me.q), | |
832 | _repr_secret(me.dp), _repr_secret(me.dq), _repr_secret(me.q_inv)) | |
833 | def _repr_pretty_(me, pp, cyclep): | |
834 | ind = _pp_bgroup_tyname(pp, me) | |
835 | if cyclep: | |
836 | pp.text('...') | |
837 | else: | |
838 | _pp_kv(pp, 'n', me.n); pp.text(','); pp.breakable() | |
839 | _pp_kv(pp, 'e', me.e); pp.text(','); pp.breakable() | |
840 | _pp_kv(pp, 'd', me.d, secretp = True); pp.text(','); pp.breakable() | |
841 | _pp_kv(pp, 'p', me.p, secretp = True); pp.text(','); pp.breakable() | |
842 | _pp_kv(pp, 'q', me.q, secretp = True); pp.text(','); pp.breakable() | |
843 | _pp_kv(pp, 'dp', me.dp, secretp = True); pp.text(','); pp.breakable() | |
844 | _pp_kv(pp, 'dq', me.dq, secretp = True); pp.text(','); pp.breakable() | |
845 | _pp_kv(pp, 'q_inv', me.q_inv, secretp = True) | |
846 | pp.end_group(ind, ')') | |
d7ab1bab | 847 | _augment(RSAPriv, _tmp) |
848 | ||
00401529 | 849 | ###-------------------------------------------------------------------------- |
bbd94558 MW |
850 | ### DSA and related schemes. |
851 | ||
852 | class _tmp: | |
853 | def __repr__(me): return '%s(G = %r, p = %r)' % (_clsname(me), me.G, me.p) | |
854 | def _repr_pretty_(me, pp, cyclep): | |
855 | ind = _pp_bgroup_tyname(pp, me) | |
856 | if cyclep: | |
857 | pp.text('...') | |
858 | else: | |
859 | _pp_kv(pp, 'G', me.G); pp.text(','); pp.breakable() | |
860 | _pp_kv(pp, 'p', me.p) | |
861 | pp.end_group(ind, ')') | |
862 | _augment(DSAPub, _tmp) | |
863 | _augment(KCDSAPub, _tmp) | |
864 | ||
865 | class _tmp: | |
866 | def __repr__(me): return '%s(G = %r, u = %s, p = %r)' % \ | |
867 | (_clsname(me), me.G, _repr_secret(me.u), me.p) | |
868 | def _repr_pretty_(me, pp, cyclep): | |
869 | ind = _pp_bgroup_tyname(pp, me) | |
870 | if cyclep: | |
871 | pp.text('...') | |
872 | else: | |
873 | _pp_kv(pp, 'G', me.G); pp.text(','); pp.breakable() | |
874 | _pp_kv(pp, 'u', me.u, True); pp.text(','); pp.breakable() | |
875 | _pp_kv(pp, 'p', me.p) | |
876 | pp.end_group(ind, ')') | |
877 | _augment(DSAPriv, _tmp) | |
878 | _augment(KCDSAPriv, _tmp) | |
879 | ||
880 | ###-------------------------------------------------------------------------- | |
eb8aa4ec | 881 | ### Bernstein's elliptic curve crypto and related schemes. |
848ba392 | 882 | |
8e6f45a3 MW |
883 | X25519_BASE = MP(9).storel(32) |
884 | X448_BASE = MP(5).storel(56) | |
eb8aa4ec | 885 | |
5a8b43b3 | 886 | Z128 = ByteString.zero(16) |
848ba392 | 887 | |
925aa45b | 888 | class _BasePub (object): |
f40e338b | 889 | def __init__(me, pub, *args, **kw): |
925aa45b MW |
890 | if not me._PUBSZ.check(len(pub)): raise ValueError, 'bad public key' |
891 | super(_BasePub, me).__init__(*args, **kw) | |
848ba392 | 892 | me.pub = pub |
bbd94558 | 893 | def __repr__(me): return '%s(pub = %r)' % (_clsname(me), me.pub) |
925aa45b | 894 | def _pp(me, pp): _pp_kv(pp, 'pub', me.pub) |
bbd94558 MW |
895 | def _repr_pretty_(me, pp, cyclep): |
896 | ind = _pp_bgroup_tyname(pp, me) | |
925aa45b MW |
897 | if cyclep: pp.text('...') |
898 | else: me._pp(pp) | |
bbd94558 | 899 | pp.end_group(ind, ')') |
848ba392 | 900 | |
925aa45b | 901 | class _BasePriv (object): |
f40e338b | 902 | def __init__(me, priv, pub = None, *args, **kw): |
925aa45b MW |
903 | if not me._KEYSZ.check(len(priv)): raise ValueError, 'bad private key' |
904 | if pub is None: pub = me._pubkey(priv) | |
905 | super(_BasePriv, me).__init__(pub = pub, *args, **kw) | |
848ba392 | 906 | me.priv = priv |
925aa45b MW |
907 | @classmethod |
908 | def generate(cls, rng = rand): | |
909 | return cls(rng.block(cls._KEYSZ.default)) | |
910 | def __repr__(me): | |
911 | return '%s(priv = %d, pub = %r)' % \ | |
912 | (_clsname(me), _repr_secret(me.priv), me.pub) | |
913 | def _pp(me, pp): | |
914 | _pp_kv(pp, 'priv', me.priv, secretp = True); pp.text(','); pp.breakable() | |
915 | super(_BasePriv, me)._pp(pp) | |
916 | ||
917 | class _XDHPub (_BasePub): pass | |
918 | ||
919 | class _XDHPriv (_BasePriv): | |
920 | def _pubkey(me, priv): return me._op(priv, me._BASE) | |
848ba392 | 921 | def agree(me, you): return me._op(me.priv, you.pub) |
925aa45b MW |
922 | def boxkey(me, recip): return me._hashkey(me.agree(recip)) |
923 | def box(me, recip, n, m): return secret_box(me.boxkey(recip), n, m) | |
924 | def unbox(me, recip, n, c): return secret_unbox(me.boxkey(recip), n, c) | |
848ba392 | 925 | |
925aa45b MW |
926 | class X25519Pub (_XDHPub): |
927 | _PUBSZ = KeySZSet(X25519_PUBSZ) | |
848ba392 MW |
928 | _BASE = X25519_BASE |
929 | ||
925aa45b MW |
930 | class X25519Priv (_XDHPriv, X25519Pub): |
931 | _KEYSZ = KeySZSet(X25519_KEYSZ) | |
848ba392 MW |
932 | def _op(me, k, X): return x25519(k, X) |
933 | def _hashkey(me, z): return hsalsa20_prf(z, Z128) | |
934 | ||
925aa45b MW |
935 | class X448Pub (_XDHPub): |
936 | _PUBSZ = KeySZSet(X448_PUBSZ) | |
eb8aa4ec MW |
937 | _BASE = X448_BASE |
938 | ||
925aa45b MW |
939 | class X448Priv (_XDHPriv, X448Pub): |
940 | _KEYSZ = KeySZSet(X448_KEYSZ) | |
eb8aa4ec | 941 | def _op(me, k, X): return x448(k, X) |
f1b0cf0d | 942 | def _hashkey(me, z): return Shake256().hash(z).done(salsa20.keysz.default) |
eb8aa4ec | 943 | |
925aa45b | 944 | class _EdDSAPub (_BasePub): |
058f0a00 MW |
945 | def beginhash(me): return me._HASH() |
946 | def endhash(me, h): return h.done() | |
925aa45b MW |
947 | |
948 | class _EdDSAPriv (_BasePriv, _EdDSAPub): | |
949 | pass | |
950 | ||
951 | class Ed25519Pub (_EdDSAPub): | |
952 | _PUBSZ = KeySZSet(ED25519_PUBSZ) | |
058f0a00 | 953 | _HASH = sha512 |
5c4c0231 MW |
954 | def verify(me, msg, sig, **kw): |
955 | return ed25519_verify(me.pub, msg, sig, **kw) | |
dafb2da4 | 956 | |
925aa45b MW |
957 | class Ed25519Priv (_EdDSAPriv, Ed25519Pub): |
958 | _KEYSZ = KeySZAny(ED25519_KEYSZ) | |
959 | def _pubkey(me, priv): return ed25519_pubkey(priv) | |
5c4c0231 MW |
960 | def sign(me, msg, **kw): |
961 | return ed25519_sign(me.priv, msg, pub = me.pub, **kw) | |
dafb2da4 | 962 | |
eee202c3 MW |
963 | class Ed448Pub (_EdDSAPub): |
964 | _PUBSZ = KeySZSet(ED448_PUBSZ) | |
965 | _HASH = shake256 | |
966 | def verify(me, msg, sig, **kw): | |
967 | return ed448_verify(me.pub, msg, sig, **kw) | |
968 | ||
969 | class Ed448Priv (_EdDSAPriv, Ed448Pub): | |
970 | _KEYSZ = KeySZAny(ED448_KEYSZ) | |
971 | def _pubkey(me, priv): return ed448_pubkey(priv) | |
972 | def sign(me, msg, **kw): | |
973 | return ed448_sign(me.priv, msg, pub = me.pub, **kw) | |
974 | ||
848ba392 | 975 | ###-------------------------------------------------------------------------- |
00401529 | 976 | ### Built-in named curves and prime groups. |
ed8cc62d MW |
977 | |
978 | class _groupmap (object): | |
979 | def __init__(me, map, nth): | |
980 | me.map = map | |
981 | me.nth = nth | |
1b61856d MW |
982 | me._n = max(map.values()) + 1 |
983 | me.i = me._n*[None] | |
ed8cc62d | 984 | def __repr__(me): |
96d7ed6c MW |
985 | return '{%s}' % ', '.join(['%r: %r' % kv for kv in me.iteritems()]) |
986 | def _repr_pretty_(me, pp, cyclep): | |
582568f1 MW |
987 | ind = _pp_bgroup(pp, '{ ') |
988 | if cyclep: pp.text('...') | |
989 | else: _pp_dict(pp, me.iteritems()) | |
990 | pp.end_group(ind, ' }') | |
1b61856d MW |
991 | def __len__(me): |
992 | return me._n | |
ed8cc62d MW |
993 | def __contains__(me, k): |
994 | return k in me.map | |
995 | def __getitem__(me, k): | |
996 | i = me.map[k] | |
997 | if me.i[i] is None: | |
998 | me.i[i] = me.nth(i) | |
999 | return me.i[i] | |
1000 | def __setitem__(me, k, v): | |
1001 | raise TypeError, "immutable object" | |
1002 | def __iter__(me): | |
1003 | return iter(me.map) | |
96851f5d MW |
1004 | def iterkeys(me): |
1005 | return iter(me.map) | |
1006 | def itervalues(me): | |
1007 | for k in me: | |
1008 | yield me[k] | |
1009 | def iteritems(me): | |
1010 | for k in me: | |
1011 | yield k, me[k] | |
ed8cc62d MW |
1012 | def keys(me): |
1013 | return [k for k in me] | |
1014 | def values(me): | |
1015 | return [me[k] for k in me] | |
96851f5d MW |
1016 | def items(me): |
1017 | return [(k, me[k]) for k in me] | |
ed8cc62d MW |
1018 | eccurves = _groupmap(_base._eccurves, ECInfo._curven) |
1019 | primegroups = _groupmap(_base._pgroups, DHInfo._groupn) | |
1020 | bingroups = _groupmap(_base._bingroups, BinDHInfo._groupn) | |
1021 | ||
00401529 MW |
1022 | ###-------------------------------------------------------------------------- |
1023 | ### Prime number generation. | |
ed8cc62d MW |
1024 | |
1025 | class PrimeGenEventHandler (object): | |
1026 | def pg_begin(me, ev): | |
1027 | return me.pg_try(ev) | |
1028 | def pg_done(me, ev): | |
1029 | return PGEN_DONE | |
1030 | def pg_abort(me, ev): | |
1031 | return PGEN_TRY | |
1032 | def pg_fail(me, ev): | |
1033 | return PGEN_TRY | |
1034 | def pg_pass(me, ev): | |
1035 | return PGEN_TRY | |
d7ab1bab | 1036 | |
1037 | class SophieGermainStepJump (object): | |
1038 | def pg_begin(me, ev): | |
1039 | me.lf = PrimeFilter(ev.x) | |
1040 | me.hf = me.lf.muladd(2, 1) | |
1041 | return me.cont(ev) | |
1042 | def pg_try(me, ev): | |
1043 | me.step() | |
1044 | return me.cont(ev) | |
1045 | def cont(me, ev): | |
1046 | while me.lf.status == PGEN_FAIL or me.hf.status == PGEN_FAIL: | |
1047 | me.step() | |
1048 | if me.lf.status == PGEN_ABORT or me.hf.status == PGEN_ABORT: | |
1049 | return PGEN_ABORT | |
1050 | ev.x = me.lf.x | |
1051 | if me.lf.status == PGEN_DONE and me.hf.status == PGEN_DONE: | |
1052 | return PGEN_DONE | |
1053 | return PGEN_TRY | |
1054 | def pg_done(me, ev): | |
1055 | del me.lf | |
1056 | del me.hf | |
1057 | ||
1058 | class SophieGermainStepper (SophieGermainStepJump): | |
1059 | def __init__(me, step): | |
1060 | me.lstep = step; | |
1061 | me.hstep = 2 * step | |
1062 | def step(me): | |
1063 | me.lf.step(me.lstep) | |
1064 | me.hf.step(me.hstep) | |
1065 | ||
1066 | class SophieGermainJumper (SophieGermainStepJump): | |
1067 | def __init__(me, jump): | |
1068 | me.ljump = PrimeFilter(jump); | |
1069 | me.hjump = me.ljump.muladd(2, 0) | |
1070 | def step(me): | |
1071 | me.lf.jump(me.ljump) | |
1072 | me.hf.jump(me.hjump) | |
1073 | def pg_done(me, ev): | |
1074 | del me.ljump | |
1075 | del me.hjump | |
1076 | SophieGermainStepJump.pg_done(me, ev) | |
1077 | ||
1078 | class SophieGermainTester (object): | |
1079 | def __init__(me): | |
1080 | pass | |
1081 | def pg_begin(me, ev): | |
1082 | me.lr = RabinMiller(ev.x) | |
1083 | me.hr = RabinMiller(2 * ev.x + 1) | |
1084 | def pg_try(me, ev): | |
1085 | lst = me.lr.test(ev.rng.range(me.lr.x)) | |
1086 | if lst != PGEN_PASS and lst != PGEN_DONE: | |
1087 | return lst | |
1088 | rst = me.hr.test(ev.rng.range(me.hr.x)) | |
1089 | if rst != PGEN_PASS and rst != PGEN_DONE: | |
1090 | return rst | |
1091 | if lst == PGEN_DONE and rst == PGEN_DONE: | |
1092 | return PGEN_DONE | |
1093 | return PGEN_PASS | |
1094 | def pg_done(me, ev): | |
1095 | del me.lr | |
1096 | del me.hr | |
1097 | ||
d7ab1bab | 1098 | class PrimitiveStepper (PrimeGenEventHandler): |
1099 | def __init__(me): | |
1100 | pass | |
1101 | def pg_try(me, ev): | |
1102 | ev.x = me.i.next() | |
1103 | return PGEN_TRY | |
1104 | def pg_begin(me, ev): | |
1105 | me.i = iter(smallprimes) | |
1106 | return me.pg_try(ev) | |
1107 | ||
1108 | class PrimitiveTester (PrimeGenEventHandler): | |
1109 | def __init__(me, mod, hh = [], exp = None): | |
1110 | me.mod = MPMont(mod) | |
1111 | me.exp = exp | |
1112 | me.hh = hh | |
1113 | def pg_try(me, ev): | |
1114 | x = ev.x | |
1115 | if me.exp is not None: | |
1116 | x = me.mod.exp(x, me.exp) | |
1117 | if x == 1: return PGEN_FAIL | |
1118 | for h in me.hh: | |
1119 | if me.mod.exp(x, h) == 1: return PGEN_FAIL | |
1120 | ev.x = x | |
1121 | return PGEN_DONE | |
1122 | ||
1123 | class SimulStepper (PrimeGenEventHandler): | |
1124 | def __init__(me, mul = 2, add = 1, step = 2): | |
1125 | me.step = step | |
1126 | me.mul = mul | |
1127 | me.add = add | |
1128 | def _stepfn(me, step): | |
1129 | if step <= 0: | |
1130 | raise ValueError, 'step must be positive' | |
1131 | if step <= MPW_MAX: | |
1132 | return lambda f: f.step(step) | |
1133 | j = PrimeFilter(step) | |
1134 | return lambda f: f.jump(j) | |
1135 | def pg_begin(me, ev): | |
1136 | x = ev.x | |
1137 | me.lf = PrimeFilter(x) | |
1138 | me.hf = PrimeFilter(x * me.mul + me.add) | |
1139 | me.lstep = me._stepfn(me.step) | |
1140 | me.hstep = me._stepfn(me.step * me.mul) | |
1141 | SimulStepper._cont(me, ev) | |
1142 | def pg_try(me, ev): | |
1143 | me._step() | |
1144 | me._cont(ev) | |
1145 | def _step(me): | |
1146 | me.lstep(me.lf) | |
1147 | me.hstep(me.hf) | |
1148 | def _cont(me, ev): | |
1149 | while me.lf.status == PGEN_FAIL or me.hf.status == PGEN_FAIL: | |
1150 | me._step() | |
1151 | if me.lf.status == PGEN_ABORT or me.hf.status == PGEN_ABORT: | |
1152 | return PGEN_ABORT | |
1153 | ev.x = me.lf.x | |
1154 | if me.lf.status == PGEN_DONE and me.hf.status == PGEN_DONE: | |
1155 | return PGEN_DONE | |
1156 | return PGEN_TRY | |
1157 | def pg_done(me, ev): | |
1158 | del me.lf | |
1159 | del me.hf | |
1160 | del me.lstep | |
1161 | del me.hstep | |
1162 | ||
1163 | class SimulTester (PrimeGenEventHandler): | |
1164 | def __init__(me, mul = 2, add = 1): | |
1165 | me.mul = mul | |
1166 | me.add = add | |
1167 | def pg_begin(me, ev): | |
1168 | x = ev.x | |
1169 | me.lr = RabinMiller(x) | |
1170 | me.hr = RabinMiller(x * me.mul + me.add) | |
1171 | def pg_try(me, ev): | |
1172 | lst = me.lr.test(ev.rng.range(me.lr.x)) | |
1173 | if lst != PGEN_PASS and lst != PGEN_DONE: | |
1174 | return lst | |
1175 | rst = me.hr.test(ev.rng.range(me.hr.x)) | |
1176 | if rst != PGEN_PASS and rst != PGEN_DONE: | |
1177 | return rst | |
1178 | if lst == PGEN_DONE and rst == PGEN_DONE: | |
1179 | return PGEN_DONE | |
1180 | return PGEN_PASS | |
1181 | def pg_done(me, ev): | |
1182 | del me.lr | |
1183 | del me.hr | |
1184 | ||
1185 | def sgprime(start, step = 2, name = 'p', event = pgen_nullev, nsteps = 0): | |
1186 | start = MP(start) | |
1187 | return pgen(start, name, SimulStepper(step = step), SimulTester(), event, | |
00401529 | 1188 | nsteps, RabinMiller.iters(start.nbits)) |
d7ab1bab | 1189 | |
1190 | def findprimitive(mod, hh = [], exp = None, name = 'g', event = pgen_nullev): | |
1191 | return pgen(0, name, PrimitiveStepper(), PrimitiveTester(mod, hh, exp), | |
00401529 | 1192 | event, 0, 1) |
d7ab1bab | 1193 | |
1194 | def kcdsaprime(pbits, qbits, rng = rand, | |
00401529 | 1195 | event = pgen_nullev, name = 'p', nsteps = 0): |
d7ab1bab | 1196 | hbits = pbits - qbits |
1197 | h = pgen(rng.mp(hbits, 1), name + ' [h]', | |
00401529 MW |
1198 | PrimeGenStepper(2), PrimeGenTester(), |
1199 | event, nsteps, RabinMiller.iters(hbits)) | |
d7ab1bab | 1200 | q = pgen(rng.mp(qbits, 1), name, SimulStepper(2 * h, 1, 2), |
00401529 | 1201 | SimulTester(2 * h, 1), event, nsteps, RabinMiller.iters(qbits)) |
d7ab1bab | 1202 | p = 2 * q * h + 1 |
1203 | return p, q, h | |
1204 | ||
1205 | #----- That's all, folks ---------------------------------------------------- |