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.

Saturday 27 August 2016

Data Encryption Standard (DES)

Hello everyone. In this blog, I will be discussing about first Symmetric Key
Cryptography - Data Encryption Standard (DES) - in details.

DES was developed by IBM in 1970s and later standardized in public by NSA
in 1977. It is a block cipher. It encrypts data in blocks of size 64 bits
each. DES uses heavily bit operations. It uses a key of 56 bit length. The
same algorithm and the key is used for decryption process.

Actually, the original key is of 64 bit length. But for parity checking
purpose, every 8th bit is discarded from the original key, making it a
key of 56 bit length. Now what I have done here is that I took ASCII value
of each character from the plain text and the key and converted to binary
digits of 8 bit length. Now this happens that the total length of the plain
text and the key may not be an exact multiple of 64. So I appended zeroes
at the end of the plain text and the key in such a way that they become a
multiple of 64. One important thing to note is that the key size cannot be
greater than 8 characters. As each character represents 8 bits and the
size of key cannot be greater than 64 bits, hence key size cannot be
more than 8 characters.

Now divide the plain text in blocks of 64 bits. Take each block one by one.
And start encrypting them with DES. The DES involves the following steps :



1. Initial Permutation:
   As the name suggests, it rearranges the first Plain Text block bits
   according to the IP table. That is, the first bit of the permuted text
   block will be the 58th bit of the first plain text block, the second
   bit will be the 50th bit of the first plain text block and so on. Now
   divide the permuted text into two halves - 32 bit Left Plain Text (LPT)
   and 32 bit Right Plain Text (RPT).



2. 16 Rounds:
   a) Key Transformation:
      Divide the 56 bit Key into two halves - C Key (28 bit) and
      D Key (28 bit). Perform Left Circular Shift to C Key and D Key
      according to the Circular Left Shift Table.



      After the shift, join C Key and D Key again to make Shifted Key of
      56 bit.

   b) Compression Permutation:
      This step involves selection of 48 bits out of 56 bits of Shifted
      Key. In other words, Shifted Key is compressed and permuted at the
      same time. It is done according to the Compression Permutation table.
      For example, the first bit of Compressed Key will be the 14th
      bit of the shifted key and so on.



   c) Expansion Permutation:
      Recall that after Initial Permutation, we had LPT and RPT, each of 32
      bit length. During this step, RPT is expanded from 32 bit to 48 bit.
      Besides this, it is permuted as well. Hence the Expansion Permutation.
      At first, 32 bit RPT is divided into 8 blocks of 4 bits each. Then
      each 4 bit block is expanded to 6 bit block by adding two more bits.
      One bit at the beginning of the 4 bit block and the other bit at the
      end of that 4 bit block.



      This is how it is done. For simplicity of the computation, this process
      has been stored in the Expansion Permutation table. After this step, RPT
      has 8 blocks of 6 bits each, making it a 48 bit Expanded RPT.



   d) XOR:
      This step involves the bitwise XOR operation between the Expanded RPT
      of 48 bit length and the Compressed Key of 48 bit length. This results
      in the XORed RPT of 48 bit length.

   e) S Box Substitution:
      The XORed RPT is fed into the S Box Substitution step. Here, the XORed
      RPT is again divided into 8 blocks of 6 bit each. For each block, there
      is a separate S Box table which gives 4 bit output. Hence, there are 8
      S Box tables corresponding to 8 blocks. For example, Block 1 will be
      fed to S Box 1, Block 2 to S Box 2 and so on. S Box tables consist of
      4 rows and 16 columns. Each row contains 0 to 15 numbers in haphazard
      manner. These 0 to 15 numbers can be represented with 4 bits. As we know,
      each block contains 6 bits, these 6 bits tell us the row number and the
      column number of the S Box table corresponding to that block. The 1st
      bit and the 6th bit determines the row number whereas 2nd, 3rd, 4th and
      5th bits determine the column number. The value that is obtained at the
      intersection of the row number and the column number is the 4 bit output
      of the S Box table. So each of the 8 blocks gives 4 bit output, giving
      rise to 32 bit S Box RPT.






   f) P Box Permutation:
      In this step, S Box RPT will be permuted according to the P Box table
      giving rise to P Box RPT.



   g) XOR and Swap:
      During all these operations, the LPT was left untouched so far. So in
      this step, P Box RPT of 32 bit length and the untouched LPT of 32 bit
      length is XORed. The XORed text is stored in the RPT and the original
      RPT is stored in the LPT. After this, again the next round starts.
      That is why it is called 16 Rounds.



