Sunday, May 8, 2016

Caesar Cipher in C#

So I was talking to a co-worker the other day and the topic of a Caesar Cipher came up in our conversation. We talked about how it wouldn't be too hard to code something quick that would be able to "encrypt" some text.

So I was kind of bored over this weekend, and I decided that it would be a good exercise to write a Caesar Cipher. Here is my code:

class CaesarCipher
{
    private string Sentence;
    private int EncryptShift;
    private int DecryptShift;
    private bool IsEncrypted = false;

    public CaesarCipher(string input, int shifting)
    {
        Sentence = input.ToLower();
        EncryptShift = shifting;
        DecryptShift = -shifting;
    }

    public string Encrypt()
    {
        if (IsEncrypted)
            return Sentence;

        char[] char_array = Sentence.ToCharArray();

        Shuffle(char_array, EncryptShift);

        Recunstruct(char_array);

        return Sentence;
    }

    public string Decrypt()
    {
        if (!IsEncrypted)
            return Sentence;

        char[] char_array = Sentence.ToCharArray();

        Shuffle(char_array, DecryptShift);

        Recunstruct(char_array);

        return Sentence;
    }

    private void Shuffle(char[] char_array, int shift)
    {
        for (int index = 0; index < char_array.Length; index++)
        {
            char letter = char_array[index];

            if (letter >= 'a' && letter <= 'z')
            {
                letter = (char)(letter + shift);

                if (letter > 'z')
                    letter = (char)(letter - 26);

                else if (letter < 'a')
                    letter = (char)(letter + 26);
            }

            char_array[index] = letter;
        }
    }

    private void Recunstruct(char[] char_array)
    {
        Sentence = null;

        foreach (char letter in char_array)
            Sentence += letter;

        IsEncrypted = true;
    }
}

That's all for now, thanks for reading!

No comments:

Post a Comment