Files
rose-ash/lib/ocaml/baseline/xor_cipher.ml
giles 60e3ce1c96
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 22s
ocaml: phase 5.1 xor_cipher.ml baseline (XOR roll-key encryption, round-trip = 601)
For each character, XOR with the corresponding key char (key cycled
via 'i mod kn'):

  let xor_cipher key text =
    let buf = Buffer.create n in
    for i = 0 to n - 1 do
      let c = Char.code text.[i] in
      let k = Char.code key.[i mod kn] in
      Buffer.add_string buf (String.make 1 (Char.chr (c lxor k)))
    done;
    Buffer.contents buf

XOR is its own inverse, so encrypt + decrypt with the same key yields
the original. Test combines:
  - String.length decoded            = 6
  - decoded = 'Hello!'                  -> 1
  - 6 * 100 + 1                          = 601

Tests Char.code + Char.chr round-trip, the iter-127 lxor operator,
Buffer.add_string + String.make 1, and key-cycling via mod.

90 baseline programs total.
2026-05-09 18:19:02 +00:00

17 lines
471 B
OCaml

let xor_cipher key text =
let n = String.length text in
let kn = String.length key in
let buf = Buffer.create n in
for i = 0 to n - 1 do
let c = Char.code text.[i] in
let k = Char.code key.[i mod kn] in
Buffer.add_string buf (String.make 1 (Char.chr (c lxor k)))
done;
Buffer.contents buf
;;
let encoded = xor_cipher "key" "Hello!" in
let decoded = xor_cipher "key" encoded in
String.length decoded * 100 + (if decoded = "Hello!" then 1 else 0)