chiark / gitweb /
catacomb/__init__.py: Fix up cipher etc. names better.
[catacomb-python] / catacomb / __init__.py
index 0b7f418c94eda3e1c83614b50d907c9373da1025..f79b4d29b210c56129138a0c08607dff637d5bca 100644 (file)
@@ -1,34 +1,55 @@
-# -*-python-*-
-#
-# $Id$
-#
-# Setup for Catacomb/Python bindings
-#
-# (c) 2004 Straylight/Edgeware
-#
-
-#----- Licensing notice -----------------------------------------------------
-#
-# This file is part of the Python interface to Catacomb.
-#
-# Catacomb/Python is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 of the License, or
-# (at your option) any later version.
-# 
-# Catacomb/Python is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-# 
-# You should have received a copy of the GNU General Public License
-# along with Catacomb/Python; if not, write to the Free Software Foundation,
-# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+### -*-python-*-
+###
+### Setup for Catacomb/Python bindings
+###
+### (c) 2004 Straylight/Edgeware
+###
+
+###----- Licensing notice ---------------------------------------------------
+###
+### This file is part of the Python interface to Catacomb.
+###
+### Catacomb/Python is free software; you can redistribute it and/or modify
+### it under the terms of the GNU General Public License as published by
+### the Free Software Foundation; either version 2 of the License, or
+### (at your option) any later version.
+###
+### Catacomb/Python is distributed in the hope that it will be useful,
+### but WITHOUT ANY WARRANTY; without even the implied warranty of
+### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+### GNU General Public License for more details.
+###
+### You should have received a copy of the GNU General Public License
+### along with Catacomb/Python; if not, write to the Free Software Foundation,
+### Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 
 import _base
 import types as _types
 from binascii import hexlify as _hexify, unhexlify as _unhexify
+from sys import argv as _argv
 
+###--------------------------------------------------------------------------
+### Basic stuff.
+
+## For the benefit of the default keyreporter, we need the program na,e.
+_base._ego(_argv[0])
+
+## How to fix a name back into the right identifier.  Alas, the rules are not
+## consistent.
+def _fixname(name):
+
+  ## Hyphens consistently become underscores.
+  name = name.replace('-', '_')
+
+  ## But slashes might become underscores or just vanish.
+  if name.startswith('salsa20'): name = name.translate(None, '/')
+  else: name = name.replace('/', '_')
+
+  ## Done.
+  return name
+
+## Initialize the module.  Drag in the static methods of the various
+## classes; create names for the various known crypto algorithms.
 def _init():
   d = globals()
   b = _base.__dict__;
@@ -37,20 +58,26 @@ def _init():
       d[i] = b[i];
   for i in ['MP', 'GF', 'Field',
             'ECPt', 'ECPtCurve', 'ECCurve', 'ECInfo',
-            'DHInfo', 'BinDHInfo', 'RSAPriv', 'PrimeFilter', 'RabinMiller',
-            'Group', 'GE']:
+            'DHInfo', 'BinDHInfo', 'RSAPriv', 'BBSPriv',
+            'PrimeFilter', 'RabinMiller',
+            'Group', 'GE',
+            'KeySZ', 'KeyData']:
     c = d[i]
     pre = '_' + i + '_'
     plen = len(pre)
     for j in b:
       if j[:plen] == pre:
         setattr(c, j[plen:], classmethod(b[j]))
-  for i in [gcciphers, gchashes, gcmacs]:
-    for j in i:
-      c = i[j]
-      d[c.name.replace('-', '_')] = c
+  for i in [gcciphers, gchashes, gcmacs, gcprps]:
+    for c in i.itervalues():
+      d[_fixname(c.name)] = c
+  for c in gccrands.itervalues():
+    d[_fixname(c.name + 'rand')] = c
 _init()
 
+## A handy function for our work: add the methods of a named class to an
+## existing class.  This is how we write the Python-implemented parts of our
+## mostly-C types.
 def _augment(c, cc):
   for i in cc.__dict__:
     a = cc.__dict__[i]
@@ -60,6 +87,18 @@ def _augment(c, cc):
       continue
     setattr(c, i, a)
 
+## Parsing functions tend to return the object parsed and the remainder of
+## the input.  This checks that the remainder is input and, if so, returns
+## just the object.
+def _checkend(r):
+  x, rest = r
+  if rest != '':
+    raise SyntaxError, 'junk at end of string'
+  return x
+
+###--------------------------------------------------------------------------
+### Bytestrings.
+
 class _tmp:
   def fromhex(x):
     return ByteString(_unhexify(x))
@@ -71,6 +110,62 @@ class _tmp:
 _augment(ByteString, _tmp)
 bytes = ByteString.fromhex
 