3. At the end of the 16 rounds, the Final Permutation is done on the combined
   LPT and RPT giving rise to 64 bit first Cipher Text block. It is done
   according to the Final Permutation table.



4. All the previous steps i.e. 1,2 and 3 is performed for all the other Plain
   Text blocks to get the corresponding Cipher Text blocks. At the very end,
   all the Cipher Text blocks are combined to obtain the final cipher text.

Here is the file that contains the C# code for DES. As it is a very long code
(574 lines of code more specifically), that's why I have provided the file.
https://drive.google.com/file/d/0B9s_U5HeDEtAcWJfMl81VloycFE/view?usp=sharing

Here is the theoretical video of DES:


Here is the working video of DES:


In this modern world, people don't use Single DES as it is vulnerable to
heavy attacks. That's why they prefer more Double DES and Triple DES.
In Double DES, DES is done twice with 2 different keys.



In Triple DES, DES is done thrice. Here Triple DES can be performed with
3 keys or even 2 keys.





That's the end of this blog. I hope you find my blogs useful. Till then
stay tuned and keep coding.

Practice Page Link:
http://handsoncrypto.azurewebsites.net/PracticePage.aspx

Sunday 14 August 2016

Key Based Cryptographic Algorithms

Hello everyone. With my previous blogs, we have come to know a little about
Technique Based Cryptographic Algorithms and their working mechanisms. In this
blog, I will be discussing about Key Based Cryptographic Algorithms. Key based
algorithms are fairly harder than the Technique based algorithms. These involve
more complex concepts that make these algorithms far more secure than Technique
based algorithms.

Before going into the details of Key based algorithms, there is another small
classification of the algorithms that categorize into parts :

1. Stream Cipher -  In this cipher, one by one character is processed at a time.

2. Block Cipher -  In this cipher, a fixed size block is extracted from the whole
   plain text and then one by one character is processed at a time.

We will start to see the significance of this classification once we start digging into
the algorithm demonstrations.

So, let's come back to the classification of Key Based Algorithms. There are two types :

1. Symmetric Key Cryptography or Private Key Cryptography :
   In this type of cryptography, only one key is used and the same key is used to encrypt
   and decrypt the message. Both parties must agree upon the same key before any
   transmission begins. This key should be only known to the two parties and no one else.
   That's why it is also called as Private Key Cryptography or Secret Key Cryptography.
   Example - DES, IDEA, RC4, RC5, BlowFish, AES, etc.



2. Asymmetric Key Cryptography or Public Key Cryptography :
   In this type of cryptography, two different keys are used - one is public key which is
   available to all for encrypting the message and the other one is private key which is
   available only to the receiver for decrypting the message. Both the keys are generated
   by the receiver but only the public key is sent to the sender for encryption. Any sender
   can encrypt the message with the public key but only receiver can decrypt the message
   with the private key. This feature ensures that only the intended person can only read
   the message and no one else. That's why it is also called Public Key Cryptography.
   Example - Merkle's Puzzles, RSA, ElGamal, ECC, etc.



In my next blogs, I will start with the demonstrations of Symmetric Key Cryptographic
Algorithms. That's all for this blog.

I hope you find it useful. Till then keep coding.

Friday 29 July 2016

Simple Columnar Method With Multiple Rounds

Hello everyone. This blog introduces you to another Transposition
techniques - Simple Columnar Method With Multiple Rounds.

It is a very efficient and useful transposition algorithm. There are
two forms of this algorithm. One is the "Simple Columnar Method With
One Round" or simply "Simple Columnar Method" and the other one is
the "Simple Columnar Method With Multiple Rounds". Here we are going
to discuss the latter.

In this algorithm, we write the plain text message row-by-row in a
2D array of any size( Let's say 10x5 according to the example given
below ). Then read the message in column-by-column. However, it is
not necessary to read the message in order of Column 1, Column 2,
Column 3 and so on. It can be any random order like 2, 0, 3, 1, 4
( according the example ). Thus the message obtained is the cipher
text of round 1. This cipher text is input as plain text to round 2.
This process keeps on going until the last round. You can keep the
column order same or different for every round. Here I have used
different column order for every round. This example involves
four rounds. That's why it is called Simple Columnar Method With
Multiple Rounds. The final message that we obtain after the last
round is the cipher text that is send to the receiver. The receiver
reverses the algorithm to decrypt the cipher text. On the receiver
side, the last round of the sender side becomes the first round of
receiver side and so. We write the cipher text column-by-column in
the specified column order by the corresponding round. Then we read
row-by-row to get the original message.



