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 def negp(x): return x < 0
104 def posp(x): return x > 0
105 def zerop(x): return x == 0
106 def oddp(x): return x.testbit(0)
107 def evenp(x): return not x.testbit(0)
108 def mont(x): return MPMont(x)
109 def barrett(x): return MPBarrett(x)
110 def reduce(x): return MPReduce(x)
114 def zerop(x): return x == 0
115 def reduce(x): return GFReduce(x)
116 def trace(x, y): return x.reduce().trace(y)
117 def halftrace(x, y): return x.reduce().halftrace(y)
118 def modsqrt(x, y): return x.reduce().sqrt(y)
119 def quadsolve(x, y): return x.reduce().quadsolve(y)
124 'product(ITERABLE) or product(I, ...) -> PRODUCT'
125 return MPMul(*arg).done()
126 product = staticmethod(product)
127 _augment(MPMul, _tmp)
129 ###--------------------------------------------------------------------------
133 def fromstring(str): return _checkend(Field.parse(str))
134 fromstring = staticmethod(fromstring)
135 _augment(Field, _tmp)
138 def __repr__(me): return '%s(%sL)' % (type(me).__name__, me.p)
139 def ec(me, a, b): return ECPrimeProjCurve(me, a, b)
140 _augment(PrimeField, _tmp)
143 def __repr__(me): return '%s(%sL)' % (type(me).__name__, hex(me.p))
144 def ec(me, a, b): return ECBinProjCurve(me, a, b)
145 _augment(BinField, _tmp)
148 def __str__(me): return str(me.value)
149 def __repr__(me): return '%s(%s)' % (repr(me.field), repr(me.value))
152 ###--------------------------------------------------------------------------
157 return '%s(%r, %s, %s)' % (type(me).__name__, me.field, me.a, me.b)
159 return ecpt.frombuf(me, s)
161 return ecpt.fromraw(me, s)
164 _augment(ECCurve, _tmp)
168 if not me: return 'ECPt()'
169 return 'ECPt(%s, %s)' % (me.ix, me.iy)
171 if not me: return 'inf'
172 return '(%s, %s)' % (me.ix, me.iy)
177 return 'ECInfo(curve = %r, G = %r, r = %s, h = %s)' % \
178 (me.curve, me.G, me.r, me.h)
181 _augment(ECInfo, _tmp)
185 if not me: return '%r()' % (me.curve)
186 return '%r(%s, %s)' % (me.curve, me.x, me.y)
188 if not me: return 'inf'
189 return '(%s, %s)' % (me.x, me.y)
190 _augment(ECPtCurve, _tmp)
192 ###--------------------------------------------------------------------------
196 def __repr__(me): return 'KeySZAny(%d)' % me.default
197 def check(me, sz): return True
198 def best(me, sz): return sz
199 _augment(KeySZAny, _tmp)
203 return 'KeySZRange(%d, %d, %d, %d)' % \
204 (me.default, me.min, me.max, me.mod)
205 def check(me, sz): return me.min <= sz <= me.max and sz % me.mod == 0
207 if sz < me.min: raise ValueError, 'key too small'
208 elif sz > me.max: return me.max
209 else: return sz - (sz % me.mod)
210 _augment(KeySZRange, _tmp)
213 def __repr__(me): return 'KeySZSet(%d, %s)' % (me.default, me.set)
214 def check(me, sz): return sz in me.set
218 if found < i <= sz: found = i
219 if found < 0: raise ValueError, 'key too small'
221 _augment(KeySZSet, _tmp)
223 ###--------------------------------------------------------------------------
228 return '%s(p = %s, r = %s, g = %s)' % \
229 (type(me).__name__, me.p, me.r, me.g)
230 _augment(FGInfo, _tmp)
233 def group(me): return PrimeGroup(me)
234 _augment(DHInfo, _tmp)
237 def group(me): return BinGroup(me)
238 _augment(BinDHInfo, _tmp)
242 return '%s(%r)' % (type(me).__name__, me.info)
243 _augment(Group, _tmp)
247 return '%r(%r)' % (me.group, str(me))
250 ###--------------------------------------------------------------------------
251 ### RSA encoding techniques.
253 class PKCS1Crypt (object):
254 def __init__(me, ep = '', rng = rand):
257 def encode(me, msg, nbits):
258 return _base._p1crypt_encode(msg, nbits, me.ep, me.rng)
259 def decode(me, ct, nbits):
260 return _base._p1crypt_decode(ct, nbits, me.ep, me.rng)
262 class PKCS1Sig (object):
263 def __init__(me, ep = '', rng = rand):
266 def encode(me, msg, nbits):
267 return _base._p1sig_encode(msg, nbits, me.ep, me.rng)
268 def decode(me, msg, sig, nbits):
269 return _base._p1sig_decode(msg, sig, nbits, me.ep, me.rng)
272 def __init__(me, mgf = sha_mgf, hash = sha, ep = '', rng = rand):
277 def encode(me, msg, nbits):
278 return _base._oaep_encode(msg, nbits, me.mgf, me.hash, me.ep, me.rng)
279 def decode(me, ct, nbits):
280 return _base._oaep_decode(ct, nbits, me.mgf, me.hash, me.ep, me.rng)
283 def __init__(me, mgf = sha_mgf, hash = sha, saltsz = None, rng = rand):
290 def encode(me, msg, nbits):
291 return _base._pss_encode(msg, nbits, me.mgf, me.hash, me.saltsz, me.rng)
292 def decode(me, msg, sig, nbits):
293 return _base._pss_decode(msg, sig, nbits,
294 me.mgf, me.hash, me.saltsz, me.rng)
297 def encrypt(me, msg, enc):
298 return me.pubop(enc.encode(msg, me.n.nbits))
299 def verify(me, msg, sig, enc):
300 if msg is None: return enc.decode(msg, me.pubop(sig), me.n.nbits)
302 x = enc.decode(msg, me.pubop(sig), me.n.nbits)
303 return x is None or x == msg
306 _augment(RSAPub, _tmp)
309 def decrypt(me, ct, enc): return enc.decode(me.privop(ct), me.n.nbits)
310 def sign(me, msg, enc): return me.privop(enc.encode(msg, me.n.nbits))
311 _augment(RSAPriv, _tmp)
313 ###--------------------------------------------------------------------------
314 ### Built-in named curves and prime groups.
316 class _groupmap (object):
317 def __init__(me, map, nth):
320 me.i = [None] * (max(map.values()) + 1)
322 return '{%s}' % ', '.join(['%r: %r' % (k, me[k]) for k in me])
323 def __contains__(me, k):
325 def __getitem__(me, k):
330 def __setitem__(me, k, v):
331 raise TypeError, "immutable object"
343 return [k for k in me]
345 return [me[k] for k in me]
347 return [(k, me[k]) for k in me]
348 eccurves = _groupmap(_base._eccurves, ECInfo._curven)
349 primegroups = _groupmap(_base._pgroups, DHInfo._groupn)
350 bingroups = _groupmap(_base._bingroups, BinDHInfo._groupn)
352 ###--------------------------------------------------------------------------
353 ### Prime number generation.
355 class PrimeGenEventHandler (object):
356 def pg_begin(me, ev):
360 def pg_abort(me, ev):
367 class SophieGermainStepJump (object):
368 def pg_begin(me, ev):
369 me.lf = PrimeFilter(ev.x)
370 me.hf = me.lf.muladd(2, 1)
376 while me.lf.status == PGEN_FAIL or me.hf.status == PGEN_FAIL:
378 if me.lf.status == PGEN_ABORT or me.hf.status == PGEN_ABORT:
381 if me.lf.status == PGEN_DONE and me.hf.status == PGEN_DONE:
388 class SophieGermainStepper (SophieGermainStepJump):
389 def __init__(me, step):
396 class SophieGermainJumper (SophieGermainStepJump):
397 def __init__(me, jump):
398 me.ljump = PrimeFilter(jump);
399 me.hjump = me.ljump.muladd(2, 0)
406 SophieGermainStepJump.pg_done(me, ev)
408 class SophieGermainTester (object):
411 def pg_begin(me, ev):
412 me.lr = RabinMiller(ev.x)
413 me.hr = RabinMiller(2 * ev.x + 1)
415 lst = me.lr.test(ev.rng.range(me.lr.x))
416 if lst != PGEN_PASS and lst != PGEN_DONE:
418 rst = me.hr.test(ev.rng.range(me.hr.x))
419 if rst != PGEN_PASS and rst != PGEN_DONE:
421 if lst == PGEN_DONE and rst == PGEN_DONE:
428 class PrimitiveStepper (PrimeGenEventHandler):
434 def pg_begin(me, ev):
435 me.i = iter(smallprimes)
438 class PrimitiveTester (PrimeGenEventHandler):
439 def __init__(me, mod, hh = [], exp = None):
445 if me.exp is not None:
446 x = me.mod.exp(x, me.exp)
447 if x == 1: return PGEN_FAIL
449 if me.mod.exp(x, h) == 1: return PGEN_FAIL
453 class SimulStepper (PrimeGenEventHandler):
454 def __init__(me, mul = 2, add = 1, step = 2):
458 def _stepfn(me, step):
460 raise ValueError, 'step must be positive'
462 return lambda f: f.step(step)
463 j = PrimeFilter(step)
464 return lambda f: f.jump(j)
465 def pg_begin(me, ev):
467 me.lf = PrimeFilter(x)
468 me.hf = PrimeFilter(x * me.mul + me.add)
469 me.lstep = me._stepfn(me.step)
470 me.hstep = me._stepfn(me.step * me.mul)
471 SimulStepper._cont(me, ev)
479 while me.lf.status == PGEN_FAIL or me.hf.status == PGEN_FAIL:
481 if me.lf.status == PGEN_ABORT or me.hf.status == PGEN_ABORT:
484 if me.lf.status == PGEN_DONE and me.hf.status == PGEN_DONE:
493 class SimulTester (PrimeGenEventHandler):
494 def __init__(me, mul = 2, add = 1):
497 def pg_begin(me, ev):
499 me.lr = RabinMiller(x)
500 me.hr = RabinMiller(x * me.mul + me.add)
502 lst = me.lr.test(ev.rng.range(me.lr.x))
503 if lst != PGEN_PASS and lst != PGEN_DONE:
505 rst = me.hr.test(ev.rng.range(me.hr.x))
506 if rst != PGEN_PASS and rst != PGEN_DONE:
508 if lst == PGEN_DONE and rst == PGEN_DONE:
515 def sgprime(start, step = 2, name = 'p', event = pgen_nullev, nsteps = 0):
517 return pgen(start, name, SimulStepper(step = step), SimulTester(), event,
518 nsteps, RabinMiller.iters(start.nbits))
520 def findprimitive(mod, hh = [], exp = None, name = 'g', event = pgen_nullev):
521 return pgen(0, name, PrimitiveStepper(), PrimitiveTester(mod, hh, exp),
524 def kcdsaprime(pbits, qbits, rng = rand,
525 event = pgen_nullev, name = 'p', nsteps = 0):
526 hbits = pbits - qbits
527 h = pgen(rng.mp(hbits, 1), name + ' [h]',
528 PrimeGenStepper(2), PrimeGenTester(),
529 event, nsteps, RabinMiller.iters(hbits))
530 q = pgen(rng.mp(qbits, 1), name, SimulStepper(2 * h, 1, 2),
531 SimulTester(2 * h, 1), event, nsteps, RabinMiller.iters(qbits))
535 #----- That's all, folks ----------------------------------------------------