Click here to Skip to main content
Licence CPOL
First Posted 5 Mar 2010
Views 24,314
Downloads 3,529
Bookmarked 53 times

Classical Encryption Techniques

By | 5 Mar 2010 | Article
Implementation of famous Ciphering algorithms
img_Demo.JPG

Introduction

Basic Encryption algorithms and their implementation in C# 

Overview

The two basic building blocks of all encryption techniques are:

Substitution      

•          Letters of plain text are replaced by other letters or by numbers or symbols

•          If the plain text is viewed as a sequence of bits, then substitution involves replacing plain text bit patterns with cipher text bit patterns

Transposition/Permutation 

•          The letters/bytes/bits of the plaintext are rearranged without altering the actual letters used

•          can be easily recognised  since the ciphertext have the same frequency distribution as the original plain text. 

Substitution Algorithms

Caesar Cipher  

Earliest known substitution cipher by Julius Caesar

It involves replacing  each letter in the plaintext by a shifted letter in the alphabet used.

Example: If the shift value is (3) then we can define transformation as: 

img_ceaser_1.png

so the message "meet me after the toga party" becomes:  

PHHW PH DIWHU WKH WRJD SDUWB

Mathematical Model 

mathematically give each letter a number:   

img_ceaser_3.png

then the Caesar cipher  is expressed as:

 

C = E(p) = (p + k) mod (26)

     p = D(C) = (C – k) mod (26)     

private string Ceaser(string strText, Mode mode)
        {
            int nKey = Convert.ToInt32(nm_Key.Value);
            int nchar_position, nRes;
            string strReturn = "";
            for (int i = 0; i < strText.Length; i++)
            {
                nchar_position = m_DicAlphabetSorted[strText[i]];
                nRes = GetAlphabetPosition(nchar_position, nKey, mode);
                strReturn += m_DicAlphabetSorted.Keys.ElementAt(nRes % 26);
            }
            return strReturn;
        }
		

Cryptanalysis 

Can try each of the keys (shifts) in turn, until we recognize the original message,   Therefore using a Brute Force Attack we can have only 26 trials !! 

Example:  

breaking cipher text "GCUA VQ DTGCM” is: “ easy to break", with a shift of 2  

Mono-alphabetic Cipher 

Each plaintext letter maps to a different random cipher text letter ,  Hence the key size is 26 letters long   

Example: 

Key: 

img_mono_1.png

Plain text: ifwewishtoreplaceletters

Cipher text: WIRFRWAJUHYFTSDVFSFUUFYA

Cryptanalysis

Now the Brute Force attack to this cipher requires exhaustive search of a total of 26! = 4 x 1026 keys, but the cryptanalysis makes use of the language characteristics, the Letter that is commonly used in English is the letter e , then T,R,N,I,O,A,S other letters are fairly rare Z,J,K,Q,X There are tables of single, double & triple letter frequencies:

img_mono_2.png
for (int i = 0; i < strPlainText.Length; i++)
                    {
                        nchar_position = m_DicAlphabetSorted[strPlainText[i]];
                        strCypher += m_DicAlphabetRandom[nchar_position];
                    }
		

Playfair Cipher  

One approach to improving security was to encrypt multiple letters, Playfair Key Matrix: A 5X5 matrix of letters based on a keyword Fill in letters of keyword (sans duplicates),  Fill rest of matrix with other letters.

Example: Using "playfair example" as the key, the table becomes:

  • Plaintext encrypted two letters at a time  
  • If a pair is a repeated letter, insert a filler like 'X', ex: “Communication" encrypts as “Com x munication
  • If the letters appear on the same row of your table, replace them with the letters to their immediate right respectively (wrapping around to the left side of the row if a letter in the original pair was on the right side of the row).
XM becomes MI 

  • If the letters appear on the same column of your table, replace them with the letters immediately below respectively (again wrapping around to the top side of the column if a letter in the original pair was on the bottom side of the column).
 NU becomes UL 

  • If the letters are not on the same row or column, replace them with the letters on the same row respectively but at the other pair of corners of the rectangle defined by the original pair. The order is important – the first letter of the encrypted pair is the one that lies on the same row as the first letter of the plaintext pair.