Here is the C# code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WpfAppCryptography.ViewModel;
namespace WpfAppCryptography.Algorithms.TechniqueBased.Transposition
{
    public class SimpleColumnarMethodWithMultipleRounds : Algorithm
    {
        public new string AlgorithmName = "Simple Columnar Method With Multiple Rounds";

        public override string Decrypt(string ciphertext, string key)
        {
            string plaintext = null;
            char[] ctca = ciphertext.ToCharArray();
            char[] itca = new char[ctca.Length];
            char[,] cells = new char[10, 5];
            int[][] rounds = new int[4][];
            rounds[0] = new int[] { 4, 1, 0, 3, 2 };
            rounds[1] = new int[] { 0, 4, 3, 1, 2 };
            rounds[2] = new int[] { 1, 4, 2, 3, 0 };
            rounds[3] = new int[] { 2, 0, 3, 1, 4 };

            itca = ctca;

            for (int i = 0; i < 4; i++)
            {
                cells = SetCharactersInCellsVertically(cells, itca.Length, itca, rounds[i]);
                itca = SetItcaFromCellsHorizontally(cells, itca);
            }

            for (int i = 0; i < itca.Length; i++)
            {
                plaintext += itca[i];
            }

            return plaintext;
        }

        public override string Encrypt(string plaintext, string key)
        {
            string ciphertext = null;
            char[] ptca = plaintext.ToCharArray();
            char[] itca = new char[ptca.Length];
            char[,] cells = new char[10, 5];
            int[][] rounds = new int[4][];
            rounds[0] = new int[] { 2, 0, 3, 1, 4 };
            rounds[1] = new int[] { 1, 4, 2, 3, 0 };
            rounds[2] = new int[] { 0, 4, 3, 1, 2 };
            rounds[3] = new int[] { 4, 1, 0, 3, 2 };

            itca = ptca;

            for (int i = 0; i < 4; i++)
            {
                cells = SetCharactersInCellsHorizontally(cells, itca.Length, itca);
                itca = SetItcaFromCellsVertically(cells, itca, rounds[i]);
            }

            for (int i = 0; i < itca.Length; i++)
            {
                ciphertext += itca[i];
            }

            return ciphertext;
        }

        private char[,] SetCharactersInCellsHorizontally(char[,] cells, int length, char[] itca)
        {
            int x = 0, y = 0;

            for (int i = 0; i < itca.Length; i++)
            {
                cells[x, y++] = itca[i];
                if (y == 5)
                {
                    y = 0;
                    ++x;
                }
            }

            return cells;
        }

        private char[] SetItcaFromCellsVertically(char[,] cells, char[] itca, int[] columnorder)
        {
            int k = 0;

            for (int x = 0; x < 5; x++)
            {
                int t = columnorder[x];
                for (int y = 0; cells[y,t] != '\0'; y++)
                {
                    itca[k++] = cells[y, t];
                }
            }

            return itca;
        }

        private char[,] SetCharactersInCellsVertically(char[,] cells, int length, char[] itca, int[] columnorder)
        {
            int k = 0;

            for (int x = 0; x < 5; x++)
            {
                int t = columnorder[x];
                for (int i = 0; ((i*5)+t) < length; i++)
                {
                    cells[i, t] = itca[k++];
                }
            }

            return cells;
        }

        private char[] SetItcaFromCellsHorizontally(char[,] cells, char[] itca)
        {
            int x = 0, y = 0;

            for (int i = 0; i < itca.Length; i++)
            {
                itca[i] = cells[x, y++];
                if (y == 5)
                {
                    y = 0;
                    ++x;
                }
            }

            return itca;
        }
    }
}


Here is the video :



That's the end of it. I hope you find my blogs useful.
See you next time. Till then keep coding.

Practice Page Link :
http://handsoncrypto.azurewebsites.net/PracticePage.aspx

Sunday 10 July 2016

Rail Fence