+###--------------------------------------------------------------------------
+### Multiprecision integers and binary polynomials.
+
+def _split_rat(x):
+  if isinstance(x, BaseRat): return x._n, x._d
+  else: return x, 1
+class BaseRat (object):
+  """Base class implementing fields of fractions over Euclidean domains."""
+  def __new__(cls, a, b):
+    a, b = cls.RING(a), cls.RING(b)
+    q, r = divmod(a, b)
+    if r == 0: return q
+    g = b.gcd(r)
+    me = super(BaseRat, cls).__new__(cls)
+    me._n = a//g
+    me._d = b//g
+    return me
+  @property
+  def numer(me): return me._n
+  @property
+  def denom(me): return me._d
+  def __str__(me): return '%s/%s' % (me._n, me._d)
+  def __repr__(me): return '%s(%s, %s)' % (type(me).__name__, me._n, me._d)
+
+  def __add__(me, you):
+    n, d = _split_rat(you)
+    return type(me)(me._n*d + n*me._d, d*me._d)
+  __radd__ = __add__
+  def __sub__(me, you):
+    n, d = _split_rat(you)
+    return type(me)(me._n*d - n*me._d, d*me._d)
+  def __rsub__(me, you):
+    n, d = _split_rat(you)
+    return type(me)(n*me._d - me._n*d, d*me._d)
+  def __mul__(me, you):
+    n, d = _split_rat(you)
+    return type(me)(me._n*n, me._d*d)
+  def __div__(me, you):
+    n, d = _split_rat(you)
+    return type(me)(me._n*d, me._d*n)
+  def __rdiv__(me, you):
+    n, d = _split_rat(you)
+    return type(me)(me._d*n, me._n*d)
+  def __cmp__(me, you):
+    n, d = _split_rat(you)
+    return type(me)(me._n*d, n*me._d)
+  def __rcmp__(me, you):
+    n, d = _split_rat(you)
+    return cmp(n*me._d, me._n*d)
+
+class IntRat (BaseRat):
+  RING = MP
+
+class GFRat (BaseRat):
+  RING = GF
+
 class _tmp:
   def negp(x): return x < 0
   def posp(x): return x > 0
@@ -80,23 +175,31 @@ class _tmp:
   def mont(x): return MPMont(x)
   def barrett(x): return MPBarrett(x)
   def reduce(x): return MPReduce(x)
-  def factorial(x):
-    'factorial(X) -> X!'
-    if x < 0: raise ValueError, 'factorial argument must be > 0'
-    return MP.product(xrange(1, x + 1))
-  factorial = staticmethod(factorial)
+  def __div__(me, you): return IntRat(me, you)
+  def __rdiv__(me, you): return IntRat(you, me)
 _augment(MP, _tmp)
 
-def _checkend(r):
-  x, rest = r
-  if rest != '':
-    raise SyntaxError, 'junk at end of string'
-  return x
-
 class _tmp:
-  def reduce(x): return GReduce(x)
+  def zerop(x): return x == 0
+  def reduce(x): return GFReduce(x)
+  def trace(x, y): return x.reduce().trace(y)
+  def halftrace(x, y): return x.reduce().halftrace(y)
+  def modsqrt(x, y): return x.reduce().sqrt(y)
+  def quadsolve(x, y): return x.reduce().quadsolve(y)
+  def __div__(me, you): return GFRat(me, you)
+  def __rdiv__(me, you): return GFRat(you, me)
 _augment(GF, _tmp)
 
+class _tmp:
+  def product(*arg):
+    'product(ITERABLE) or product(I, ...) -> PRODUCT'
+    return MPMul(*arg).done()
+  product = staticmethod(product)
+_augment(MPMul, _tmp)
+
+###--------------------------------------------------------------------------
+### Abstract fields.
+
 class _tmp:
   def fromstring(str): return _checkend(Field.parse(str))
   fromstring = staticmethod(fromstring)
@@ -104,6 +207,7 @@ _augment(Field, _tmp)
 
 class _tmp:
   def __repr__(me): return '%s(%sL)' % (type(me).__name__, me.p)
+  def __hash__(me): return 0x114401de ^ hash(me.p)
   def ec(me, a, b): return ECPrimeProjCurve(me, a, b)
 _augment(PrimeField, _tmp)
 
@@ -112,36 +216,25 @@ class _tmp:
   def ec(me, a, b): return ECBinProjCurve(me, a, b)
 _augment(BinField, _tmp)
 
