Saturday 7 January 2017

AI Caesar Cipher

Hello everyone. This blog is all about creating a smart code that secures
your data in a better way.

Here, I will be discussing about AI (Artificially Intelligent) Caesar Cipher.
The basic Caesar Cipher algorithm remains the same. But the change that has
been introduced here is the randomness of the key value that encrypts
the plain text. For example, 3 is normally added with every character of
the plain text giving rise to the cipher text.

Plain Text
H
e
l
l
o
Key
+3
+3
+3
+3
+3
Cipher Text
K
h
o
o
r


In this special case, key value is not fixed, it is random. It can be 3, 4, 5 or
anything.

Before going into the details, I need to explain something. It is not an
artificially intelligent algorithm. Rather it is an artificially intelligent
encryptor-decryptor. Reason behind this statement is that there should not
be any alteration done on the algorithm while the message is in transit. As
the decryptor may not be able to retrieve the original message from the
cipher text because of the changed algorithm. Whatever change must be done,
must be done before sending the message and after receiving the message.
Not while in transit!

Let’s dive into my code.

First of all, it generates a random key of 5 characters. The key is a combination
of { 3, 4, 5, C, D, E }. I chose this combination out of nowhere. You can have
yours. For example, the key can be 3EE4D, C553D, D5CCE, etc.
This key plays an important role in this code. With this key, the encryptor
knows which value should be added or subtracted from the plain text.
For example, for the key values 3, 4 & 5; 3, 4 or 5 will be subtracted from the
plain text and for the key values C, D & E; 3, 4 or 5 will be added to the plain
text. As the key is of 5 characters, the plain text is encrypted 5 times using
Caesar Cipher along with the corresponding key value. The randomness of
the key adds an extra security layer to our message. Anyone who tries to
hack the message, won’t be able to guess the logic as there is no
fixed sequence of operations.

Then how will the decryptor know about the sequence of operations?
The answer is hidden inside the key. The sequence of the characters in the
key will tell the decryptor what operation to do next. This logic can be
used not only for one algorithm, but for multiple algorithms. Each character
in the key can denote a different algorithm. And that’s how the encryptor
and the decryptor becomes smart (artificially intelligent).

Here is the MainWindow.xaml code

<Window x:Class="WpfAppAICryptoAlgo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfAppAICryptoAlgo"
        mc:Ignorable="d"
        Title="MainWindow" Height="380" Width="525" WindowStartupLocation="CenterScreen">
    <Grid>
        <Button x:Name="GenerateButton" Content="Generate Random Key" HorizontalAlignment="Left" Height="20" Margin="10,10,0,0" VerticalAlignment="Top" Width="128" Click="GenerateButton_Click"/>
        <Label x:Name="KeyLabel" HorizontalAlignment="Left" Height="29" Margin="155,10,0,0" VerticalAlignment="Top" Width="125"/>
        <TextBlock HorizontalAlignment="Left" Margin="41,69,0,0" TextWrapping="Wrap" Text="Key" VerticalAlignment="Top"/>
        <TextBox x:Name="KeyTextBox" HorizontalAlignment="Left" Height="23" Margin="136,69,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <TextBlock HorizontalAlignment="Left" Margin="46,121,0,0" TextWrapping="Wrap" Text="Plain Text" VerticalAlignment="Top"/>
        <TextBox x:Name="PlainTextBox" HorizontalAlignment="Left" Height="23" Margin="136,120,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="213"/>
        <Button x:Name="EncryptButton" Content="Encrypt" HorizontalAlignment="Left" Height="22" Margin="105,167,0,0" VerticalAlignment="Top" Width="132" Click="EncryptButton_Click"/>
        <TextBlock HorizontalAlignment="Left" Margin="46,218,0,0" TextWrapping="Wrap" Text="Cipher Text" VerticalAlignment="Top"/>
        <TextBox x:Name="CipherTextBox" HorizontalAlignment="Left" Height="23" Margin="136,217,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="213"/>
        <TextBlock HorizontalAlignment="Left" Margin="46,287,0,0" TextWrapping="Wrap" Text="Plain Text" VerticalAlignment="Top"/>
        <TextBox x:Name="PlainTextBox_Copy" HorizontalAlignment="Left" Height="23" Margin="136,286,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="213"/>
        <Button x:Name="DecryptButton" Content="Decrypt" HorizontalAlignment="Left" Height="22" Margin="105,252,0,0" VerticalAlignment="Top" Width="132" Click="DecryptButton_Click"/>
        <Button x:Name="ResetButton" Content="Reset" HorizontalAlignment="Left" Height="29" Margin="411,10,0,0" VerticalAlignment="Top" Width="85" Click="ResetButton_Click"/>

    </Grid>
</Window>

