The Wayback Machine - https://web.archive.org/web/20240710011301/https://www.geeksforgeeks.org/substitution-cipher/
Open In App

Substitution Cipher

Last Updated : 10 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Hiding some data is known as encryption. When plain text is encrypted it becomes unreadable and is known as ciphertext. In a Substitution cipher, any character of plain text from the given fixed set of characters is substituted by some other character from the same set depending on a key. For example with a shift of 1, A would be replaced by B, B would become C, and so on. 

Note: Special case of Substitution cipher is known as Caesar cipher where the key is taken as 3.

Mathematical representation

The encryption can be represented using modular arithmetic by first transforming the letters into numbers, according to the scheme, A = 0, B = 1,…, Z = 25. Encryption of a letter by a shift n can be described mathematically as.
 

E_n(x)=(x+n)mod\ 26

(Encryption Phase with shift n) 

D_n(x)=(x-n)mod\ 26

(Decryption Phase with shift n) 

substitution-cipher

Examples: 

Plain Text: I am studying Data Encryption
Key: 4
Output: M eq wxyhCmrk Hexe IrgvCtxmsr

Plain Text: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Key: 4
Output: EFGHIJKLMNOPQRSTUVWXYZabcd

Algorithm for Substitution Cipher: 

Input: 

  • A String of both lower and upper case letters, called PlainText. 
  • An Integer denoting the required key. 

Procedure: 

  • Create a list of all the characters. 
  • Create a dictionary to store the substitution for all characters. 
  • For each character, transform the given character as per the rule, depending on whether we’re encrypting or decrypting the text. 
  • Print the new string generated. 

Below is the implementation.

C++




#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    string all_letrs = "abcdefghijklmnopqrstuvwxyzABCDEFGHI"
                       "JKLMNOPQRSTUVWXYZ";
 
    // create a dictionary to store the substitution for the
    // given alphabet in the plain text based on the key
    map<char, char> dict1;
    int key = 4;
    for (int i = 0; i < all_letrs.length(); i++) {
        dict1[all_letrs[i]]
            = all_letrs[(i + key) % all_letrs.length()];
    }
 
    string plain_txt = "I am studying Data Encryption";
    string cipher_txt;
 
    // loop to generate ciphertext
    for (char& c : plain_txt) {
        if (all_letrs.find(c) != string::npos) {
            cipher_txt += dict1;
        }
        else {
            cipher_txt += c;
        }
    }
 
    cout << "Cipher Text is: " << cipher_txt << endl;
 
    // create a map to store the substitution for the given
    // alphabet in the cipher text based on the key
    map<char, char> dict2;
    for (int i = 0; i < all_letrs.length(); i++) {
        dict2[all_letrs[i]]
            = all_letrs[(i - key) % all_letrs.length()];
    }
 
    string decrypt_txt;
 
    // loop to recover plain text
    for (char& c : cipher_txt) {
        if (all_letrs.find(c) != string::npos) {
            decrypt_txt += dict2;
        }
        else {
            decrypt_txt += c;
        }
    }
 
    cout << "Recovered plain text : " << decrypt_txt
         << endl;
 
    return 0;
}


Java




// Java implementation of Substitution Cipher
import java.io.*;
import java.util.*;
import java.util.HashMap;
import java.util.Map;
 
public class CaesarCipher {
    public static void main(String[] args) {
        String allLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHI" + "JKLMNOPQRSTUVWXYZ";
 
        // create a dictionary to store the substitution for the given alphabet in the plain text based on the key
        Map<Character, Character> dict1 = new HashMap<>();
        int key = 4;
        for (int i = 0; i < allLetters.length(); i++) {
            dict1.put(allLetters.charAt(i),
                    allLetters.charAt((i + key) % allLetters.length()));
        }
 
        String plainText = "I am studying Data Encryption";
        StringBuilder cipherText = new StringBuilder();
 
        // loop to generate ciphertext
        for (char c : plainText.toCharArray()) {
            if (allLetters.indexOf(c) != -1) {
                cipherText.append(dict1.get(c));
            } else {
                cipherText.append(c);
            }
        }
 
        System.out.println("Cipher Text is: " + cipherText);
 
        // create a map to store the substitution for the given alphabet in the cipher text based on the key
        Map<Character, Character> dict2 = new HashMap<>();
        for (int i = 0; i < allLetters.length(); i++) {
            dict2.put(allLetters.charAt(i),
                    allLetters.charAt((i - key + allLetters.length()) % allLetters.length()));
        }
 
        StringBuilder decryptedText = new StringBuilder();
 
        // loop to recover plain text
        for (char c : cipherText.toString().toCharArray()) {
            if (allLetters.indexOf(c) != -1) {
                decryptedText.append(dict2.get(c));
            } else {
                decryptedText.append(c);
            }
        }
 
        System.out.println("Recovered plain text: " + decryptedText);
    }
}


