algorithms.c, etc.: Support the new AEAD abstraction.
[catacomb-python] / catacomb / __init__.py
index bb7703e..8038815 100644 (file)
@@ -102,7 +102,7 @@ def _init():
     for j in b:
       if j[:plen] == pre:
         setattr(c, j[plen:], classmethod(b[j]))
-  for i in [gcciphers, gchashes, gcmacs, gcprps]:
+  for i in [gcciphers, gcaeads, gchashes, gcmacs, gcprps]:
     for c in i.itervalues():
       d[_fixname(c.name)] = c
   for c in gccrands.itervalues():
@@ -184,6 +184,27 @@ ByteString.__hash__ = str.__hash__
 bytes = ByteString.fromhex
 
 ###--------------------------------------------------------------------------
+### Symmetric encryption.
+
+class _tmp:
+  def encrypt(me, n, m, tsz = None, h = ByteString('')):
+    if tsz is None: tsz = me.__class__.tagsz.default
+    e = me.enc(n, len(h), len(m), tsz)
+    if not len(h): a = None
+    else: a = e.aad().hash(h)
+    c0 = e.encrypt(m)
+    c1, t = e.done(aad = a)
+    return c0 + c1, t
+  def decrypt(me, n, c, t, h = ByteString('')):
+    d = me.dec(n, len(h), len(c), len(t))
+    if not len(h): a = None
+    else: a = d.aad().hash(h)
+    m = d.decrypt(c)
+    m += d.done(t, aad = a)
+    return m
+_augment(GAEKey, _tmp)
+
+###--------------------------------------------------------------------------
 ### Hashing.
 
 class _tmp:
@@ -287,21 +308,12 @@ class KMAC256 (KMAC): _SHAKE = Shake256; _TAGSZ = 32
 ### 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()
+  y, t = salsa20_naclbox(k).encrypt(n, m)
   return 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:])
+  tsz = poly1305.tagsz
+  return salsa20_naclbox(k).decrypt(n, c[tsz:], c[0:tsz])
 
 ###--------------------------------------------------------------------------
 ### Multiprecision integers and binary polynomials.