[Ask] Cookie Crypto

for a CGI I need to encrypt a cookie header payload like

let encrypt sec nonce adata =
  assert (32 = (sec |> Cstruct.length));
  assert (12 = (nonce |> Cstruct.length));
  let key = sec |> Mirage_crypto.Chacha20.of_secret in
  adata
  |> Mirage_crypto.Chacha20.authenticate_encrypt ~key ~nonce
  |> Cstruct.append nonce
  |> Cstruct.to_string
  |> Base64.encode_string

and wonder it it’s sane to add the nonce to the crypted string.

P.S.: while writing this I found https://opam.ocaml.org/packages/http-cookie/ - maybe I should use that?

Judging from the API, it seems that you are expected to provide the nonce during encryption, i.e. the ciphertext produced does not embed the nonce.

So yes seems like one would want to add the nonce in some way to the ciphertext.

AFAIK, nonce does not need to be secretive (so an append suffices indeed) as it’s mainly to introduce non-determinism and used as part of MAC, an attacker cannot do much with it without the secret key.

mind the return value has the nonce prepended.

So you mean Mirage_crypto.Chacha20.authenticate_encrypt already does that?

no, the |> Cstruct.append nonce

I was saying what you were doing was fine and probably what you’d want to end up doing anyway : v

1 Like