Python3




# Python program to demonstrate
# Substitution Cipher
 
 
import string
 
 
# A list containing all characters
all_letters= string.ascii_letters
  
     
"""
create a dictionary to store the substitution
for the given alphabet in the plain text
based on the key
"""
  
     
dict1 = {}
key = 4
  
for i in range(len(all_letters)):
    dict1[all_letters[i]] = all_letters[(i+key)%len(all_letters)]
  
  
plain_txt= "I am studying Data Encryption"
cipher_txt=[]
  
# loop to generate ciphertext
  
for char in plain_txt:
    if char in all_letters:
        temp = dict1[char]
        cipher_txt.append(temp)
    else:
        temp =char
        cipher_txt.append(temp)
         
cipher_txt= "".join(cipher_txt)
print("Cipher Text is: ",cipher_txt)
  
     
"""
create a dictionary to store the substitution
for the given alphabet in the cipher
text based on the key
"""
  
     
dict2 = {}    
for i in range(len(all_letters)):
    dict2[all_letters[i]] = all_letters[(i-key)%(len(all_letters))]
      
# loop to recover plain text
decrypt_txt = []
 
for char in cipher_txt:
    if char in all_letters:
        temp = dict2[char]
        decrypt_txt.append(temp)
    else:
        temp = char
        decrypt_txt.append(temp)
         
decrypt_txt = "".join(decrypt_txt)
print("Recovered plain text :", decrypt_txt)


C#




using System;
using System.Collections.Generic;
using System.Text;
 
namespace SubstitutionCipher
{
    class Program
    {
        static void Main(string[] args)
        {
            string allLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHI" + "JKLMNOPQRSTUVWXYZ";
 
            // create a dictionary to store the substitution for the given alphabet in the plain text based on the key
            Dictionary<char, char> dict1 = new Dictionary<char, char>();
            int key = 4;
            for (int i = 0; i < allLetters.Length; i++)
            {
                dict1.Add(allLetters[i],
                    allLetters[(i + key) % allLetters.Length]);
            }
 
            string plainText = "I am studying Data Encryption";
            StringBuilder cipherText = new StringBuilder();
 
            // loop to generate ciphertext
            foreach (char c in plainText)
            {
                if (allLetters.IndexOf(c) != -1)
                {
                    cipherText.Append(dict1);
                }
                else
                {
                    cipherText.Append(c);
                }
            }
 
            Console.WriteLine("Cipher Text is: " + cipherText);
 
            // create a dictionary to store the substitution for the given alphabet in the cipher text based on the key
            Dictionary<char, char> dict2 = new Dictionary<char, char>();
            for (int i = 0; i < allLetters.Length; i++)
            {
                dict2.Add(allLetters[i],
                    allLetters[(i - key + allLetters.Length) % allLetters.Length]);
            }
 
            StringBuilder decryptedText = new StringBuilder();
 
            // loop to recover plain text
            foreach (char c in cipherText.ToString())
            {
                if (allLetters.IndexOf(c) != -1)
                {
                    decryptedText.Append(dict2);
                }
                else
                {
                    decryptedText.Append(c);
                }
            }
 
            Console.WriteLine("Recovered plain text: " + decryptedText);
        }
    }
}


Javascript




// JavaScript program to demonstrate
// Substitution Cipher
 
// A string containing all characters
const all_letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
 
/*
Create a map to store the substitution for the given alphabet in the plain text based on the key
*/
const dict1 = {};
const key = 4;
 
for (let i = 0; i < all_letters.length; i++) {
dict1[all_letters[i]] = all_letters[(i + key) % all_letters.length];
}
 
const plain_txt = "I am studying Data Encryption";
let cipher_txt = "";
 
// loop to generate ciphertext
for (let i = 0; i < plain_txt.length; i++) {
const char = plain_txt[i];
if (all_letters.includes(char)) {
const temp = dict1[char];
cipher_txt += temp;
} else {
cipher_txt += char;
}
}
 
console.log("Cipher Text is: ", cipher_txt);
 