TH becomes  ZB 
  • To decrypt, use the INVERSE (opposite) of the last 3 rules, and the 1st as is (dropping any extra "X"s that don't make sense in the final message when you finish).

Encrypting the message "Hide the gold in the tree stump": 

Cipher Text: BM OD ZB XD NA BE KU DM UI XM MO UV IF 

  • The Playfair cipher is a great advance over simple monoalphabetic ciphers,due to:
  • The identification of digrams is more difficult than individual letters: 

i) In the Monoalphabetic cipher, the attacker searches in 26 letters only.

ii) But using the Playfair cipher, the attacker is searching in 26 x 26 = 676 digrams.

  • The relative frequencies of individual letters exhibit a much greater range than that of digrams, making frequency analysis much more difficult. 
  • private string PlayFair(string strText, Mode enumMode)
            {
                List<char> lstKey = new List<char>();
    
                //Key:Charcater
                //Value:Position
                Dictionary<char, string> dicCharacter_positions_in_Matrix = new Dictionary<char, string>();
    
                //Key:Position
                //Value:Charcater
                Dictionary<string, char> dicPosition_Character_in_Matrix = new Dictionary<string, char>();
    
    
                foreach (char c in txt_Key.Text.ToLower().Trim())//get key..remove duplicates
                {
                    if (!lstKey.Contains(c) && c != ' ')
                        lstKey.Add(c);
                }
                FillMatrix(lstKey, ref dicCharacter_positions_in_Matrix, ref dicPosition_Character_in_Matrix);
                strText = RepairWord(strText);
                ////////////////////////////////////////////////
                string strReturn = "";
                for (int i = 0; i < strText.Length; i += 2)
                {
                    string strSubstring_of_2 = strText.Substring(i, 2);//get characters from text by pairs
                    //get Row & Column of each character
                    string strR_C_1 = dicCharacter_positions_in_Matrix[strSubstring_of_2[0]];
                    string strR_C_2 = dicCharacter_positions_in_Matrix[strSubstring_of_2[1]];
    
                    if (strR_C_1[0] == strR_C_2[0])//Same Row, different Column
                    {
                        int nNew_C1 = 0, nNew_C2 = 0;
                        switch (enumMode)
                        {
                            case Mode.Encrypt://Increment Columns
                                nNew_C1 = (int.Parse(strR_C_1[1].ToString()) + 1) % 5;
                                nNew_C2 = (int.Parse(strR_C_2[1].ToString()) + 1) % 5;
                                break;
                            case Mode.Decrypt://Decrement Columns
                                nNew_C1 = (int.Parse(strR_C_1[1].ToString()) - 1) % 5;
                                nNew_C2 = (int.Parse(strR_C_2[1].ToString()) - 1) % 5;
                                break;
                        }
                        nNew_C1 = RepairNegative(nNew_C1);
                        nNew_C2 = RepairNegative(nNew_C2);
                        strReturn += dicPosition_Character_in_Matrix[strR_C_1[0].ToString() + nNew_C1.ToString()];
                        strReturn += dicPosition_Character_in_Matrix[strR_C_2[0].ToString() + nNew_C2.ToString()];
                    }
    
                    else if (strR_C_1[1] == strR_C_2[1])//Same Column, different Row
                    {
                        int nNew_R1 = 0, nNew_R2 = 0;
    
                        switch (enumMode)
                        {
                            case Mode.Encrypt://Increment Rows
                                nNew_R1 = (int.Parse(strR_C_1[0].ToString()) + 1) % 5;
                                nNew_R2 = (int.Parse(strR_C_2[0].ToString()) + 1) % 5;
                                break;
                            case Mode.Decrypt://Decrement Rows
                                nNew_R1 = (int.Parse(strR_C_1[0].ToString()) - 1) % 5;
                                nNew_R2 = (int.Parse(strR_C_2[0].ToString()) - 1) % 5;
                                break;
                        }
                        nNew_R1 = RepairNegative(nNew_R1);
                        nNew_R2 = RepairNegative(nNew_R2);
                        strReturn += dicPosition_Character_in_Matrix[nNew_R1.ToString() + strR_C_1[1].ToString()];
                        strReturn += dicPosition_Character_in_Matrix[nNew_R2.ToString() + strR_C_2[1].ToString()];
                    }
    
                    else//different Row & Column
                    {
                        //1st character:row of 1st + col of 2nd
                        //2nd character:row of 2nd + col of 1st
                        strReturn += dicPosition_Character_in_Matrix[strR_C_1[0].ToString() + strR_C_2[1].ToString()];
                        strReturn += dicPosition_Character_in_Matrix[strR_C_2[0].ToString() + strR_C_1[1].ToString()];
                    }
                }
                return strReturn;
            }
    		 

