Avatar of emengd

emengd's solution

to Atbash Cipher in the OCaml Track

Published at Feb 21 2019 · 0 comments
Instructions
Test suite
Solution

Note:

This exercise has changed since this solution was written.

Create an implementation of the atbash cipher, an ancient encryption system created in the Middle East.

The Atbash cipher is a simple substitution cipher that relies on transposing all the letters in the alphabet such that the resulting alphabet is backwards. The first letter is replaced with the last letter, the second with the second-last, and so on.

An Atbash cipher for the Latin alphabet would be as follows:

Plain:  abcdefghijklmnopqrstuvwxyz
Cipher: zyxwvutsrqponmlkjihgfedcba

It is a very weak cipher because it only has one possible key, and it is a simple monoalphabetic substitution cipher. However, this may not have been an issue in the cipher's time.

Ciphertext is written out in groups of fixed length, the traditional group size being 5 letters, and punctuation is excluded. This is to make it harder to guess things based on word boundaries.

Examples

  • Encoding test gives gvhg
  • Decoding gvhg gives test
  • Decoding gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt gives thequickbrownfoxjumpsoverthelazydog

Deprecation of String.lowercase

Depending on the version of OCaml you installed the use of String.lowercase is frowned upon. Since version 4.03.0 String.lowercase is deprecated in favor of String.lowercase_ascii. So instead of writing

String.lowercase "Hello, World!"

use

String.lowercase_ascii "Hello, World!"

See String documentation for more useful functions.

Getting Started

For installation and learning resources, refer to the exercism help page.

Installation

To work on the exercises, you will need Opam and Base. Consult opam website for instructions on how to install opam for your OS. Once opam is installed open a terminal window and run the following command to install base:

opam install base

To run the tests you will need OUnit. Install it using opam:

opam install ounit

Running Tests

A Makefile is provided with a default target to compile your solution and run the tests. At the command line, type:

make

Interactive Shell

utop is a command line program which allows you to run Ocaml code interactively. The easiest way to install it is via opam:

opam install utop

Consult utop for more detail.

Feedback, Issues, Pull Requests

The exercism/ocaml repository on GitHub is the home for all of the Ocaml exercises.

If you have feedback about an exercise, or want to help implementing a new one, head over there and create an issue. We'll do our best to help you!

Source

Wikipedia http://en.wikipedia.org/wiki/Atbash

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

test.ml

open OUnit2
open Atbash_cipher

let ae exp got _test_ctxt = assert_equal ~printer:(fun x -> x) exp got

let encode_tests = [
   "encode yes" >::
     ae "bvh" (encode "yes");
   "encode no" >::
     ae "ml" (encode "no");
   "encode OMG" >::
     ae "lnt" (encode "OMG");
   "encode spaces" >::
     ae "lnt" (encode "O M G");
   "encode mindblowingly" >::
     ae "nrmwy oldrm tob" (encode "mindblowingly");
   "encode numbers" >::
     ae "gvhgr mt123 gvhgr mt" (encode "Testing,1 2 3, testing.");
   "encode deep thought" >::
     ae "gifgs rhurx grlm" (encode "Truth is fiction.");
   "encode all the letters" >::
     ae "gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt" (encode "The quick brown fox jumps over the lazy dog.");
]


let decode_tests = [
   "decode exercism" >::
     ae "exercism" (decode "vcvix rhn");
   "decode a sentence" >::
     ae "anobstacleisoftenasteppingstone" (decode "zmlyh gzxov rhlug vmzhg vkkrm thglm v");
   "decode numbers" >::
     ae "testing123testing" (decode "gvhgr mt123 gvhgr mt");
   "decode all the letters" >::
     ae "thequickbrownfoxjumpsoverthelazydog" (decode "gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt");
   "decode with too many spaces" >::
     ae "exercism" (decode "vc vix    r hn");
   "decode with no spaces" >::
     ae "anobstacleisoftenasteppingstone" (decode "zmlyhgzxovrhlugvmzhgvkkrmthglmv");
]

let different_block_size_test = [
  "encode mindblowingly with a different block size" >::
    ae "n r m w y o l d r m t o b" (encode ~block_size:1 "mindblowingly");
]

let () =
  run_test_tt_main (
    "atbash-cipher tests" >:::
      List.concat [encode_tests; decode_tests; different_block_size_test]
  )
open Base

let encrypt c =
  if Char.is_lowercase c then
    Char.(of_int_exn ((to_int 'z') + (to_int 'a') - (to_int c)))
  else
    c

let encode ?(block_size = 5) text =
  let buf = Buffer.create ((String.length text) * 2) in
  String.fold text ~init:0 ~f:(fun i c ->
      let c = Char.lowercase c in
      if Char.is_alphanum c then begin
        let i =
          if i = block_size then begin
            Buffer.add_char buf ' ';
            1
          end
          else
            i + 1
        in
        Buffer.add_char buf (encrypt c);
        i
      end
      else
        i)
  |> ignore;
  Buffer.contents buf

let decode text =
  let buf = Buffer.create (String.length text) in
  String.iter text ~f:(fun c ->
      if Char.is_alphanum c then
        Buffer.add_char buf (encrypt c)
      else if Char.(c = ' ') then
        ()
      else
        raise (Invalid_argument "invalid characters in input"));
  Buffer.contents buf

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?