From dfeb96842aa50f831ae296a3b403a1cc1729b8f4 Mon Sep 17 00:00:00 2001 From: Vincent Bernardoff Date: Tue, 6 Feb 2018 19:16:26 +0100 Subject: [PATCH] Crypto: add `Secretbox` --- src/lib_crypto/crypto_box.ml | 28 ++++++++++++++++++++++++++++ src/lib_crypto/crypto_box.mli | 17 +++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/src/lib_crypto/crypto_box.ml b/src/lib_crypto/crypto_box.ml index b2f303b65..0e2861823 100644 --- a/src/lib_crypto/crypto_box.ml +++ b/src/lib_crypto/crypto_box.ml @@ -17,6 +17,32 @@ type channel_key = Box.combined Box.key type nonce = Nonce.t type target = Z.t +module Secretbox = struct + include Secretbox + + let of_bytes bytes = + of_cstruct (Cstruct.of_bigarray bytes) + + let of_bytes_exn bytes = + of_cstruct_exn (Cstruct.of_bigarray bytes) + + let box key msg nonce = + let msg = Cstruct.of_bigarray msg in + Cstruct.to_bigarray (box ~key ~msg ~nonce) + + let box_open key cmsg nonce = + let cmsg = Cstruct.of_bigarray cmsg in + Option.map ~f:Cstruct.to_bigarray (box_open ~key ~cmsg ~nonce) + + let box_noalloc key nonce msg = + let msg = Cstruct.of_bigarray msg in + box_noalloc ~key ~nonce ~msg + + let box_open_noalloc key nonce cmsg = + let cmsg = Cstruct.of_bigarray cmsg in + box_open_noalloc ~key ~nonce ~cmsg +end + module Public_key_hash = Blake2B.Make (Base58) (struct let name = "Crypto_box.Public_key_hash" let title = "A Cryptobox public key ID" @@ -36,6 +62,8 @@ let boxzerobytes = Box.boxzerobytes let random_keypair () = let pk, sk = Box.keypair () in sk, pk, hash pk + +let zero_nonce = Tweetnacl.Nonce.(of_cstruct_exn (Cstruct.create bytes)) let random_nonce = Nonce.gen let increment_nonce = Nonce.increment diff --git a/src/lib_crypto/crypto_box.mli b/src/lib_crypto/crypto_box.mli index 78e8c0f43..c3f0f1542 100644 --- a/src/lib_crypto/crypto_box.mli +++ b/src/lib_crypto/crypto_box.mli @@ -11,9 +11,26 @@ type nonce +val zero_nonce : nonce val random_nonce : unit -> nonce val increment_nonce : ?step:int -> nonce -> nonce +module Secretbox : sig + type key + + val zerobytes : int + val boxzerobytes : int + + val of_bytes : MBytes.t -> key option + val of_bytes_exn : MBytes.t -> key + + val box : key -> MBytes.t -> nonce -> MBytes.t + val box_open : key -> MBytes.t -> nonce -> MBytes.t option + + val box_noalloc : key -> nonce -> MBytes.t -> unit + val box_open_noalloc : key -> nonce -> MBytes.t -> bool +end + type target val default_target : target val make_target : float -> target