# rootulp's solution

## to Simple Cipher in the Java Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

#### Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

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.

# Java Tips

This exercise has three test classes: SimpleCipherStepOneTest.java, SimpleCipherStepTwoTest.java and SimpleCipherStepThreeTest.java.

To run only one test class (e.g. in this example SimpleCipherStepOneTest.java):

``````\$ gradle test --tests *StepOne*
``````

# Running the tests

You can run all the tests for an exercise by entering

``````\$ gradle test
``````

## 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.

### SimpleCipherStepOneTest.java

``````import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
* Step 1: Make a simple shift cipher
*/
public class SimpleCipherStepOneTest {
private Cipher cipherWithDefaultKey;

@Before
public void setup() {
cipherWithDefaultKey = new Cipher();
}

/**
* Here we take advantage of the fact that plaintext of "aaa..." doesn't output the key. This is a critical problem
* with shift ciphers, some characters will always output the key verbatim.
*/
@Test
public void cipherCanEncode() {
String cipherText = cipherWithDefaultKey.getKey().substring(0, 10);
assertEquals(cipherText, cipherWithDefaultKey.encode("aaaaaaaaaa"));
}

@Ignore("Remove to run test")
@Test
public void cipherCanDecode() {
String cipherText = "aaaaaaaaaa";
assertEquals(cipherText, cipherWithDefaultKey.decode(cipherWithDefaultKey.getKey().substring(0, 10)));
}

@Ignore("Remove to run test")
@Test
public void cipherIsReversible() {
String plainText = "abcdefghij";
assertEquals(plainText, cipherWithDefaultKey.decode(cipherWithDefaultKey.encode(plainText)));
}
}``````

### SimpleCipherStepThreeTest.java

``````import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import static org.junit.Assert.*;

/**
* Step 3: Generate random key if key isn't specified. Check key is right format
*/
public class SimpleCipherStepThreeTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();

@Ignore("Remove to run test")
@Test
assertTrue(new Cipher().getKey().matches("[a-z]+"));
}

@Ignore("Remove to run test")
@Test
public void defaultCipherKeyIs100Characters() {
assertEquals(100, new Cipher().getKey().length());
}

@Ignore("Remove to run test")
@Test
public void cipherKeysAreRandomlyGenerated() {
String newKey = new Cipher().getKey();
assertFalse("Cipher constructor without argument should generate a random key. No two calls to the" +
" constructor should generate the same key. Two calls to the constructor " +
"both returned key: " + newKey, newKey.equals(new Cipher().getKey()));
}

@Ignore("Remove to run test")
@Test
public void cipherThrowsWithAllCapsKey() {
expectedException.expect(IllegalArgumentException.class);
new Cipher("ABCDEF");
}

@Ignore("Remove to run test")
@Test
public void cipherThrowsWithAnyCapsKey() {
expectedException.expect(IllegalArgumentException.class);
new Cipher("abcdEFg");
}

@Ignore("Remove to run test")
@Test
public void cipherThrowsWithNumericKey() {
expectedException.expect(IllegalArgumentException.class);
new Cipher("12345");
}

@Ignore("Remove to run test")
@Test
public void cipherThrowsWithAnyNumericKey() {
expectedException.expect(IllegalArgumentException.class);
new Cipher("abcd345ef");
}
}``````

### SimpleCipherStepTwoTest.java

``````import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import static org.junit.Assert.assertEquals;

/**
* Step 2: Specify key and use that for shift distance : substitution cipher
*/
public class SimpleCipherStepTwoTest {
private Cipher cipherWithSetKey;
private static final String key = "abcdefghij";

@Rule
public ExpectedException expectedException = ExpectedException.none();

@Before
public void setup() {
cipherWithSetKey = new Cipher(key);
}

@Ignore("Remove to run test")
@Test
public void cipherKeepsTheSubmittedKey() {
assertEquals(key, cipherWithSetKey.getKey());
}

@Ignore("Remove to run test")
@Test
public void cipherThrowsWithEmptyKey() {
expectedException.expect(IllegalArgumentException.class);
new Cipher("");
}

@Ignore("Remove to run test")
@Test
public void cipherCanEncodeWithGivenKey() {
String cipherText = "abcdefghij";
assertEquals(cipherText, cipherWithSetKey.encode("aaaaaaaaaa"));
}

@Ignore("Remove to run test")
@Test
public void cipherCanDecodeWithGivenKey() {
String cipherText = "aaaaaaaaaa";
assertEquals(cipherText, cipherWithSetKey.decode("abcdefghij"));
}

@Ignore("Remove to run test")
@Test
public void cipherIsReversibleGivenKey() {
String plainText = "abcdefghij";
assertEquals(plainText, cipherWithSetKey.decode(cipherWithSetKey.encode("abcdefghij")));
}

@Ignore("Remove to run test")
@Test
public void cipherCanWrapEncode() {
String cipherText = "zabcdefghi";
assertEquals(cipherText, cipherWithSetKey.encode("zzzzzzzzzz"));
}

@Ignore("Remove to run test")
@Test
public void cipherCanEncodeMessageThatIsShorterThanTheKey() {
String cipherText = "abcde";
assertEquals(cipherText, cipherWithSetKey.encode("aaaaa"));
}

@Ignore("Remove to run test")
@Test
public void cipherCanDecodeMessageThatIsShorterThanTheKey() {
String cipherText = "aaaaa";
assertEquals(cipherText, cipherWithSetKey.decode("abcde"));
}

@Ignore("Remove to run test")
@Test
public void cipherCanDoubleShiftEncode() {
String plainText = "iamapandabear";
String cipherText = "qayaeaagaciai";
assertEquals(cipherText, new Cipher(plainText).encode(plainText));
}
}``````
``````import java.util.Random;

public final class Cipher {

private String key;
private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";

public Cipher(String key) {
setKey(key);
}

public Cipher() {
setKey(randomKey());
}

public String getKey() {
return key;
}

private void setKey(String key) {
if (!key.matches("\\p{javaLowerCase}+")) {
throw new IllegalArgumentException();
}

this.key = key;
}

public String encode(String input) {
StringBuilder output = new StringBuilder(input.length());

for (int i = 0; i < Math.min(input.length(), key.length()); i++) {
output.append(encodeChar(input.charAt(i), i));
}

return output.toString();
}

public String decode(String input) {
StringBuilder output = new StringBuilder(input.length());

for (int i = 0; i < input.length(); i++) {
output.append(decodeChar(input.charAt(i), i));
}

return output.toString();
}

private char encodeChar(Character c, Integer i) {
int alphaI = ALPHABET.indexOf(c) + ALPHABET.indexOf(key.charAt(i));
return ALPHABET.charAt(wrapAlphaI(alphaI));
}

private char decodeChar(Character c, Integer i) {
int alphaI = ALPHABET.indexOf(c) - ALPHABET.indexOf(key.charAt(i));
return ALPHABET.charAt(wrapAlphaI(alphaI));
}

private Integer wrapAlphaI(Integer alphaI) {

while (alphaI < 0) {
alphaI += ALPHABET.length();
}

while (alphaI >= ALPHABET.length()) {
alphaI -= ALPHABET.length();
}

return alphaI;
}

private String randomKey() {
StringBuilder key = new StringBuilder(100);

for (int i = 0; i < 100; i++) {
key.append(randomChar());
}

return key.toString();
}

private char randomChar() {
Random r = new Random();
return (char)(r.nextInt(26) + 'a');
}

}``````