this repo has no description
1let nonce_size = 12
2let tag_size = 16
3let version_size = 1
4let encryption_version = 0
5let key_size = 16
6let overhead = version_size + nonce_size + tag_size
7
8type key = Mirage_crypto.AES.GCM.key
9
10let init_key secret =
11 if String.length secret <> key_size then Error `Invalid_key_length
12 else Ok (Mirage_crypto.AES.GCM.of_secret secret)
13
14let generate_nonce (random : _ Eio.Flow.source) =
15 let buf = Cstruct.create nonce_size in
16 Eio.Flow.read_exact random buf;
17 Cstruct.to_string buf
18
19let encrypt ~key ~random plaintext =
20 let nonce = generate_nonce random in
21 let ciphertext =
22 Mirage_crypto.AES.GCM.authenticate_encrypt ~key ~nonce
23 (Cstruct.to_string plaintext)
24 in
25 let result =
26 Cstruct.create (version_size + nonce_size + String.length ciphertext)
27 in
28 Cstruct.set_uint8 result 0 encryption_version;
29 Cstruct.blit_from_string nonce 0 result version_size nonce_size;
30 Cstruct.blit_from_string ciphertext 0 result
31 (version_size + nonce_size)
32 (String.length ciphertext);
33 result
34
35let decrypt ~key data =
36 if Cstruct.length data < overhead then Error `Too_short
37 else
38 let version = Cstruct.get_uint8 data 0 in
39 if version <> encryption_version then Error `Unsupported_version
40 else
41 let nonce =
42 Cstruct.to_string (Cstruct.sub data version_size nonce_size)
43 in
44 let ciphertext =
45 Cstruct.to_string
46 (Cstruct.sub data
47 (version_size + nonce_size)
48 (Cstruct.length data - version_size - nonce_size))
49 in
50 match
51 Mirage_crypto.AES.GCM.authenticate_decrypt ~key ~nonce ciphertext
52 with
53 | Some plaintext -> Ok (Cstruct.of_string plaintext)
54 | None -> Error `Decryption_failed