How to resolve the algorithm Caesar cipher step by step in the OCaml programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Caesar cipher step by step in the OCaml programming language

Table of Contents

Problem Statement

Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Caesar cipher step by step in the OCaml programming language

Source code in the ocaml programming language

let islower c =
  c >= 'a' && c <= 'z'

let isupper c =
  c >= 'A' && c <= 'Z'

let rot x str =
  let upchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  and lowchars = "abcdefghijklmnopqrstuvwxyz" in
  let rec decal x =
    if x < 0 then decal (x + 26) else x
  in
  let x = (decal x) mod 26 in
  let decal_up = x - (int_of_char 'A')
  and decal_low = x - (int_of_char 'a') in
  String.map (fun c ->
    if islower c then
      let j = ((int_of_char c) + decal_low) mod 26 in
      lowchars.[j]
    else if isupper c then
      let j = ((int_of_char c) + decal_up) mod 26 in
      upchars.[j]
    else
      c
  ) str


let () =
  let key = 3 in
  let orig = "The five boxing wizards jump quickly" in
  let enciphered = rot key orig in
  print_endline enciphered;
  let deciphered = rot (- key) enciphered in
  print_endline deciphered;
  Printf.printf "equal: %b\n" (orig = deciphered)
;;


  

You may also check:How to resolve the algorithm Self-describing numbers step by step in the K programming language
You may also check:How to resolve the algorithm JSON step by step in the Go programming language
You may also check:How to resolve the algorithm Non-decimal radices/Convert step by step in the PL/I programming language
You may also check:How to resolve the algorithm Sort an integer array step by step in the Slate programming language
You may also check:How to resolve the algorithm Safe primes and unsafe primes step by step in the Rust programming language