+class _tmp:
+  def __hash__(me): return 0x23e4701c ^ hash(me.p)
+_augment(BinPolyField, _tmp)
+
+class _tmp:
+  def __hash__(me):
+    h = 0x9a7d6240
+    h ^=   hash(me.p)
+    h ^= 2*hash(me.beta) & 0xffffffff
+    return h
+_augment(BinNormField, _tmp)
+
 class _tmp:
   def __str__(me): return str(me.value)
   def __repr__(me): return '%s(%s)' % (repr(me.field), repr(me.value))
 _augment(FE, _tmp)
 
-class _groupmap (object):
-  def __init__(me, map, nth):
-    me.map = map
-    me.nth = nth
-    me.i = [None] * (max(map.values()) + 1)
-  def __repr__(me):
-    return '{%s}' % ', '.join(['%r: %r' % (k, me[k]) for k in me])
-  def __contains__(me, k):
-    return k in me.map
-  def __getitem__(me, k):
-    i = me.map[k]
-    if me.i[i] is None:
-      me.i[i] = me.nth(i)
-    return me.i[i]
-  def __setitem__(me, k, v):
-    raise TypeError, "immutable object"
-  def __iter__(me):
-    return iter(me.map)
-  def keys(me):
-    return [k for k in me]
-  def values(me):
-    return [me[k] for k in me]
-eccurves = _groupmap(_base._eccurves, ECInfo._curven)
-primegroups = _groupmap(_base._pgroups, DHInfo._groupn)
-bingroups = _groupmap(_base._bingroups, BinDHInfo._groupn)
+###--------------------------------------------------------------------------
+### Elliptic curves.
 
 class _tmp:
   def __repr__(me):
@@ -151,9 +244,27 @@ class _tmp:
   def fromraw(me, s):
     return ecpt.fromraw(me, s)
   def pt(me, *args):
-    return ECPt(me, *args)
+    return me(*args)
 _augment(ECCurve, _tmp)
 
+class _tmp:
+  def __hash__(me):
+    h = 0x6751d341
+    h ^=   hash(me.field)
+    h ^= 2*hash(me.a) ^ 0xffffffff
+    h ^= 5*hash(me.b) ^ 0xffffffff
+    return h
+_augment(ECPrimeCurve, _tmp)
+
+class _tmp:
+  def __hash__(me):
+    h = 0x2ac203c5
+    h ^=   hash(me.field)
+    h ^= 2*hash(me.a) ^ 0xffffffff
+    h ^= 5*hash(me.b) ^ 0xffffffff
+    return h
+_augment(ECBinCurve, _tmp)
+
 class _tmp:
   def __repr__(me):
     if not me: return 'ECPt()'
@@ -167,6 +278,11 @@ class _tmp:
   def __repr__(me):
     return 'ECInfo(curve = %r, G = %r, r = %s, h = %s)' % \
            (me.curve, me.G, me.r, me.h)
+  def __hash__(me):
+    h = 0x9bedb8de
+    h ^=   hash(me.curve)
+    h ^= 2*hash(me.G) & 0xffffffff
+    return h
   def group(me):
     return ECGroup(me)
 _augment(ECInfo, _tmp)
@@ -180,6 +296,9 @@ class _tmp:
     return '(%s, %s)' % (me.x, me.y)
 _augment(ECPtCurve, _tmp)
 
+###--------------------------------------------------------------------------
+### Key sizes.
+
 class _tmp:
   def __repr__(me): return 'KeySZAny(%d)' % me.default
   def check(me, sz): return True
@@ -208,6 +327,9 @@ class _tmp:
     return found
 _augment(KeySZSet, _tmp)
 
+###--------------------------------------------------------------------------
+### Abstract groups.
+
 class _tmp:
   def __repr__(me):
     return '%s(p = %s, r = %s, g = %s)' % \
@@ -227,12 +349,39 @@ class _tmp:
     return '%s(%r)' % (type(me).__name__, me.info)
 _augment(Group, _tmp)
 
+class _tmp:
+  def __hash__(me):
+    info = me.info
+    h = 0xbce3cfe6
+    h ^=   hash(info.p)
+    h ^= 2*hash(info.r) & 0xffffffff
+    h ^= 5*hash(info.g) & 0xffffffff
+    return h
+_augment(PrimeGroup, _tmp)
+
+class _tmp:
+  def __hash__(me):
+    info = me.info
+    h = 0x80695949
+    h ^=   hash(info.p)
+    h ^= 2*hash(info.r) & 0xffffffff
+    h ^= 5*hash(info.g) & 0xffffffff
+    return h
+_augment(BinGroup, _tmp)
+
+class _tmp:
+  def __hash__(me): return 0x0ec23dab ^ hash(me.info)
+_augment(ECGroup, _tmp)
+
 class _tmp:
   def __repr__(me):
     return '%r(%r)' % (me.group, str(me))
 _augment(GE, _tmp)
 
