Cryptokit usage

I am trying to use the crytokit library to encrypt the message .

let msg = “Hello World”
let key = “xyz”
let iv = “123abc”

let aes = new Cryptokit.Block.aes_encrypt key
let aes_cbc = new Cryptokit.Block.cbc_encrypt ~iv aes

let cip =
let size =
int_of_float (ceil (float String.(length msg) /. 16. ) *. 16. ) in
Bytes.create size

let messagewe = Cstruct.of_string msg
let message = Cstruct.to_bytes messagewe

let () = aes_cbc#transform message 0 cip 0

But I am getting the below error

Entering directory ‘/home/work/ocaml’
Entering directory ‘/home/work/ocaml’
Fatal error: exception Cryptokit.Error(0)

You should catch exception Cryptokit.Error to print it. I don’t think there is a function to convert those errors to a string though so you’ll have to write it yourself. But it will give you a better error message, and thus will allow you to understand what you did wrong.

If we look at the definition of the Cryptokit.error type ( we see that error 0 is probably “wrong key size”. You key has length 3, which is not a valid length for an AES key. You will probably also get the “wrong IV size” too.

As @rbardou wrote, the key, the IV, and the message have incorrect lengths. If you look up the documentation of aes_encrypt in cryptokit.mli, you’ll see that they key must have length 16, 24, or 32, corresponding to AES-128, AES-192, and AES-256.

Likewise, cbc_encrypt requires the length of the IV to agree with the cipher’s block size, which is 16 (128 bits) for AES.

Finally, block ciphers process messages by blocks (duh), and AES has block size 16, while your message "Hello world" has length 11. This won’t work. You may need padding.

Here is a variant of your example that works:

let cleartext = "Hello World"
let key = "wxyzwxyzwxyzwxyz"
let iv =  "0123456789012345"

let aes = 
  Cryptokit.Cipher.(aes ~mode:CBC ~pad:Cryptokit.Padding.length ~iv:iv
                    key Encrypt)

let ciphertext = Cryptokit.transform_string aes cleartext
1 Like