chiark / gitweb /
pubkey.c, ...: Support Bernstein's `X25519' key-agreement algorithm.
[catacomb-python] / catacomb / __init__.py
index aaec637f8692fb43f5f1e58edaa0c82b864fb6da..115e8fe785cec67af3ce5d46b0480ad4866cea08 100644 (file)
@@ -1,38 +1,35 @@
-# -*-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.
-
-#----- Imports --------------------------------------------------------------
+### -*-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 ----------------------------------------------------------
+###--------------------------------------------------------------------------
+### Basic stuff.
 
 ## For the benefit of the default keyreporter, we need the program na,e.
 _base._ego(_argv[0])
@@ -46,22 +43,22 @@ def _init():
     if i[0] != '_':
       d[i] = b[i];
   for i in ['MP', 'GF', 'Field',
-           'ECPt', 'ECPtCurve', 'ECCurve', 'ECInfo',
-           'DHInfo', 'BinDHInfo', 'RSAPriv', 'BBSPriv',
-           'PrimeFilter', 'RabinMiller',
-           'Group', 'GE',
-           'KeyData']:
+            'ECPt', 'ECPtCurve', 'ECCurve', 'ECInfo',
+            '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]))
+        setattr(c, j[plen:], classmethod(b[j]))
   for i in [gcciphers, gchashes, gcmacs, gcprps]:
     for c in i.itervalues():
-      d[c.name.replace('-', '_')] = c
+      d[c.name.replace('-', '_').translate(None, '/')] = c
   for c in gccrands.itervalues():
-    d[c.name.replace('-', '_') + 'rand'] = c
+    d[c.name.replace('-', '_').translate(None, '/') + 'rand'] = c
 _init()
 
 ## A handy function for our work: add the methods of a named class to an
@@ -85,7 +82,8 @@ def _checkend(r):
     raise SyntaxError, 'junk at end of string'
   return x
 
-#----- Bytestrings ----------------------------------------------------------
+###--------------------------------------------------------------------------
+### Bytestrings.
 
 class _tmp:
   def fromhex(x):
@@ -96,9 +94,94 @@ class _tmp:
   def __repr__(me):
     return 'bytes(%r)' % hex(me)
 _augment(ByteString, _tmp)
+ByteString.__hash__ = str.__hash__
 bytes = ByteString.fromhex
 
-#----- Multiprecision integers and binary polynomials -----------------------
+###--------------------------------------------------------------------------
+### Hashing.
+
+class _tmp:
+  def check(me, h):
+    hh = me.done()
+    return ctstreq(h, hh)
+_augment(GHash, _tmp)
+_augment(Poly1305Hash, _tmp)
+
+###--------------------------------------------------------------------------
+### NaCl `secretbox'.
+
+def secret_box(k, n, m):
+  E = xsalsa20(k).setiv(n)
+  r = E.enczero(poly1305.keysz.default)
+  s = E.enczero(poly1305.masksz)
+  y = E.encrypt(m)
+  t = poly1305(r)(s).hash(y).done()
+  return ByteString(t + y)
+
+def secret_unbox(k, n, c):
+  E = xsalsa20(k).setiv(n)
+  r = E.enczero(poly1305.keysz.default)
+  s = E.enczero(poly1305.masksz)
+  y = c[poly1305.tagsz:]
+  if not poly1305(r)(s).hash(y).check(c[0:poly1305.tagsz]):
+    raise ValueError, 'decryption failed'
+  return E.decrypt(c[poly1305.tagsz:])
+
+###--------------------------------------------------------------------------
+### 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
@@ -109,11 +192,8 @@ 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 MPMul.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)
 
 class _tmp:
@@ -123,6 +203,8 @@ class _tmp:
   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:
@@ -132,7 +214,8 @@ class _tmp:
   product = staticmethod(product)
 _augment(MPMul, _tmp)
 
-#----- Abstract fields ------------------------------------------------------
+###--------------------------------------------------------------------------
+### Abstract fields.
 
 class _tmp:
   def fromstring(str): return _checkend(Field.parse(str))
@@ -141,6 +224,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)
 
@@ -149,12 +233,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)
 
-#----- Elliptic curves ------------------------------------------------------
+###--------------------------------------------------------------------------
+### Elliptic curves.
 
 class _tmp:
   def __repr__(me):
@@ -167,6 +264,24 @@ class _tmp:
     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()'
@@ -179,7 +294,12 @@ _augment(ECPt, _tmp)
 class _tmp:
   def __repr__(me):
     return 'ECInfo(curve = %r, G = %r, r = %s, h = %s)' % \
-          (me.curve, me.G, me.r, me.h)
+           (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)
@@ -193,7 +313,8 @@ class _tmp:
     return '(%s, %s)' % (me.x, me.y)
 _augment(ECPtCurve, _tmp)
 
-#----- Key sizes ------------------------------------------------------------
+###--------------------------------------------------------------------------
+### Key sizes.
 
 class _tmp:
   def __repr__(me): return 'KeySZAny(%d)' % me.default
@@ -204,7 +325,7 @@ _augment(KeySZAny, _tmp)
 class _tmp:
   def __repr__(me):
     return 'KeySZRange(%d, %d, %d, %d)' % \
