upstream: https://github.com/mirage/mirage-crypto
at main 78 lines 2.1 kB view raw
1module type S = sig 2 type 'a iter = 'a Uncommon.iter 3 type t 4 5 val mac_size : int 6 val empty : key:string -> t 7 val feed : t -> string -> t 8 val feedi : t -> string iter -> t 9 val get : t -> string 10 val mac : key:string -> string -> string 11 val maci : key:string -> string iter -> string 12 13 val mac_into : 14 key:string -> (string * int * int) list -> bytes -> dst_off:int -> unit 15 16 val unsafe_mac_into : 17 key:string -> (string * int * int) list -> bytes -> dst_off:int -> unit 18end 19 20module It : S = struct 21 type 'a iter = 'a Uncommon.iter 22 23 module P = Native.Poly1305 24 25 let mac_size = P.mac_size () 26 27 type t = bytes 28 29 let dup = Bytes.copy 30 31 let empty ~key = 32 let ctx = Bytes.create (P.ctx_size ()) in 33 if String.length key <> 32 then invalid_arg "Poly1305 key must be 32 bytes"; 34 P.init ctx key; 35 ctx 36 37 let update ctx data = P.update ctx data 0 (String.length data) 38 39 let feed ctx cs = 40 let t = dup ctx in 41 update t cs; 42 t 43 44 let feedi ctx iter = 45 let t = dup ctx in 46 iter (update t); 47 t 48 49 let final ctx = 50 let res = Bytes.create mac_size in 51 P.finalize ctx res 0; 52 Bytes.unsafe_to_string res 53 54 let get ctx = final (dup ctx) 55 let mac ~key data = feed (empty ~key) data |> final 56 let maci ~key iter = feedi (empty ~key) iter |> final 57 58 let unsafe_mac_into ~key datas dst ~dst_off = 59 let ctx = empty ~key in 60 List.iter (fun (d, off, len) -> P.update ctx d off len) datas; 61 P.finalize ctx dst dst_off 62 63 let mac_into ~key datas dst ~dst_off = 64 if Bytes.length dst - dst_off < mac_size then 65 Uncommon.invalid_arg "Poly1305: dst length %u - off %u < len %u" 66 (Bytes.length dst) dst_off mac_size; 67 if dst_off < 0 then Uncommon.invalid_arg "Poly1305: dst_off %u < 0" dst_off; 68 let ctx = empty ~key in 69 List.iter 70 (fun (d, off, len) -> 71 if off < 0 then Uncommon.invalid_arg "Poly1305: d off %u < 0" off; 72 if String.length d - off < len then 73 Uncommon.invalid_arg "Poly1305: d length %u - off %u < len %u" 74 (String.length d) off len; 75 P.update ctx d off len) 76 datas; 77 P.finalize ctx dst dst_off 78end