Avatar of artemkorsakov

artemkorsakov's solution

to Simple Cipher in the C# Track

Published at Feb 27 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 cryptanalysis, but we are lucky that generally our little sisters are not cryptanalysts.

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:

Caesar Cipher

For example:

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

When "ldpdsdqgdehdu" is put into the decode method 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 alphanumeric characters in length.

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.

Running the tests

To run the tests, run the command dotnet test from within the exercise directory.

Initially, only the first test will be enabled. This is to encourage you to solve the exercise one step at a time. Once you get the first test passing, remove the Skip property from the next test and work on getting that test passing. Once none of the tests are skipped and they are all passing, you can submit your solution using exercism submit SimpleCipher.cs

Further information

For more detailed information about the C# track, including how to get help if you're having trouble, please visit the exercism.io C# language 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.

SimpleCipherTest.cs

// This file was auto-generated based on version 2.0.0 of the canonical data.

using System;
using Xunit;

public class SimpleCipherTest
{
    [Fact]
    public void Random_key_cipher_can_encode()
    {
        var sut = new SimpleCipher();
        Assert.Equal(sut.Key.Substring(0, 10), sut.Encode("aaaaaaaaaa"));
    }

    [Fact(Skip = "Remove to run test")]
    public void Random_key_cipher_can_decode()
    {
        var sut = new SimpleCipher();
        Assert.Equal("aaaaaaaaaa", sut.Decode(sut.Key.Substring(0, 10)));
    }

    [Fact(Skip = "Remove to run test")]
    public void Random_key_cipher_is_reversible_i_e_if_you_apply_decode_in_a_encoded_result_you_must_see_the_same_plaintext_encode_parameter_as_a_result_of_the_decode_method()
    {
        var sut = new SimpleCipher();
        Assert.Equal("abcdefghij", sut.Decode(sut.Encode("abcdefghij")));
    }

    [Fact(Skip = "Remove to run test")]
    public void Random_key_cipher_key_is_made_only_of_lowercase_letters()
    {
        var sut = new SimpleCipher();
        Assert.Matches("^[a-z]+$", sut.Key);
    }

    [Fact(Skip = "Remove to run test")]
    public void Substitution_cipher_can_encode()
    {
        var sut = new SimpleCipher("abcdefghij");
        Assert.Equal("abcdefghij", sut.Encode("aaaaaaaaaa"));
    }

    [Fact(Skip = "Remove to run test")]
    public void Substitution_cipher_can_decode()
    {
        var sut = new SimpleCipher("abcdefghij");
        Assert.Equal("aaaaaaaaaa", sut.Decode("abcdefghij"));
    }

    [Fact(Skip = "Remove to run test")]
    public void Substitution_cipher_is_reversible_i_e_if_you_apply_decode_in_a_encoded_result_you_must_see_the_same_plaintext_encode_parameter_as_a_result_of_the_decode_method()
    {
        var sut = new SimpleCipher("abcdefghij");
        Assert.Equal("abcdefghij", sut.Decode(sut.Encode("abcdefghij")));
    }

    [Fact(Skip = "Remove to run test")]
    public void Substitution_cipher_can_double_shift_encode()
    {
        var sut = new SimpleCipher("iamapandabear");
        Assert.Equal("qayaeaagaciai", sut.Encode("iamapandabear"));
    }

    [Fact(Skip = "Remove to run test")]
    public void Substitution_cipher_can_wrap_on_encode()
    {
        var sut = new SimpleCipher("abcdefghij");
        Assert.Equal("zabcdefghi", sut.Encode("zzzzzzzzzz"));
    }

    [Fact(Skip = "Remove to run test")]
    public void Substitution_cipher_can_wrap_on_decode()
    {
        var sut = new SimpleCipher("abcdefghij");
        Assert.Equal("zzzzzzzzzz", sut.Decode("zabcdefghi"));
    }

    [Fact(Skip = "Remove to run test")]
    public void Substitution_cipher_can_encode_messages_longer_than_the_key()
    {
        var sut = new SimpleCipher("abc");
        Assert.Equal("iboaqcnecbfcr", sut.Encode("iamapandabear"));
    }

    [Fact(Skip = "Remove to run test")]
    public void Substitution_cipher_can_decode_messages_longer_than_the_key()
    {
        var sut = new SimpleCipher("abc");
        Assert.Equal("iamapandabear", sut.Decode("iboaqcnecbfcr"));
    }
}
using System;
using System.Linq;

public class SimpleCipher
{
    private const string Chars = "abcdefghijklmnopqrstuvwxyz";
    private static readonly Random Random = new Random();

    public SimpleCipher()
    {
        Key = new string(Enumerable.Repeat(Chars, 100).Select(s => s[Random.Next(s.Length)]).ToArray());
    }

    public SimpleCipher(string key)
    {
        Key = key;
    }

    public string Key { get; }

    public string Encode(string plaintext)
    {
        return plaintext.Select((t, i) => GetAlphabetChar(t, i, +1)).Aggregate("", (current, d) => current + d);
    }

    public string Decode(string ciphertext)
    {
        return ciphertext.Select((t, i) => GetAlphabetChar(t, i, -1)).Aggregate("", (current, d) => current + d);
    }

    private char GetAlphabetChar(char oldChar, int index, int sign)
    {
        var shift = Key[index % Key.Length] - 'a';
        var newChar = oldChar + sign * shift;
        var result = newChar > 'z' ? newChar - Chars.Length : newChar < 'a' ? newChar + Chars.Length : newChar;
        return (char)result;
    }
}

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?