In our implementation, we will be using the second scheme - starting with a random master key, and then for each block deriving a block level key (`blockKEY`) and block level initialization vector (`blockIV`).
For some introduction and examples on BearSSL, please consult:
- [[How to generate a random number using BearSSL]]
- [[How to create a hash using BearSSL]]
- [[How to encrypt and decrypt content using symmetric encryption in BearSSL]]
Before document design considerations for the content encryption in the Codex client, let's first see how to use BearSSL primitives to encrypt and decrypt some content:
```nim
import std/sequtils
import bearssl/blockx
import stew/byteutils
import ./rng
var plaintext = "0123456789abcdef".toBytes
echo "plaintext: ", plaintext.toHex
let key = newSeqWith(16, Rng.instance.rand(uint8.high).byte)
let ive = newSeqWith(16, Rng.instance.rand(uint8.high).byte)
Important to notice here is that `aesBigCbcencRun` will mutate the provided initialization vector `IV` so that it is ready to use for the subsequent chunk of data - a classical CBC mode for AES. Yet, for Codex, we use slightly modified scheme as already shown above.
For codex:
1. we first generate a `MASTER_KEY` - which will be returned to the user
2. from the `MASTER_KEY`, for each block, we derive the corresponding block level encryption key `blockKEY` and block level initialization vector `blockIV` as shown in the proposal above
3. using the derived `blockKEY` and `blockIV`, we then encrypt the block using the BearSSL encryption primitives as demonstrated above.
As we see above, the block index is used in the process of the key and initialization vector derivation. For this reason we also need to remember to convert the block index to a byte representation - we use big-endian ordering. For this conversion a very simple function can be used:
- [bearssl Nim bindings](https://github.com/status-im/nim-bearssl)
- A nice example of using BearSSL encryption API (Arduino) https://github.com/kakopappa/esp8266-aes-cbc-encryption-decryption/blob/main/esp8266-aes-cbc-encryption-decryption.ino