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.
27 import types as _types
28 from binascii import hexlify as _hexify, unhexlify as _unhexify
29 from sys import argv as _argv
31 ###--------------------------------------------------------------------------
34 ## For the benefit of the default keyreporter, we need the program na,e.
37 ## Initialize the module. Drag in the static methods of the various
38 ## classes; create names for the various known crypto algorithms.
45 for i in ['MP', 'GF', 'Field',
46 'ECPt', 'ECPtCurve', 'ECCurve', 'ECInfo',
47 'DHInfo', 'BinDHInfo', 'RSAPriv', 'BBSPriv',
48 'PrimeFilter', 'RabinMiller',
56 setattr(c, j[plen:], classmethod(b[j]))
57 for i in [gcciphers, gchashes, gcmacs, gcprps]:
58 for c in i.itervalues():
59 d[c.name.replace('-', '_')] = c
60 for c in gccrands.itervalues():
61 d[c.name.replace('-', '_') + 'rand'] = c
64 ## A handy function for our work: add the methods of a named class to an
65 ## existing class. This is how we write the Python-implemented parts of our
70 if type(a) is _types.MethodType:
72 elif type(a) not in (_types.FunctionType, staticmethod, classmethod):
76 ## Parsing functions tend to return the object parsed and the remainder of
77 ## the input. This checks that the remainder is input and, if so, returns
82 raise SyntaxError, 'junk at end of string'
85 ###--------------------------------------------------------------------------
90 return ByteString(_unhexify(x))
91 fromhex = staticmethod(fromhex)
95 return 'bytes(%r)' % hex(me)
96 _augment(ByteString, _tmp)
97 bytes = ByteString.fromhex
99 ###--------------------------------------------------------------------------
100 ### Multiprecision integers and binary polynomials.
103 if isinstance(x, BaseRat): return x._n, x._d
105 class BaseRat (object):
106 """Base class implementing fields of fractions over Euclidean domains."""
107 def __new__(cls, a, b):
108 a, b = cls.RING(a), cls.RING(b)
112 me = super(BaseRat, cls).__new__(cls)
117 def numer(me): return me._n
119 def denom(me): return me._d
120 def __str__(me): return '%s/%s' % (me._n, me._d)
121 def __repr__(me): return '%s(%s, %s)' % (type(me).__name__, me._n, me._d)
123 def __add__(me, you):
124 n, d = _split_rat(you)
125 return type(me)(me._n*d + n*me._d, d*me._d)
127 def __sub__(me, you):
128 n, d = _split_rat(you)
129 return type(me)(me._n*d - n*me._d, d*me._d)
130 def __rsub__(me, you):
131 n, d = _split_rat(you)
132 return type(me)(n*me._d - me._n*d, d*me._d)
133 def __mul__(me, you):
134 n, d = _split_rat(you)
135 return type(me)(me._n*n, me._d*d)
136 def __div__(me, you):
137 n, d = _split_rat(you)
138 return type(me)(me._n*d, me._d*n)
139 def __rdiv__(me, you):
140 n, d = _split_rat(you)
141 return type(me)(me._d*n, me._n*d)
142 def __cmp__(me, you):
143 n, d = _split_rat(you)
144 return type(me)(me._n*d, n*me._d)
145 def __rcmp__(me, you):
146 n, d = _split_rat(you)
147 return cmp(n*me._d, me._n*d)
149 class IntRat (BaseRat):
152 class GFRat (BaseRat):
156 def negp(x): return x < 0
157 def posp(x): return x > 0
158 def zerop(x): return x == 0
159 def oddp(x): return x.testbit(0)
160 def evenp(x): return not x.testbit(0)
161 def mont(x): return MPMont(x)
162 def barrett(x): return MPBarrett(x)
163 def reduce(x): return MPReduce(x)
164 def __div__(me, you): return IntRat(me, you)
165 def __rdiv__(me, you): return IntRat(you, me)
169 def zerop(x): return x == 0
170 def reduce(x): return GFReduce(x)
171 def trace(x, y): return x.reduce().trace(y)
172 def halftrace(x, y): return x.reduce().halftrace(y)
173 def modsqrt(x, y): return x.reduce().sqrt(y)
174 def quadsolve(x, y): return x.reduce().quadsolve(y)
175 def __div__(me, you): return GFRat(me, you)
176 def __rdiv__(me, you): return GFRat(you, me)
181 'product(ITERABLE) or product(I, ...) -> PRODUCT'
182 return MPMul(*arg).done()
183 product = staticmethod(product)
184 _augment(MPMul, _tmp)
186 ###--------------------------------------------------------------------------
190 def fromstring(str): return _checkend(Field.parse(str))
191 fromstring = staticmethod(fromstring)
192 _augment(Field, _tmp)
195 def __repr__(me): return '%s(%sL)' % (type(me).__name__, me.p)
196 def __hash__(me): return 0x114401de ^ hash(me.p)
197 def ec(me, a, b): return ECPrimeProjCurve(me, a, b)
198 _augment(PrimeField, _tmp)
201 def __repr__(me): return '%s(%sL)' % (type(me).__name__, hex(me.p))
202 def ec(me, a, b): return ECBinProjCurve(me, a, b)
203 _augment(BinField, _tmp)
206 def __hash__(me): return 0x23e4701c ^ hash(me.p)
207 _augment(BinPolyField, _tmp)
213 h ^= 2*hash(me.beta) & 0xffffffff
215 _augment(BinNormField, _tmp)
218 def __str__(me): return str(me.value)
219 def __repr__(me): return '%s(%s)' % (repr(me.field), repr(me.value))
222 ###--------------------------------------------------------------------------
227 return '%s(%r, %s, %s)' % (type(me).__name__, me.field, me.a, me.b)
229 return ecpt.frombuf(me, s)
231 return ecpt.fromraw(me, s)
234 _augment(ECCurve, _tmp)
240 h ^= 2*hash(me.a) ^ 0xffffffff
241 h ^= 5*hash(me.b) ^ 0xffffffff
243 _augment(ECPrimeCurve, _tmp)
249 h ^= 2*hash(me.a) ^ 0xffffffff
250 h ^= 5*hash(me.b) ^ 0xffffffff
252 _augment(ECBinCurve, _tmp)
256 if not me: return 'ECPt()'
257 return 'ECPt(%s, %s)' % (me.ix, me.iy)
259 if not me: return 'inf'
260 return '(%s, %s)' % (me.ix, me.iy)
265 return 'ECInfo(curve = %r, G = %r, r = %s, h = %s)' % \
266 (me.curve, me.G, me.r, me.h)
270 h ^= 2*hash(me.G) & 0xffffffff
274 _augment(ECInfo, _tmp)
278 if not me: return '%r()' % (me.curve)
279 return '%r(%s, %s)' % (me.curve, me.x, me.y)
281 if not me: return 'inf'
282 return '(%s, %s)' % (me.x, me.y)
283 _augment(ECPtCurve, _tmp)
285 ###--------------------------------------------------------------------------
289 def __repr__(me): return 'KeySZAny(%d)' % me.default
290 def check(me, sz): return True
291 def best(me, sz): return sz
292 _augment(KeySZAny, _tmp)
296 return 'KeySZRange(%d, %d, %d, %d)' % \
297 (me.default, me.min, me.max, me.mod)
298 def check(me, sz): return me.min <= sz <= me.max and sz % me.mod == 0
300 if sz < me.min: raise ValueError, 'key too small'
301 elif sz > me.max: return me.max
302 else: return sz - (sz % me.mod)
303 _augment(KeySZRange, _tmp)
306 def __repr__(me): return 'KeySZSet(%d, %s)' % (me.default, me.set)
307 def check(me, sz): return sz in me.set
311 if found < i <= sz: found = i
312 if found < 0: raise ValueError, 'key too small'
314 _augment(KeySZSet, _tmp)
316 ###--------------------------------------------------------------------------
321 return '%s(p = %s, r = %s, g = %s)' % \
322 (type(me).__name__, me.p, me.r, me.g)
323 _augment(FGInfo, _tmp)
326 def group(me): return PrimeGroup(me)
327 _augment(DHInfo, _tmp)
330 def group(me): return BinGroup(me)
331 _augment(BinDHInfo, _tmp)
335 return '%s(%r)' % (type(me).__name__, me.info)
336 _augment(Group, _tmp)
343 h ^= 2*hash(info.r) & 0xffffffff
344 h ^= 5*hash(info.g) & 0xffffffff
346 _augment(PrimeGroup, _tmp)
353 h ^= 2*hash(info.r) & 0xffffffff
354 h ^= 5*hash(info.g) & 0xffffffff
356 _augment(BinGroup, _tmp)
359 def __hash__(me): return 0x0ec23dab ^ hash(me.info)
360 _augment(ECGroup, _tmp)
364 return '%r(%r)' % (me.group, str(me))
367 ###--------------------------------------------------------------------------
368 ### RSA encoding techniques.
370 class PKCS1Crypt (object):
371 def __init__(me, ep = '', rng = rand):
374 def encode(me, msg, nbits):
375 return _base._p1crypt_encode(msg, nbits, me.ep, me.rng)
376 def decode(me, ct, nbits):
377 return _base._p1crypt_decode(ct, nbits, me.ep, me.rng)
379 class PKCS1Sig (object):
380 def __init__(me, ep = '', rng = rand):
383 def encode(me, msg, nbits):
384 return _base._p1sig_encode(msg, nbits, me.ep, me.rng)
385 def decode(me, msg, sig, nbits):
386 return _base._p1sig_decode(msg, sig, nbits, me.ep, me.rng)
389 def __init__(me, mgf = sha_mgf, hash = sha, ep = '', rng = rand):
394 def encode(me, msg, nbits):
395 return _base._oaep_encode(msg, nbits, me.mgf, me.hash, me.ep, me.rng)
396 def decode(me, ct, nbits):
397 return _base._oaep_decode(ct, nbits, me.mgf, me.hash, me.ep, me.rng)
400 def __init__(me, mgf = sha_mgf, hash = sha, saltsz = None, rng = rand):
407 def encode(me, msg, nbits):
408 return _base._pss_encode(msg, nbits, me.mgf, me.hash, me.saltsz, me.rng)
409 def decode(me, msg, sig, nbits):
410 return _base._pss_decode(msg, sig, nbits,
411 me.mgf, me.hash, me.saltsz, me.rng)
414 def encrypt(me, msg, enc):
415 return me.pubop(enc.encode(msg, me.n.nbits))
416 def verify(me, msg, sig, enc):
417 if msg is None: return enc.decode(msg, me.pubop(sig), me.n.nbits)
419 x = enc.decode(msg, me.pubop(sig), me.n.nbits)
420 return x is None or x == msg
423 _augment(RSAPub, _tmp)
426 def decrypt(me, ct, enc): return enc.decode(me.privop(ct), me.n.nbits)
427 def sign(me, msg, enc): return me.privop(enc.encode(msg, me.n.nbits))
428 _augment(RSAPriv, _tmp)
430 ###--------------------------------------------------------------------------
431 ### Built-in named curves and prime groups.
433 class _groupmap (object):
434 def __init__(me, map, nth):
437 me.i = [None] * (max(map.values()) + 1)
439 return '{%s}' % ', '.join(['%r: %r' % (k, me[k]) for k in me])
440 def __contains__(me, k):
442 def __getitem__(me, k):
447 def __setitem__(me, k, v):
448 raise TypeError, "immutable object"
460 return [k for k in me]
462 return [me[k] for k in me]
464 return [(k, me[k]) for k in me]
465 eccurves = _groupmap(_base._eccurves, ECInfo._curven)
466 primegroups = _groupmap(_base._pgroups, DHInfo._groupn)
467 bingroups = _groupmap(_base._bingroups, BinDHInfo._groupn)
469 ###--------------------------------------------------------------------------
470 ### Prime number generation.
472 class PrimeGenEventHandler (object):
473 def pg_begin(me, ev):
477 def pg_abort(me, ev):
484 class SophieGermainStepJump (object):
485 def pg_begin(me, ev):
486 me.lf = PrimeFilter(ev.x)
487 me.hf = me.lf.muladd(2, 1)
493 while me.lf.status == PGEN_FAIL or me.hf.status == PGEN_FAIL:
495 if me.lf.status == PGEN_ABORT or me.hf.status == PGEN_ABORT:
498 if me.lf.status == PGEN_DONE and me.hf.status == PGEN_DONE:
505 class SophieGermainStepper (SophieGermainStepJump):
506 def __init__(me, step):
513 class SophieGermainJumper (SophieGermainStepJump):
514 def __init__(me, jump):
515 me.ljump = PrimeFilter(jump);
516 me.hjump = me.ljump.muladd(2, 0)
523 SophieGermainStepJump.pg_done(me, ev)
525 class SophieGermainTester (object):
528 def pg_begin(me, ev):
529 me.lr = RabinMiller(ev.x)
530 me.hr = RabinMiller(2 * ev.x + 1)
532 lst = me.lr.test(ev.rng.range(me.lr.x))
533 if lst != PGEN_PASS and lst != PGEN_DONE:
535 rst = me.hr.test(ev.rng.range(me.hr.x))
536 if rst != PGEN_PASS and rst != PGEN_DONE:
538 if lst == PGEN_DONE and rst == PGEN_DONE:
545 class PrimitiveStepper (PrimeGenEventHandler):
551 def pg_begin(me, ev):
552 me.i = iter(smallprimes)
555 class PrimitiveTester (PrimeGenEventHandler):
556 def __init__(me, mod, hh = [], exp = None):
562 if me.exp is not None:
563 x = me.mod.exp(x, me.exp)
564 if x == 1: return PGEN_FAIL
566 if me.mod.exp(x, h) == 1: return PGEN_FAIL
570 class SimulStepper (PrimeGenEventHandler):
571 def __init__(me, mul = 2, add = 1, step = 2):
575 def _stepfn(me, step):
577 raise ValueError, 'step must be positive'
579 return lambda f: f.step(step)
580 j = PrimeFilter(step)
581 return lambda f: f.jump(j)
582 def pg_begin(me, ev):
584 me.lf = PrimeFilter(x)
585 me.hf = PrimeFilter(x * me.mul + me.add)
586 me.lstep = me._stepfn(me.step)
587 me.hstep = me._stepfn(me.step * me.mul)
588 SimulStepper._cont(me, ev)
596 while me.lf.status == PGEN_FAIL or me.hf.status == PGEN_FAIL:
598 if me.lf.status == PGEN_ABORT or me.hf.status == PGEN_ABORT:
601 if me.lf.status == PGEN_DONE and me.hf.status == PGEN_DONE:
610 class SimulTester (PrimeGenEventHandler):
611 def __init__(me, mul = 2, add = 1):
614 def pg_begin(me, ev):
616 me.lr = RabinMiller(x)
617 me.hr = RabinMiller(x * me.mul + me.add)
619 lst = me.lr.test(ev.rng.range(me.lr.x))
620 if lst != PGEN_PASS and lst != PGEN_DONE:
622 rst = me.hr.test(ev.rng.range(me.hr.x))
623 if rst != PGEN_PASS and rst != PGEN_DONE:
625 if lst == PGEN_DONE and rst == PGEN_DONE:
632 def sgprime(start, step = 2, name = 'p', event = pgen_nullev, nsteps = 0):
634 return pgen(start, name, SimulStepper(step = step), SimulTester(), event,
635 nsteps, RabinMiller.iters(start.nbits))
637 def findprimitive(mod, hh = [], exp = None, name = 'g', event = pgen_nullev):
638 return pgen(0, name, PrimitiveStepper(), PrimitiveTester(mod, hh, exp),
641 def kcdsaprime(pbits, qbits, rng = rand,
642 event = pgen_nullev, name = 'p', nsteps = 0):
643 hbits = pbits - qbits
644 h = pgen(rng.mp(hbits, 1), name + ' [h]',
645 PrimeGenStepper(2), PrimeGenTester(),
646 event, nsteps, RabinMiller.iters(hbits))
647 q = pgen(rng.mp(qbits, 1), name, SimulStepper(2 * h, 1, 2),
648 SimulTester(2 * h, 1), event, nsteps, RabinMiller.iters(qbits))
652 #----- That's all, folks ----------------------------------------------------