-          (me.default, me.min, me.max, me.mod)
+           (me.default, me.min, me.max, me.mod)
   def check(me, sz): return me.min <= sz <= me.max and sz % me.mod == 0
   def best(me, sz):
     if sz < me.min: raise ValueError, 'key too small'
@@ -223,12 +344,13 @@ class _tmp:
     return found
 _augment(KeySZSet, _tmp)
 
-#----- Abstract groups ------------------------------------------------------
+###--------------------------------------------------------------------------
+### Abstract groups.
 
 class _tmp:
   def __repr__(me):
     return '%s(p = %s, r = %s, g = %s)' % \
-          (type(me).__name__, me.p, me.r, me.g)
+           (type(me).__name__, me.p, me.r, me.g)
 _augment(FGInfo, _tmp)
 
 class _tmp:
@@ -244,12 +366,37 @@ 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)
 
-#----- RSA encoding techniques ----------------------------------------------
+###--------------------------------------------------------------------------
+### RSA encoding techniques.
 
 class PKCS1Crypt (object):
   def __init__(me, ep = '', rng = rand):
@@ -292,7 +439,7 @@ class PSS (object):
     return _base._pss_encode(msg, nbits, me.mgf, me.hash, me.saltsz, me.rng)
   def decode(me, msg, sig, nbits):
     return _base._pss_decode(msg, sig, nbits,
-                            me.mgf, me.hash, me.saltsz, me.rng)
+                             me.mgf, me.hash, me.saltsz, me.rng)
 
 class _tmp:
   def encrypt(me, msg, enc):
@@ -311,7 +458,45 @@ 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 -------------------------------
+###--------------------------------------------------------------------------
+### Bernstein's elliptic curve crypto.
+
+X25519_BASE = \
+  bytes('0900000000000000000000000000000000000000000000000000000000000000')
+
+Z128 = bytes('00000000000000000000000000000000')
+
+class _BoxyPub (object):
+  def __init__(me, pub, *kw, **kwargs):
+    if len(pub) != me._PUBSZ: raise ValueError, 'bad public key'
+    super(_BoxyPub, me).__init__(*kw, **kwargs)
+    me.pub = pub
+
+class _BoxyPriv (_BoxyPub):
+  def __init__(me, priv, pub = None, *kw, **kwargs):
+    if len(priv) != me._KEYSZ: raise ValueError, 'bad private key'
+    if pub is None: pub = me._op(priv, me._BASE)
+    super(_BoxyPriv, me).__init__(pub = pub, *kw, **kwargs)
+    me.priv = priv
+  def agree(me, you): return me._op(me.priv, you.pub)
+  def boxkey(me, recip):
+    return me._hashkey(me.agree(recip))
+  def box(me, recip, n, m):
+    return secret_box(me.boxkey(recip), n, m)
+  def unbox(me, recip, n, c):
+    return secret_unbox(me.boxkey(recip, n, c))
+
+class X25519Pub (_BoxyPub):
+  _PUBSZ = X25519_PUBSZ
+  _BASE = X25519_BASE
+
+class X25519Priv (_BoxyPriv, X25519Pub):
+  _KEYSZ = X25519_KEYSZ
+  def _op(me, k, X): return x25519(k, X)
+  def _hashkey(me, z): return hsalsa20_prf(z, Z128)
+
+###--------------------------------------------------------------------------
+### Built-in named curves and prime groups.
 
 class _groupmap (object):
   def __init__(me, map, nth):
@@ -349,7 +534,8 @@ eccurves = _groupmap(_base._eccurves, ECInfo._curven)
 primegroups = _groupmap(_base._pgroups, DHInfo._groupn)
 bingroups = _groupmap(_base._bingroups, BinDHInfo._groupn)
 
-#----- Prime number generation ----------------------------------------------
+###--------------------------------------------------------------------------
+### Prime number generation.
 
 class PrimeGenEventHandler (object):
   def pg_begin(me, ev):
@@ -514,20 +700,20 @@ class SimulTester (PrimeGenEventHandler):
 def sgprime(start, step = 2, name = 'p', event = pgen_nullev, nsteps = 0):
   start = MP(start)
   return pgen(start, name, SimulStepper(step = step), SimulTester(), event,
-             nsteps, RabinMiller.iters(start.nbits))
+              nsteps, RabinMiller.iters(start.nbits))
 
 def findprimitive(mod, hh = [], exp = None, name = 'g', event = pgen_nullev):
   return pgen(0, name, PrimitiveStepper(), PrimitiveTester(mod, hh, exp),
-             event, 0, 1)
+              event, 0, 1)
 
 def kcdsaprime(pbits, qbits, rng = rand,
-              event = pgen_nullev, name = 'p', nsteps = 0):
+               event = pgen_nullev, name = 'p', nsteps = 0):
   hbits = pbits - qbits
   h = pgen(rng.mp(hbits, 1), name + ' [h]',
-          PrimeGenStepper(2), PrimeGenTester(),
-          event, nsteps, RabinMiller.iters(hbits))
+           PrimeGenStepper(2), PrimeGenTester(),
+           event, nsteps, RabinMiller.iters(hbits))
   q = pgen(rng.mp(qbits, 1), name, SimulStepper(2 * h, 1, 2),
-          SimulTester(2 * h, 1), event, nsteps, RabinMiller.iters(qbits))
+           SimulTester(2 * h, 1), event, nsteps, RabinMiller.iters(qbits))
   p = 2 * q * h + 1
   return p, q, h