ocaml http/1, http/2 and websocket client and server library
at v0.3.3 1.7 kB view raw
1let initialized = ref false 2 3let ensure_initialized () = 4 if not !initialized then begin 5 Mirage_crypto_rng_unix.use_default (); 6 initialized := true 7 end 8 9let generate n = 10 ensure_initialized (); 11 Mirage_crypto_rng.generate n 12 13let generate_bytes n = Bytes.of_string (Mirage_crypto_rng.generate n) 14 15let int bound = 16 if bound <= 0 then invalid_arg "Secure_random.int: bound must be positive"; 17 let rec sample () = 18 let s = Mirage_crypto_rng.generate 8 in 19 let v = 20 (Char.code s.[0] lsl 56) 21 lor (Char.code s.[1] lsl 48) 22 lor (Char.code s.[2] lsl 40) 23 lor (Char.code s.[3] lsl 32) 24 lor (Char.code s.[4] lsl 24) 25 lor (Char.code s.[5] lsl 16) 26 lor (Char.code s.[6] lsl 8) 27 lor Char.code s.[7] 28 in 29 let v = v land max_int in 30 let limit = max_int - (max_int mod bound) in 31 if v < limit then v mod bound else sample () 32 in 33 sample () 34 35let token ?(bytes = 32) () = 36 let raw = generate bytes in 37 Base64.encode_string ~pad:false ~alphabet:Base64.uri_safe_alphabet raw 38 39let uuid () = 40 let bytes = generate_bytes 16 in 41 Bytes.set bytes 6 42 (Char.chr (Char.code (Bytes.get bytes 6) land 0x0f lor 0x40)); 43 Bytes.set bytes 8 44 (Char.chr (Char.code (Bytes.get bytes 8) land 0x3f lor 0x80)); 45 let hex = Bytes.create 36 in 46 let hex_chars = "0123456789abcdef" in 47 let pos = ref 0 in 48 for i = 0 to 15 do 49 if i = 4 || i = 6 || i = 8 || i = 10 then begin 50 Bytes.set hex !pos '-'; 51 incr pos 52 end; 53 let b = Char.code (Bytes.get bytes i) in 54 Bytes.set hex !pos hex_chars.[b lsr 4]; 55 incr pos; 56 Bytes.set hex !pos hex_chars.[b land 0x0f]; 57 incr pos 58 done; 59 Bytes.to_string hex