Avatar of shmibs

shmibs's solution

to Atbash Cipher in the Crystal Track

Published at Nov 18 2018 · 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

Setup

Follow the setup instructions for Crystal here:

http://exercism.io/languages/crystal

More help installing can be found here:

http://crystal-lang.org/docs/installation/index.html

Making the Test Suit Pass

Execute the tests with:

$ crystal spec

In each test suite all but the first test have been skipped.

Once you get a test passing, you can unskip the next one by changing pending to it.

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.

atbash_cipher_spec.cr

require "spec"
require "../src/*"

describe "Atbash" do
  describe "#encode" do
    it "encodes no" do
      Atbash.encode("no").should eq "ml"
    end

    pending "encodes yes" do
      Atbash.encode("yes").should eq "bvh"
    end

    pending "encode OMG" do
      Atbash.encode("OMG").should eq "lnt"
    end

    pending "encodes O M G spaces" do
      Atbash.encode("O M G").should eq "lnt"
    end

    pending "encode long words" do
      Atbash.encode("mindblowingly").should eq "nrmwy oldrm tob"
    end

    pending "encodes numbers" do
      Atbash.encode("Testing, 1 2 3, testing.").should eq "gvhgr mt123 gvhgr mt"
    end

    pending "encodes sentence" do
      Atbash.encode("Truth is fiction.").should eq "gifgs rhurx grlm"
    end

    pending "encodes all the things" do
      plaintext = "The quick brown fox jumps over the lazy dog."
      cipher = "gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt"
      Atbash.encode(plaintext).should eq cipher
    end
  end
end
module Atbash
	extend self

	def encode(s : String, chunk_width = 5)
		if chunk_width < 1
			raise ArgumentError.new "chunk_width must be a positive integer"
		end

		# filter unused chars and reject non-ascii
		l = s.each_char.compact_map { |c|
			if !c.ascii?
				raise ArgumentError.new "non-ascii chars present in plaintext"
			end

			if c.ascii_alphanumeric?
				c
			else
				nil
			end
		}

		# work on chunks of chunk_width
		l = l.each_slice(chunk_width).map { |chunk|
			# encode each chunk
			chunk.map { |c|
				if c.ascii_number?
					# just append digits
					c
				else
					# when the alphabet is zero-indexed, 26 - c gives the atbash
					# translation. because this is ascii, 'a' is 97 rather than 0, so
					# shift values accordingly
					((26 - (c.downcase - 'a')) + 96).unsafe_chr
				end
			}
		}

		# build the return string
		String.build { |s|
			l.each.with_index { |chunk, i|
				# insert a space if not at head of the string
				if i != 0
					s << " "
				end
				# insert all the chars for this chunk
				chunk.each { |c|
					s << c
				}
			}
		}
		
	end

end

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?