def __repr__(me):
return 'bytes(%r)' % hex(me)
_augment(ByteString, _tmp)
+ByteString.__hash__ = str.__hash__
bytes = ByteString.fromhex
+###--------------------------------------------------------------------------
+### 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 sign(me, msg, enc): return me.privop(enc.encode(msg, me.n.nbits))
_augment(RSAPriv, _tmp)
+###--------------------------------------------------------------------------
+### 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.