Hello everyone. In my previous blogs, I have discussed about two different
substitution based cryptographic algorithms. That's not the end of it. There
are more. But I won't be discussing anymore algorithms of substitution
technique. You will get enough information about other algorithms in the
Wikipedia. These blogs are meant to give you the idea of cryptography.
If you face any problem while implementing them, then you can definitely
ping me in my email id.

But for now, let's move on to Transposition Technique. As the name already
suggests, it is the rearrangement of the letters. It does not involve any
replacement of characters, just jumbling of characters.

There are many algorithms which is based on Transposition Technique.
Like Rail Fence technique, Simple columnar transposition, Simple
transposition with multiple rounds, etc.

So, for the simplicity I will start with the Rail Fence algorithm.
In this technique, the characters of the plain text are written in
diagonal form at first. This arrangement forms two rows which
resembles the rail track. That's why it is called as Rail Fence.
After the two rows are produced, the cipher text is read as
row-wise.

For example,

Plain Text : Windows

Arrangement :



Cipher Text : Wnosidw

Here is the C# code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WpfAppCryptography.ViewModel;
namespace WpfAppCryptography.Algorithms.TechniqueBased.Transposition
{
    public class RailFence : Algorithm
    {
        public new string AlgorithmName = "Rail Fence";
        public override string Decrypt(string ciphertext, string key)
        {
            string plaintext = null;
            int j = 0, k = 0, mid;
            char[] ctca = ciphertext.ToCharArray();
            char[,] railarray = new char[2, 100];
            if (ctca.Length % 2 == 0)
                mid = ((ctca.Length) / 2) - 1;
            else
                mid = (ctca.Length) / 2;
            for (int i = 0; i < ctca.Length; ++i)
            {
                if (i <= mid)
                {
                    railarray[0, j] = ctca[i];
                    ++j;
                }
                else
                {
                    railarray[1, k] = ctca[i];
                    ++k;
                }
            }
            railarray[0, j] = '\0';
            railarray[1, k] = '\0';
            for (int x = 0; x <= mid; ++x)
            {
                if (railarray[0, x] != '\0')
                    plaintext += railarray[0, x];
                if (railarray[1, x] != '\0')
                    plaintext += railarray[1, x];
            }
            return plaintext;
        }
        public override string Encrypt(string plaintext, string key)
        {
            string ciphertext = null;
            int j = 0, k = 0;
            char[] ptca = plaintext.ToCharArray();
            char[,] railarray = new char[2, 100];
            for (int i = 0; i < ptca.Length; ++i)
            {
                if(i%2 == 0)
                {
                    railarray[0, j] = ptca[i];
                    ++j;
                }
                else
                {
                    railarray[1, k] = ptca[i];
                    ++k;
                }
            }
            railarray[0, j] = '\0';
            railarray[1, k] = '\0';
            for (int x = 0; x < 2; ++x)
            {
                for (int y = 0; railarray[x, y] != '\0'; ++y)
                    ciphertext += railarray[x, y];
            }
            return ciphertext;
        }
    }
}

Although it looks very simple. But it is highly useful for Encryption process.
You can merge Substitution & Transposition techniques to create your own
cryptographic algorithm.



I hope you find my blogs useful. Stay tuned and keep coding.

Practice Page Link :
http://handsoncrypto.azurewebsites.net/PracticePage.aspx

Thursday 30 June 2016

Mono Alphabetic Cipher

Hello everyone. In my last blog of Cryptography, I demonstrated Caesar Cipher.
In this blog, I will be describing Mono Alphabetic Cipher algorithm.
Mono Alphabetic Cipher is another substitution technique where each character
of the plain text is substituted with another different character. There is
no mathematical relation between the original character and the substituted
character. But whenever a specific character is encountered, it will be always
replaced by the character that is defined in the substitution table. For
example, whenever 'a' is encountered in the plain text, it will always be
replaced by 'q' in the cipher text. The relation between 'a' and 'q' is
random.

The substitution table I have defined here is as follows :
Original Characters :     a b c d e f g h i j k l m n o p q r s t u v w x y z
Substituted Characters: q w e r t y u i o p a s d f g h j k l z x c v b n m

So, accordingly if I write
Plain Text :  h e l l o
Cipher Text: i t s s g

I have done it for only lower case alphabets. But if you want, you can do
it for upper case alphabets as well as digits.
Here is the code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WpfAppCryptography.ViewModel;
namespace WpfAppCryptography.Algorithms.TechniqueBased.Substitution
{
    public class MonoAlphabeticCipher : Algorithm
    {
        public new string AlgorithmName = "Mono Alphabetic Cipher";

