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('-', '_').translate(None, '/')] = c
60 for c in gccrands.itervalues():
61 d[c.name.replace('-', '_').translate(None, '/') + '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 ByteString.__hash__ = str.__hash__
98 bytes = ByteString.fromhex
100 ###--------------------------------------------------------------------------
106 return ctstreq(h, hh)
107 _augment(GHash, _tmp)
108 _augment(Poly1305Hash, _tmp)
110 ###--------------------------------------------------------------------------
111 ### Multiprecision integers and binary polynomials.
114 if isinstance(x, BaseRat): return x._n, x._d
116 class BaseRat (object):
117 """Base class implementing fields of fractions over Euclidean domains."""
118 def __new__(cls, a, b):
119 a, b = cls.RING(a), cls.RING(b)
123 me = super(BaseRat, cls).__new__(cls)
128 def numer(me): return me._n
130 def denom(me): return me._d
131 def __str__(me): return '%s/%s' % (me._n, me._d)
132 def __repr__(me): return '%s(%s, %s)' % (type(me).__name__, me._n, me._d)
134 def __add__(me, you):
135 n, d = _split_rat(you)
136 return type(me)(me._n*d + n*me._d, d*me._d)
138 def __sub__(me, you):
139 n, d = _split_rat(you)
140 return type(me)(me._n*d - n*me._d, d*me._d)
141 def __rsub__(me, you):
142 n, d = _split_rat(you)
143 return type(me)(n*me._d - me._n*d, d*me._d)
144 def __mul__(me, you):
145 n, d = _split_rat(you)
146 return type(me)(me._n*n, me._d*d)
147 def __div__(me, you):
148 n, d = _split_rat(you)
149 return type(me)(me._n*d, me._d*n)
150 def __rdiv__(me, you):
151 n, d = _split_rat(you)
152 return type(me)(me._d*n, me._n*d)
153 def __cmp__(me, you):
154 n, d = _split_rat(you)
155 return type(me)(me._n*d, n*me._d)
156 def __rcmp__(me, you):
157 n, d = _split_rat(you)
158 return cmp(n*me._d, me._n*d)
160 class IntRat (BaseRat):
163 class GFRat (BaseRat):
167 def negp(x): return x < 0
168 def posp(x): return x > 0
169 def zerop(x): return x == 0
170 def oddp(x): return x.testbit(0)
171 def evenp(x): return not x.testbit(0)
172 def mont(x): return MPMont(x)
173 def barrett(x): return MPBarrett(x)
174 def reduce(x): return MPReduce(x)
175 def __div__(me, you): return IntRat(me, you)
176 def __rdiv__(me, you): return IntRat(you, me)
180 def zerop(x): return x == 0
181 def reduce(x): return GFReduce(x)
182 def trace(x, y): return x.reduce().trace(y)
183 def halftrace(x, y): return x.reduce().halftrace(y)
184 def modsqrt(x, y): return x.reduce().sqrt(y)
185 def quadsolve(x, y): return x.reduce().quadsolve(y)
186 def __div__(me, you): return GFRat(me, you)
187 def __rdiv__(me, you): return GFRat(you, me)
192 'product(ITERABLE) or product(I, ...) -> PRODUCT'
193 return MPMul(*arg).done()
194 product = staticmethod(product)
195 _augment(MPMul, _tmp)
197 ###--------------------------------------------------------------------------
201 def fromstring(str): return _checkend(Field.parse(str))
202 fromstring = staticmethod(fromstring)
203 _augment(Field, _tmp)
206 def __repr__(me): return '%s(%sL)' % (type(me).__name__, me.p)
207 def __hash__(me): return 0x114401de ^ hash(me.p)
208 def ec(me, a, b): return ECPrimeProjCurve(me, a, b)
209 _augment(PrimeField, _tmp)
212 def __repr__(me): return '%s(%sL)' % (type(me).__name__, hex(me.p))
213 def ec(me, a, b): return ECBinProjCurve(me, a, b)
214 _augment(BinField, _tmp)
217 def __hash__(me): return 0x23e4701c ^ hash(me.p)
218 _augment(BinPolyField, _tmp)
224 h ^= 2*hash(me.beta) & 0xffffffff
226 _augment(BinNormField, _tmp)
229 def __str__(me): return str(me.value)
230 def __repr__(me): return '%s(%s)' % (repr(me.field), repr(me.value))
233 ###--------------------------------------------------------------------------
238 return '%s(%r, %s, %s)' % (type(me).__name__, me.field, me.a, me.b)
240 return ecpt.frombuf(me, s)
242 return ecpt.fromraw(me, s)
245 _augment(ECCurve, _tmp)
251 h ^= 2*hash(me.a) ^ 0xffffffff
252 h ^= 5*hash(me.b) ^ 0xffffffff
254 _augment(ECPrimeCurve, _tmp)
260 h ^= 2*hash(me.a) ^ 0xffffffff
261 h ^= 5*hash(me.b) ^ 0xffffffff
263 _augment(ECBinCurve, _tmp)
267 if not me: return 'ECPt()'
268 return 'ECPt(%s, %s)' % (me.ix, me.iy)
270 if not me: return 'inf'
271 return '(%s, %s)' % (me.ix, me.iy)
276 return 'ECInfo(curve = %r, G = %r, r = %s, h = %s)' % \
277 (me.curve, me.G, me.r, me.h)
281 h ^= 2*hash(me.G) & 0xffffffff
285 _augment(ECInfo, _tmp)
289 if not me: return '%r()' % (me.curve)
290 return '%r(%s, %s)' % (me.curve, me.x, me.y)
292 if not me: return 'inf'
293 return '(%s, %s)' % (me.x, me.y)
294 _augment(ECPtCurve, _tmp)
296 ###--------------------------------------------------------------------------
300 def __repr__(me): return 'KeySZAny(%d)' % me.default
301 def check(me, sz): return True
302 def best(me, sz): return sz
303 _augment(KeySZAny, _tmp)
307 return 'KeySZRange(%d, %d, %d, %d)' % \
308 (me.default, me.min, me.max, me.mod)
309 def check(me, sz): return me.min <= sz <= me.max and sz % me.mod == 0
311 if sz < me.min: raise ValueError, 'key too small'
312 elif sz > me.max: return me.max
313 else: return sz - (sz % me.mod)
314 _augment(KeySZRange, _tmp)
317 def __repr__(me): return 'KeySZSet(%d, %s)' % (me.default, me.set)
318 def check(me, sz): return sz in me.set
322 if found < i <= sz: found = i
323 if found < 0: raise ValueError, 'key too small'
325 _augment(KeySZSet, _tmp)
327 ###--------------------------------------------------------------------------
332 return '%s(p = %s, r = %s, g = %s)' % \
333 (type(me).__name__, me.p, me.r, me.g)
334 _augment(FGInfo, _tmp)
337 def group(me): return PrimeGroup(me)
338 _augment(DHInfo, _tmp)
341 def group(me): return BinGroup(me)
342 _augment(BinDHInfo, _tmp)
346 return '%s(%r)' % (type(me).__name__, me.info)
347 _augment(Group, _tmp)
354 h ^= 2*hash(info.r) & 0xffffffff
355 h ^= 5*hash(info.g) & 0xffffffff
357 _augment(PrimeGroup, _tmp)
364 h ^= 2*hash(info.r) & 0xffffffff
365 h ^= 5*hash(info.g) & 0xffffffff
367 _augment(BinGroup, _tmp)
370 def __hash__(me): return 0x0ec23dab ^ hash(me.info)
371 _augment(ECGroup, _tmp)
375 return '%r(%r)' % (me.group, str(me))
378 ###--------------------------------------------------------------------------
379 ### RSA encoding techniques.
381 class PKCS1Crypt (object):
382 def __init__(me, ep = '', rng = rand):
385 def encode(me, msg, nbits):
386 return _base._p1crypt_encode(msg, nbits, me.ep, me.rng)
387 def decode(me, ct, nbits):
388 return _base._p1crypt_decode(ct, nbits, me.ep, me.rng)
390 class PKCS1Sig (object):
391 def __init__(me, ep = '', rng = rand):
394 def encode(me, msg, nbits):
395 return _base._p1sig_encode(msg, nbits, me.ep, me.rng)
396 def decode(me, msg, sig, nbits):
397 return _base._p1sig_decode(msg, sig, nbits, me.ep, me.rng)
400 def __init__(me, mgf = sha_mgf, hash = sha, ep = '', rng = rand):
405 def encode(me, msg, nbits):
406 return _base._oaep_encode(msg, nbits, me.mgf, me.hash, me.ep, me.rng)
407 def decode(me, ct, nbits):
408 return _base._oaep_decode(ct, nbits, me.mgf, me.hash, me.ep, me.rng)
411 def __init__(me, mgf = sha_mgf, hash = sha, saltsz = None, rng = rand):
418 def encode(me, msg, nbits):
419 return _base._pss_encode(msg, nbits, me.mgf, me.hash, me.saltsz, me.rng)
420 def decode(me, msg, sig, nbits):
421 return _base._pss_decode(msg, sig, nbits,
422 me.mgf, me.hash, me.saltsz, me.rng)
425 def encrypt(me, msg, enc):
426 return me.pubop(enc.encode(msg, me.n.nbits))
427 def verify(me, msg, sig, enc):
428 if msg is None: return enc.decode(msg, me.pubop(sig), me.n.nbits)
430 x = enc.decode(msg, me.pubop(sig), me.n.nbits)
431 return x is None or x == msg
434 _augment(RSAPub, _tmp)
437 def decrypt(me, ct, enc): return enc.decode(me.privop(ct), me.n.nbits)
438 def sign(me, msg, enc): return me.privop(enc.encode(msg, me.n.nbits))
439 _augment(RSAPriv, _tmp)
441 ###--------------------------------------------------------------------------
442 ### Built-in named curves and prime groups.
444 class _groupmap (object):
445 def __init__(me, map, nth):
448 me.i = [None] * (max(map.values()) + 1)
450 return '{%s}' % ', '.join(['%r: %r' % (k, me[k]) for k in me])
451 def __contains__(me, k):
453 def __getitem__(me, k):
458 def __setitem__(me, k, v):
459 raise TypeError, "immutable object"
471 return [k for k in me]
473 return [me[k] for k in me]
475 return [(k, me[k]) for k in me]
476 eccurves = _groupmap(_base._eccurves, ECInfo._curven)
477 primegroups = _groupmap(_base._pgroups, DHInfo._groupn)
478 bingroups = _groupmap(_base._bingroups, BinDHInfo._groupn)
480 ###--------------------------------------------------------------------------
481 ### Prime number generation.
483 class PrimeGenEventHandler (object):
484 def pg_begin(me, ev):
488 def pg_abort(me, ev):
495 class SophieGermainStepJump (object):
496 def pg_begin(me, ev):
497 me.lf = PrimeFilter(ev.x)
498 me.hf = me.lf.muladd(2, 1)
504 while me.lf.status == PGEN_FAIL or me.hf.status == PGEN_FAIL:
506 if me.lf.status == PGEN_ABORT or me.hf.status == PGEN_ABORT:
509 if me.lf.status == PGEN_DONE and me.hf.status == PGEN_DONE:
516 class SophieGermainStepper (SophieGermainStepJump):
517 def __init__(me, step):
524 class SophieGermainJumper (SophieGermainStepJump):
525 def __init__(me, jump):
526 me.ljump = PrimeFilter(jump);
527 me.hjump = me.ljump.muladd(2, 0)
534 SophieGermainStepJump.pg_done(me, ev)
536 class SophieGermainTester (object):
539 def pg_begin(me, ev):
540 me.lr = RabinMiller(ev.x)
541 me.hr = RabinMiller(2 * ev.x + 1)
543 lst = me.lr.test(ev.rng.range(me.lr.x))
544 if lst != PGEN_PASS and lst != PGEN_DONE:
546 rst = me.hr.test(ev.rng.range(me.hr.x))
547 if rst != PGEN_PASS and rst != PGEN_DONE:
549 if lst == PGEN_DONE and rst == PGEN_DONE:
556 class PrimitiveStepper (PrimeGenEventHandler):
562 def pg_begin(me, ev):
563 me.i = iter(smallprimes)
566 class PrimitiveTester (PrimeGenEventHandler):
567 def __init__(me, mod, hh = [], exp = None):
573 if me.exp is not None:
574 x = me.mod.exp(x, me.exp)
575 if x == 1: return PGEN_FAIL
577 if me.mod.exp(x, h) == 1: return PGEN_FAIL
581 class SimulStepper (PrimeGenEventHandler):
582 def __init__(me, mul = 2, add = 1, step = 2):
586 def _stepfn(me, step):
588 raise ValueError, 'step must be positive'
590 return lambda f: f.step(step)
591 j = PrimeFilter(step)
592 return lambda f: f.jump(j)
593 def pg_begin(me, ev):
595 me.lf = PrimeFilter(x)
596 me.hf = PrimeFilter(x * me.mul + me.add)
597 me.lstep = me._stepfn(me.step)
598 me.hstep = me._stepfn(me.step * me.mul)
599 SimulStepper._cont(me, ev)
607 while me.lf.status == PGEN_FAIL or me.hf.status == PGEN_FAIL:
609 if me.lf.status == PGEN_ABORT or me.hf.status == PGEN_ABORT:
612 if me.lf.status == PGEN_DONE and me.hf.status == PGEN_DONE:
621 class SimulTester (PrimeGenEventHandler):
622 def __init__(me, mul = 2, add = 1):
625 def pg_begin(me, ev):
627 me.lr = RabinMiller(x)
628 me.hr = RabinMiller(x * me.mul + me.add)
630 lst = me.lr.test(ev.rng.range(me.lr.x))
631 if lst != PGEN_PASS and lst != PGEN_DONE:
633 rst = me.hr.test(ev.rng.range(me.hr.x))
634 if rst != PGEN_PASS and rst != PGEN_DONE:
636 if lst == PGEN_DONE and rst == PGEN_DONE:
643 def sgprime(start, step = 2, name = 'p', event = pgen_nullev, nsteps = 0):
645 return pgen(start, name, SimulStepper(step = step), SimulTester(), event,
646 nsteps, RabinMiller.iters(start.nbits))
648 def findprimitive(mod, hh = [], exp = None, name = 'g', event = pgen_nullev):
649 return pgen(0, name, PrimitiveStepper(), PrimitiveTester(mod, hh, exp),
652 def kcdsaprime(pbits, qbits, rng = rand,
653 event = pgen_nullev, name = 'p', nsteps = 0):
654 hbits = pbits - qbits
655 h = pgen(rng.mp(hbits, 1), name + ' [h]',
656 PrimeGenStepper(2), PrimeGenTester(),
657 event, nsteps, RabinMiller.iters(hbits))
658 q = pgen(rng.mp(qbits, 1), name, SimulStepper(2 * h, 1, 2),
659 SimulTester(2 * h, 1), event, nsteps, RabinMiller.iters(qbits))
663 #----- That's all, folks ----------------------------------------------------