Here is the MainWindow.xaml.cs code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfAppAICryptoAlgo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        Random rnd;

        public MainWindow()
        {
            InitializeComponent();

            rnd = new Random();
        }

        private int GenerateRandomNumber()
        {
            int n = -1;

            n = rnd.Next(3, 6);

            return n;
        }

        private char GenerateRandomCharacter()
        {
            char ch = '!';

            int n = rnd.Next(3, 6);

            if (n == 3)
                ch = 'C';
            else if (n == 4)
                ch = 'D';
            else
                ch = 'E';

            return ch;
        }

        private string GenerateKey()
        {
            string key = "";

            for (int i = 0; i < 5; i++)
            {
                bool IsItCharacter = Convert.ToBoolean(rnd.Next(0,2));

                if(IsItCharacter)
                {
                    key += GenerateRandomCharacter();
                }
                else
                {
                    key += GenerateRandomNumber().ToString();
                }
            }

            return key;
        }

        private void GenerateButton_Click(object sender, RoutedEventArgs e)
        {
            KeyLabel.Content = GenerateKey();
            KeyTextBox.Text = KeyLabel.Content.ToString();
        }

        private int GetNumber(char v)
        {
            int vc = -1;

            if (v == 'C')
                vc = 3;
            else if (v == 'D')
                vc = 4;
            else
                vc = 5;

            return vc;
        }

        private string AIEncryption(string plaintext, string keytext)
        {
            string ciphertext = null;

            ciphertext = plaintext;
            char[] keychars = keytext.ToCharArray();
            int valuechanger;

            CaesarCipher ccAlgo = new CaesarCipher();

            for (int i = 0; i < keychars.Length; i++)
            {
                if (char.IsDigit(keychars[i]))
                {
                    valuechanger = -(int.Parse(keychars[i].ToString()));
                }
                else
                {
                    valuechanger = GetNumber(keychars[i]);
                }

                ciphertext = ccAlgo.Encrypt(ciphertext, valuechanger);
            }

            return ciphertext;
        }

        private string AIDecryption(string ciphertext, string keytext)
        {
            string plaintext = null;

     string revkey = new string(keytext.Reverse().ToArray());

            plaintext = ciphertext;
            char[] keychars = revkey.ToCharArray();
            int valuechanger;

            CaesarCipher ccAlgo = new CaesarCipher();

            for (int i = 0; i < keychars.Length; i++)
            {
                if (char.IsDigit(keychars[i]))
                {
                    valuechanger = -(int.Parse(keychars[i].ToString()));
                }
                else
                {
                    valuechanger = GetNumber(keychars[i]);
                }

                plaintext = ccAlgo.Decrypt(plaintext, valuechanger);
            }

            return plaintext;
        }

        private void EncryptButton_Click(object sender, RoutedEventArgs e)
        {
            CipherTextBox.Text = AIEncryption(PlainTextBox.Text, KeyTextBox.Text);
        }

        private void DecryptButton_Click(object sender, RoutedEventArgs e)
        {
            PlainTextBox_Copy.Text = AIDecryption(CipherTextBox.Text, KeyTextBox.Text);
        }

        private void ResetButton_Click(object sender, RoutedEventArgs e)
        {
            KeyLabel.Content = "";
            KeyTextBox.Text = "";
            PlainTextBox.Text = "";
            CipherTextBox.Text = "";
            PlainTextBox_Copy.Text = "";
        }
    }
}

Here is the CaesarCipher.cs code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfAppAICryptoAlgo
{
    public class CaesarCipher
    {
        public string Encrypt(string plaintext, int key)
        {
            int av, oav, cav, cv, moav;
            string ciphertext = null;
            char[] ptca = plaintext.ToCharArray();
            char[] cc = new char[500];

            for (int i = 0; i < ptca.Length; i++)
            {
                if (ptca[i] == ' ')
                {
                    cc[i] = ptca[i];
                }
                else
                {
                    if (Char.IsLetter(ptca[i]))
                    {
                        if (Char.IsUpper(ptca[i]))
                        {
                            av = ptca[i];
                            oav = av - 65;
                            moav = oav + key;
                            cav = ModFunction(moav, 26);
                            cv = cav + 65;
                            cc[i] = (char)cv;
                        }
                        else
                        {
                            av = ptca[i];
                            oav = av - 97;
                            moav = oav + key;
                            cav = ModFunction(moav, 26);
                            cv = cav + 97;
                            cc[i] = (char)cv;
                        }
                    }
                    else if (Char.IsDigit(ptca[i]))
                    {
                        av = ptca[i];
                        oav = av - 48;
                        moav = oav + key;
                        cav = ModFunction(moav, 10);
                        cv = cav + 48;
                        cc[i] = (char)cv;
                    }
                    else
                    {
                        av = ptca[i];
                        cv = av + key;
                        cc[i] = (char)cv;
                    }
                }
                ciphertext += cc[i];
            }

            return ciphertext;
        }

        public string Decrypt(string ciphertext, int key)
        {
            int av, oav, cav, cv, moav;
            string plaintext = null;
            char[] ctca = ciphertext.ToCharArray();
            char[] cc = new char[500];
            for (int i = 0; i < ctca.Length; i++)
            {
                if (ctca[i] == ' ')
                {
                    cc[i] = ctca[i];
                }
                else
                {
                    if (Char.IsLetter(ctca[i]))
                    {
                        if (Char.IsUpper(ctca[i]))
                        {
                            av = ctca[i];
                            oav = av - 65;
                            moav = oav - key;
                            cav = ModFunction(moav, 26);
                            cv = cav + 65;
                            cc[i] = (char)cv;
                        }
                        else
                        {
                            av = ctca[i];
                            oav = av - 97;
                            moav = oav - key;
                            cav = ModFunction(moav, 26);
                            cv = cav + 97;
                            cc[i] = (char)cv;
                        }
                    }
                    else if (Char.IsDigit(ctca[i]))
                    {
                        av = ctca[i];
                        oav = av - 48;
                        moav = oav - key;
                        cav = ModFunction(moav, 10);
                        cv = cav + 48;
                        cc[i] = (char)cv;
                    }
                    else
                    {
                        av = ctca[i];
                        cv = av - key;
                        cc[i] = (char)cv;
                    }
                }
                plaintext += cc[i];

            }
            return plaintext;
        }

        private int ModFunction(int a, int b)
        {
            int c = 0;
            if (a < 0)
            {
                c = a + b;
            }
            else
            {
                c = a % b;
            }

            return c;
        }
    }
}


Here is the working video link:



Did you notice one more thing? Even the Caesar Cipher (a technique based algorithm)
is having a key now, to lock and unlock the message! Pretty interesting right ;)

That’s the end of it. I hope you find my blogs useful.
Stay tuned and keep coding.