Skip to content

Commit

Permalink
Cookbook recipes for the Cryptography section
Browse files Browse the repository at this point in the history
Using the Cryptokit library.
  • Loading branch information
xavierleroy committed Oct 26, 2024
1 parent 719c3a3 commit 821a11b
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
31 changes: 31 additions & 0 deletions data/cookbook/calculate-sha-256-digest-of-file/00-cryptokit.ml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
---
packages:
- name: cryptokit
tested_version: "1.18"
used_libraries:
- cryptokit
---
(* `sha256sum` computes the SHA-256 digest of the given file,
and prints it in hexadecimal. *)
let sha256sum filename =
(* We select SHA-256 as the hash function *)
let hash = Cryptokit.Hash.sha256() in
(* We open the given file in binary mode (no end-of-line translation) *)
let digest =
In_channel.with_open_bin filename
(fun ic ->
(* We run the contents of the file through the hash function *)
Cryptokit.hash_channel hash ic) in
(* We convert the hash (32 bytes) to hexadecimal (64 hexadecimal digits) *)
let hex_digest =
Cryptokit.transform_string (Cryptokit.Hexa.encode()) digest in
(* We print the hexadecimal hash and the filename *)
Printf.printf "%s %s\n" hex_digest filename

(* The entry point for this program calls `sha256sum` on each filename
passed as argument on the command line. *)
let _ =
for i = 1 to Array.length Sys.argv - 1 do
sha256sum Sys.argv.(i)
done

29 changes: 29 additions & 0 deletions data/cookbook/sign-and-verify-hmac-digest/00-cryptokit.ml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
---
packages:
- name: cryptokit
tested_version: "1.18"
used_libraries:
- cryptokit
---
(* `hmac` computes the MAC (Message Authentication Code) for the given message
and the given secret key. The MAC function used is HMAC-SHA256. *)
let hmac ~key msg =
(* Use HMAC-SHA256 to create a hash function from the given key *)
let hash = Cryptokit.MAC.hmac_sha256 key in
(* Run the message through this hash function *)
Cryptokit.hash_string hash msg

(* Sign the given message. Return a pair of the message and its MAC. *)
let sign ~key msg =
(msg, hmac ~key msg)

(* Verify the signature on a message. Return `true` if the signature is valid,
`false` otherwise. *)
let verify ~key (msg, mac) =
hmac ~key msg = mac

(* A simple test. *)
let _ =
let key = "supercalifragilisticexpialidocious"
and msg = "Mary Poppins" in
assert (verify ~key (sign ~key msg))

0 comments on commit 821a11b

Please sign in to comment.