/*
Create a map to store the substitution for the given alphabet in the cipher text based on the key
*/
const dict2 = {};
 
for (let i = 0; i < all_letters.length; i++) {
dict2[all_letters[i]] = all_letters[(i - key + all_letters.length) % all_letters.length];
}
 
// loop to recover plain text
let decrypt_txt = "";
 
for (let i = 0; i < cipher_txt.length; i++) {
const char = cipher_txt[i];
if (all_letters.includes(char)) {
const temp = dict2[char];
decrypt_txt += temp;
} else {
decrypt_txt += char;
}
}
 
console.log("Recovered plain text :", decrypt_txt);


Output

Cipher Text is:  M eq wxyhCmrk Hexe IrgvCtxmsr
Recovered plain text : I am studying Data Encryption

 Time Complexity: O(n)
Auxiliary Space: O(n)



Previous Article
Next Article

Similar Reads

Difference between Monoalphabetic Cipher and Polyalphabetic Cipher
1. Monoalphabetic Cipher : A monoalphabetic cipher is any cipher in which the letters of the plain text are mapped to cipher text letters based on a single alphabetic key. Examples of monoalphabetic ciphers would include the Caesar-shift cipher, where each letter is shifted based on a numeric key, and the atbash cipher, where each letter is mapped
2 min read
What is S-Box Substitution?
S-box substitution is a vital process that helps enhance security through nonlinear substitution in symmetric key encryption. S-Box substitution is used to enhance the security of encryption algorithms by introducing non-linearity in the substitution process, which helps bring about concepts such as confusion and diffusion making it harder for atta
6 min read
Latin alphabet cipher
The Latin Alphabet Cipher Encryption Technique is one of the earliest and simplest techniques of encrypting data. It’s simply a type of substitution cipher technique, i.e., each letter of a given text is substituted by its corresponding number as represented in its alphabetical order. For Example, we have given a string as "hello everyone", then it
5 min read
Bifid Cipher in Cryptography
This cipher technique considered more secure compared to other substitution algorithms reason being it breaks the message apart into two separate streams and then recombines them. It is a combination of the Polybius square with the transposition and uses fractionation to achieve diffusion. This encrypting technique invented by Felin Delastelle. It
4 min read
Feistel Cipher
Feistel Cipher model is a structure or a design used to develop many block ciphers such as DES. Feistel cipher may have invertible, non-invertible and self invertible components in its design. Same encryption as well as decryption algorithm is used. A separate key is used for each round. However same round keys are used for encryption as well as de
3 min read
Autokey Cipher | Symmetric Ciphers
Autokey Cipher is a polyalphabetic substitution cipher. It is closely related to the Vigenere cipher but uses a different method of generating the key. It was invented by Blaise de Vigenère in 1586. In general, more secure than the Vigenere cipher. Example-1: Plaintext = "HELLO" Autokey = N Ciphertext = "ULPWZ" Example-2: Plaintext = "GEEKSFORGEEKS
4 min read
Encrypt using XOR Cipher with Repeating Key
Computer Architectures have predefined ASCII values &amp; Binary forms for all printable characters, which allows us to operate bit-wise logic like XOR and most encryption/decryption algorithms depend on. The Key is XOR-operated on the plain text to produce the encrypted text. Only Parameters required to encrypt a plain text using this technique: P
2 min read
Vernam Cipher in Cryptography
Vernam Cipher is a method of encrypting alphabetic text. It is one of the Substitution techniques for converting plain text into cipher text. In this mechanism, we assign a number to each character of the Plain-Text, like (a = 0, b = 1, c = 2, ... z = 25). Method to take key: In the Vernam cipher algorithm, we take a key to encrypt the plain text w
6 min read
XOR Cipher
XOR Encryption is an encryption method used to encrypt data and is hard to crack by brute-force method, i.e generating random encryption keys to match with the correct one. Below is a simple implementation in C++. The concept of implementation is to first define XOR - encryption key and then to perform XOR operation of the characters in the String
5 min read
Rail Fence Cipher - Encryption and Decryption
Given a plain-text message and a numeric key, cipher/de-cipher the given text using Rail Fence algorithm. The rail fence cipher (also called a zigzag cipher) is a form of transposition cipher. It derives its name from the way in which it is encoded. Examples:  EncryptionInput : "GeeksforGeeks "Key = 3Output : GsGsekfrek eoeDecryptionInput : GsGsekf
15 min read
three90RightbarBannerImg