Hill Cipher 

Each letter is first encoded as a number. Often the simplest scheme is used: A = 0, B =1, ..., Z=25, but this is not an essential feature of the cipher. The encryption takes m successive plaintext letter and substitutes them for m ciphertext letters. In case m = 3 , the encryption can be expressed in terms of the matrix multiplication as follows:

img_Hill_1.png

Mathematical Model: 

C = EK (P) = KP mod 26

P = DK (C ) = K-1 C mod 26 = K-1 KP = P
K is the key matrix and K-1 is the matrix inverse.
The inverse matrix can be calculated as K.K-1 = I where I is the identity matrix. 

Encryption example: Plaintext: “paymoremoney

Key:

img_Hill_2.pngimg_Hill_3.png

Cipher text :LNSHDLEWMTRW 

Decryption example 

For decryption use the inverse key matrix P = C mod 26

img_Hill_4.pngimg_Hill_5.png
private string Hill(string strText, Mode mode)
        {
            MatrixClass m = new MatrixClass(m_frmMatrix.m_arrMatrix);
            if (mode == Mode.Decrypt)
                m = m.Inverse();
            int npos = 0, nchar_position;
            string strSubstring, strReturn = "";
            while (npos < strText.Length)
            {
                strSubstring = strText.Substring(npos, (int)nm_Key.Value);
                npos += (int)nm_Key.Value;

                for (int i = 0; i < nm_Key.Value; i++)
                {
                    nchar_position = 0;
                    for (int j = 0; j < nm_Key.Value; j++)
                    {
                        nchar_position += (int)m[j, i].Numerator * m_DicAlphabetSorted[strSubstring[j]];
                    }
                    strReturn += m_DicAlphabetSorted.Keys.ElementAt(nchar_position % 26);
                }
            }
            return strReturn;
        }
		  

Polyalphabetic Ciphers 

Another approach to improving security is to use multiple cipher alphabets Called polyalphabetic substitution ciphers. Makes cryptanalysis harder with more alphabets to guess and flatter frequency distribution.

Use a key to select which alphabet is used for each letter of the message.

Example: the Vigenère Cipher: 

  1. Write the plain text 
  2. Write the keyword repeated below it 
  3. Use each key letter as a caesar cipher key
  4. Encrypt the corresponding plaintext letter.

img_vigener_1.png

Decryption works in the opposite way

Cryptanalysis:

The problem in repeating the key so frequently, is that there might be repetitions in the ciphertext. This helps in the cryptanalysis process as it gives a clue on the key period.

img_vigener_2.png

 

Ideally we want a key as long as the message, this is done in  Autokey Cipher.

Autokey Cipher  

Vigenère proposed the autokey cipher to strengthen his cipher system. With keyword is prefixed to message as key But still have frequency characteristics to attack.

key: deceptivewearediscoveredsav

plaintext: wearediscoveredsaveyourself 

ciphertext: ZICVTWQNGKZEIIGASXSTSLVVWLA 

notice how we completed the key with characters from plain text. 

One-Time Pad 

is a system that uses a truly random key as long as the message in the decryption and encryption processes. It is unbreakable since ciphertext bears no statistical relationship to the plaintext since for any plaintext & any ciphertext there exists a key mapping one to other.

This system is practically infeasible since its impractical to generate large quantities of random keys. The key distribution and protection is a big problem in this case. 

