ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

# SergiiVlasiuk's solution

## to Simple Cipher in the Scala Track

Published at Sep 01 2019 · 0 comments
Instructions
Test suite
Solution

Implement a simple shift cipher like Caesar and a more secure substitution cipher.

## Step 1

"If he had anything confidential to say, he wrote it in cipher, that is, by so changing the order of the letters of the alphabet, that not a word could be made out. If anyone wishes to decipher these, and get at their meaning, he must substitute the fourth letter of the alphabet, namely D, for A, and so with the others." â€”Suetonius, Life of Julius Caesar

Ciphers are very straight-forward algorithms that allow us to render text less readable while still allowing easy deciphering. They are vulnerable to many forms of cryptoanalysis, but we are lucky that generally our little sisters are not cryptoanalysts.

The Caesar Cipher was used for some messages from Julius Caesar that were sent afield. Now Caesar knew that the cipher wasn't very good, but he had one ally in that respect: almost nobody could read well. So even being a couple letters off was sufficient so that people couldn't recognize the few words that they did know.

Your task is to create a simple shift cipher like the Caesar Cipher. This image is a great example of the Caesar Cipher:

For example:

Giving "iamapandabear" as input to the encode function returns the cipher "ldpdsdqgdehdu". Obscure enough to keep our message secret in transit.

When "ldpdsdqgdehdu" is put into the decode function it would return the original "iamapandabear" letting your friend read your original message.

## Step 2

Shift ciphers are no fun though when your kid sister figures it out. Try amending the code to allow us to specify a key and use that for the shift distance. This is called a substitution cipher.

Here's an example:

Given the key "aaaaaaaaaaaaaaaaaa", encoding the string "iamapandabear" would return the original "iamapandabear".

Given the key "ddddddddddddddddd", encoding our string "iamapandabear" would return the obscured "ldpdsdqgdehdu"

In the example above, we've set a = 0 for the key value. So when the plaintext is added to the key, we end up with the same message coming out. So "aaaa" is not an ideal key. But if we set the key to "dddd", we would get the same thing as the Caesar Cipher.

## Step 3

The weakest link in any cipher is the human being. Let's make your substitution cipher a little more fault tolerant by providing a source of randomness and ensuring that the key contains only lowercase letters.

If someone doesn't submit a key at all, generate a truly random key of at least 100 characters in length.

If the key submitted is not composed only of lowercase letters, your solution should handle the error in a language-appropriate way.

## Extensions

Shift ciphers work by making the text slightly odd, but are vulnerable to frequency analysis. Substitution ciphers help that, but are still very vulnerable when the key is short or if spaces are preserved. Later on you'll see one solution to this problem in the exercise "crypto-square".

If you want to go farther in this field, the questions begin to be about how we can exchange keys in a secure way. Take a look at Diffie-Hellman on Wikipedia for one of the first implementations of this scheme.

The Scala exercises assume an SBT project scheme. The exercise solution source should be placed within the exercise directory/src/main/scala. The exercise unit tests can be found within the exercise directory/src/test/scala.

To run the tests simply run the command `sbt test` in the exercise directory.

For more detailed info about the Scala track see the help page.

## Source

Substitution Cipher at Wikipedia http://en.wikipedia.org/wiki/Substitution_cipher

## Submitting Incomplete Solutions

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

### CipherTest.scala

``````import org.scalatest.{Matchers, FunSuite}

/** @version created manually **/
class CipherTest extends FunSuite with Matchers {

test("Random key cipher - can encode/decode") {
// Here we take advantage of the fact that plaintext of "aaa..."
// outputs the key. This is a critical problem with shift ciphers, some
// characters will always output the key verbatim.

val cipher = Cipher(None)
cipher.encode("aaaaaaaaaa") should be (cipher.key.substring(0, 10))
cipher.decode(cipher.key.substring(0, 10)) should be ("aaaaaaaaaa")
}

test("Invalid key - contains caps") {
pending
intercept[IllegalArgumentException] {
Cipher(Some("ABCD"))
}
}

test("Invalid key - contains numerics") {
pending
intercept[IllegalArgumentException] {
Cipher(Some("123"))
}
}

test("Invalid key - is empty") {
pending
intercept[IllegalArgumentException] {
Cipher(Some(""))
}
}

test("Substitution cipher - can encode") {
pending
Cipher(Some("abcdefghij")).encode("aaaaaaaaaa") should be ("abcdefghij")
}

test("Substitution cipher - can decode") {
pending
Cipher(Some("abcdefghij")).decode("abcdefghij") should be ("aaaaaaaaaa")
}

test("Substitution cipher - is reversible") {
pending
val cipher = Cipher(Some("abcdefghij"))
cipher.decode(cipher.encode("abcdefghij")) should be ("abcdefghij")
}

test("Substitution cipher - can double shift") {
pending
val cipher = Cipher(Some("iamapandabear"))
cipher.encode("iamapandabear") should be ("qayaeaagaciai")
}

test("Substitution cipher - can wrap") {
pending
Cipher(Some("abcdefghij")).encode("zzzzzzzzzz") should be ("zabcdefghi")
}
}``````
``````import scala.util.Random

case class Cipher(key: String) {
private val startChar = 'a'.toInt

private def encodeChar(charKey: Char, actual: Char): Char =
(math.abs(actual + charKey - 2 * startChar) % 26 + startChar).toChar

private def decodeChar(charKey: Char, actual: Char) =
(math.abs(actual - charKey) % 26 + startChar).toChar

private def transform(input: String, fun: (Char, Char) => Char) =
key.zip(input).map { case (pivot, actual) => fun(pivot, actual) }.mkString

def encode(phrase: String): String = transform(phrase, encodeChar)

def decode(phrase: String): String = transform(phrase, decodeChar)
}

object Cipher {
val letters = 'a' to 'z'

def generateKey() = (0 until 100).map(_ => letters(Random.nextInt(letters.length))).mkString

def apply(pivot: Option[String]): Cipher = pivot match {
case Some(value) if value.isEmpty => throw new IllegalArgumentException()
case Some(value) if value.exists(x => x.isUpper || x.isDigit) => throw new IllegalArgumentException()
case None => new Cipher(generateKey)
case Some(value) => new Cipher(value)
}
}``````