        private char[] o = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
        private char[] m = new char[] { 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm' };

        private int GetIndex(char ch, char[] ca)
        {
            int i, result = 0;
            for (i = 0; i < 26; ++i)
            {
                if (ca[i] == ch)
                {
                    result = i;
                    break;
                }
            }
            return result;
        }

        public override string Decrypt(string ciphertext, string key)
        {
            int i, j;
            string plaintext = null;
            char[] ctca = ciphertext.ToCharArray();
            char[] cc = new char[500];
            for (i = 0; i < ctca.Length; ++i)
            {
                if (ctca[i] == ' ')
                {
                    cc[i] = ctca[i];
                }
                else
                {
                    j = GetIndex(ctca[i], m);
                    cc[i] = o[j];
                }
                plaintext += cc[i];
            }
            return plaintext;
        }

        public override string Encrypt(string plaintext, string key)
        {
            int i, j;
            string ciphertext = null;
            char[] ptca = plaintext.ToCharArray();
            char[] cc = new char[500];
            for (i = 0; i < ptca.Length; ++i)
            {
                if (ptca[i] == ' ')
                {
                    cc[i] = ptca[i];
                }
                else
                {
                    j = GetIndex(ptca[i],o);
                    cc[i] = m[j];
                }
                ciphertext += cc[i];
            }
            return ciphertext;
        }
    }
}



I hope you find it useful. Keep Coding.

Practice Page Link :
http://handsoncrypto.azurewebsites.net/PracticePage.aspx

Monday 6 June 2016

Introduction to Cryptography and Caesar Cipher

Hello everyone. In this series I will give you the idea about different Cryptographic Algorithms used for encryption and decryption of messages. I will provide the codes that are written in C#.

First of all, what is Cryptography?
Cryptography is the technique of storing and sending some information, by transforming the original
message into something that can be only read by the intended recipient.

It involves two main processes - Encryption and Decryption.
Encryption - It is the technique of converting the plain text into cipher text (encrypted text) by the
use of some algorithm.
Decryption - It is exactly the reverse of Encryption process, which converts the cipher text to plain
text.

There are basically two approaches :
1. Technique Based
2. Key Based

1. Technique Based can be further divided into two parts :
a) Substitution Techniques
b) Transposition Techniques

2. Key Based can also be divided into two parts :
a) Symmetric Key Cryptography
b) Asymmetric Key Cryptography

And it goes on when go deeper into these topics.

But for the simplicity, I will start with the basic algorithms like Substitution techniques.
From the name itself, it is clear that each character in the plain text is replaced with another.
In this technique, I will give you idea about many algorithms - Caesar Cipher, Modified Caesar Cipher, Mono-alphabetic Cipher, Poly-alphabetic Cipher, Homophonic Cipher and many more.

Here I will start with Caesar Cipher - the simplest of all.
In this algorithm, 3 is added with each character to get the new character. Thereby giving the cipher text. Adding 3 with each character is the Encryption process. Similarly, Decryption is the reverse process i.e. subtracting 3 from each character to get the plain text.

For example :
Plain Text :    h  e  l  l  o
Cipher Text : k  h  o o  r

For simplicity, I have considered only the lower case alphabets. But you can make it more robust by
considering all lower case, upper case alphabets and also digits!!

Here is the code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WpfAppCryptography.Algorithms.TechniqueBased.Substitution
{
    public class CaesarCipher
    {
        public string Encrypt(string plaintext)
        {
            int av, oav, cav, cv;
            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
                {
                    av = ptca[i];
                    oav = av - 97;
                    cav = (oav + 3) % 26;
                    cv = cav + 97;
                    cc[i] = (char)cv;
                }
                ciphertext += cc[i];
            }
            return ciphertext;
        }
        public string Decrypt(string ciphertext)
        {
            int av, oav, cav, cv;
            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
                {
                    av = ctca[i];
                    oav = av - 97;
                    cav = (oav - 3) % 26;
                    cv = cav + 97;
                    cc[i] = (char)cv;
                }
                plaintext += cc[i];
            }
            return plaintext;
        }
    }
}







I hope you find my blog interesting. Keep following me and keep coding.

Practice Page Link :
http://handsoncrypto.azurewebsites.net/PracticePage.aspx