Transposition Ciphers   

Rail Fence cipher  

Write the message letters out diagonally over a number of rows then read off cipher row by row. 

Example: Encrypting the following message using rail fence of depth 2:

Meet me after the Graduation party” 

Write message out as: 

m e m a t r h g a u t o p r y

e t e f e t e r d a i n a t 

Cipher text: MEMATRHGAUTOPRY ETEFETERDAINAT 

private string RailFence(string strText, Mode mode)
        {
            int nRows = Convert.ToInt32(nm_Key.Value);
            int nColumns = (int)Math.Ceiling((double)strText.Length / (double)nRows);
            char[,] arrResult = FillArray(strText, nRows, nColumns, mode);
            string strReturn = "";
            foreach (char c in arrResult)
            {
                strReturn += c;
            }
            return strReturn;
        } 

Row Transposition  

A more complex scheme. Write letters of message out in rows over a specified number of columns. Then reorder the columns according to some key before reading off the rows.

Ex:using key 4,3,1,2,5,6,7  and plain text "attack postponed until two am

7  
t  

cipher text:  TTNA APTM TSUO AODW COI* KNL* PET* 

int nColumns = 0, nRows = 0;
                        Dictionary<int,> dicRows_Positions = FillPositionsDictionary(strPlainText.Length, ref nColumns, ref nRows);
                        char[,] Matrix_2 = new char[nRows, nColumns];

                        //Fill Matrix
                        for (int i = 0; i < nRows; i++)
                        {
                            for (int j = 0; j < nColumns; j++)
                            {
                                if (nchar_position < strPlainText.Length)
                                    Matrix_2[i, j] = strPlainText[nchar_position];
                                else
                                    Matrix_2[i, j] = '*';
                                nchar_position++;
                            }
                        }

                        for (int i = 0; i < nColumns; i++)
                        {
                            for (int j = 0; j < nRows; j++)
                            {
                                strCypher += Matrix_2[j, dicRows_Positions[i + 1]];
                            }
                            strCypher += " ";
                        }</int,>

Product Ciphers  

Ciphers using substitutions or transpositions are not secure because of language characteristics. Hence consider using several ciphers in succession to make cryptanalysis harder, two substitutions make a more complex substitution,  two transpositions make more complex transposition but a substitution followed by a transposition makes a new much harder cipher. 


This is a bridge from classical to modern ciphers 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Omar Gamil

Software Developer

Egypt Egypt

Member

Enthusiastic programmer/researcher, passionate to learn new technologies, interested in problem solving,data structures, algorithms and automation.
 
If you have a question\suggestion about one of my articles, or you want an algorithm implemented in C#, feel free to contact me.
 
Résumé
vWorker Account

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 4 PinmemberCurrentlyBE2:59 21 Dec '11  
GeneralMy vote of 5 PinmemberFilip D'haene5:32 8 Jun '11  
GeneralMy vote of 5 Pinmembersyaifur rizal1:01 7 Jun '11  
GeneralExcellent Article - Well Explained and Helpful PinmemberCurt C3:13 8 Mar '11  
GeneralMy vote of 5 Pinmemberdiegocamargocasas9:05 10 Feb '11  
GeneralGood day.:) Pinmemberjojojumari16:04 3 Dec '10  
GeneralRe: Good day.:) PinmemberOmar Gamil22:51 4 Dec '10  
Generalmy vote 5 PinmemberShashankSinghThakur8:36 28 Oct '10  
GeneralMy vote of 5 Pinmemberlamar coster0:06 22 Jul '10  
GeneralThanks Pinmemberaseil12:04 20 Mar '10  
GeneralComparing your work to the C# open source project "CrypTool 2" PinmemberMember 18954618:58 9 Mar '10  
GeneralOutstanding PinmvpPete O'Hanlon10:30 6 Mar '10  
Generalmy vote of 5 PinmemberRozis11:12 5 Mar '10  
GeneralVery nice, thanks Pinmembervalex1239:38 5 Mar '10  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 5 Mar 2010
Article Copyright 2010 by Omar Gamil
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid