catacomb/__init__.py: Add a simple implementation of NaCl `secretbox'.
[catacomb-python] / catacomb / __init__.py
index 6745bce..9963572 100644 (file)
@@ -108,6 +108,26 @@ _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):