-class PKCS1Crypt(object):
+###--------------------------------------------------------------------------
+### RSA encoding techniques.
+
+class PKCS1Crypt (object):
   def __init__(me, ep = '', rng = rand):
     me.ep = ep
     me.rng = rng
@@ -241,7 +390,7 @@ class PKCS1Crypt(object):
   def decode(me, ct, nbits):
     return _base._p1crypt_decode(ct, nbits, me.ep, me.rng)
 
-class PKCS1Sig(object):
+class PKCS1Sig (object):
   def __init__(me, ep = '', rng = rand):
     me.ep = ep
     me.rng = rng
@@ -250,7 +399,7 @@ class PKCS1Sig(object):
   def decode(me, msg, sig, nbits):
     return _base._p1sig_decode(msg, sig, nbits, me.ep, me.rng)
 
-class OAEP(object):
+class OAEP (object):
   def __init__(me, mgf = sha_mgf, hash = sha, ep = '', rng = rand):
     me.mgf = mgf
     me.hash = hash
@@ -261,7 +410,7 @@ class OAEP(object):
   def decode(me, ct, nbits):
     return _base._oaep_decode(ct, nbits, me.mgf, me.hash, me.ep, me.rng)
 
-class PSS(object):
+class PSS (object):
   def __init__(me, mgf = sha_mgf, hash = sha, saltsz = None, rng = rand):
     me.mgf = mgf
     me.hash = hash
@@ -284,7 +433,7 @@ class _tmp:
       x = enc.decode(msg, me.pubop(sig), me.n.nbits)
       return x is None or x == msg
     except ValueError:
-      return False      
+      return False
 _augment(RSAPub, _tmp)
 
 class _tmp:
@@ -292,6 +441,59 @@ class _tmp:
   def sign(me, msg, enc): return me.privop(enc.encode(msg, me.n.nbits))
 _augment(RSAPriv, _tmp)
 
+###--------------------------------------------------------------------------
+### Built-in named curves and prime groups.
+
+class _groupmap (object):
+  def __init__(me, map, nth):
+    me.map = map
+    me.nth = nth
+    me.i = [None] * (max(map.values()) + 1)
+  def __repr__(me):
+    return '{%s}' % ', '.join(['%r: %r' % (k, me[k]) for k in me])
+  def __contains__(me, k):
+    return k in me.map
+  def __getitem__(me, k):
+    i = me.map[k]
+    if me.i[i] is None:
+      me.i[i] = me.nth(i)
+    return me.i[i]
+  def __setitem__(me, k, v):
+    raise TypeError, "immutable object"
+  def __iter__(me):
+    return iter(me.map)
+  def iterkeys(me):
+    return iter(me.map)
+  def itervalues(me):
+    for k in me:
+      yield me[k]
+  def iteritems(me):
+    for k in me:
+      yield k, me[k]
+  def keys(me):
+    return [k for k in me]
+  def values(me):
+    return [me[k] for k in me]
+  def items(me):
+    return [(k, me[k]) for k in me]
+eccurves = _groupmap(_base._eccurves, ECInfo._curven)
+primegroups = _groupmap(_base._pgroups, DHInfo._groupn)
+bingroups = _groupmap(_base._bingroups, BinDHInfo._groupn)
+
+###--------------------------------------------------------------------------
+### Prime number generation.
+
+class PrimeGenEventHandler (object):
+  def pg_begin(me, ev):
+    return me.pg_try(ev)
+  def pg_done(me, ev):
+    return PGEN_DONE
+  def pg_abort(me, ev):
+    return PGEN_TRY
+  def pg_fail(me, ev):
+    return PGEN_TRY
+  def pg_pass(me, ev):
+    return PGEN_TRY
 
 class SophieGermainStepJump (object):
   def pg_begin(me, ev):
@@ -354,18 +556,6 @@ class SophieGermainTester (object):
     del me.lr
     del me.hr
 
-class PrimeGenEventHandler (object):
-  def pg_begin(me, ev):
-    return me.pg_try(ev)
-  def pg_done(me, ev):
-    return PGEN_DONE
-  def pg_abort(me, ev):
-    return PGEN_TRY
-  def pg_fail(me, ev):
-    return PGEN_TRY
-  def pg_pass(me, ev):
-    return PGEN_TRY
-
 class PrimitiveStepper (PrimeGenEventHandler):
   def __init__(me):
     pass
@@ -473,6 +663,4 @@ def kcdsaprime(pbits, qbits, rng = rand,
   p = 2 * q * h + 1
   return p, q, h
 
-import pwsafe
-
 #----- That's all, folks ----------------------------------------------------