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

Feistel Cipher

Last Updated : 14 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 decryption. 
 

Feistel cipher algorithm

  • Create a list of all the Plain Text characters. 
     
  • Convert the Plain Text to Ascii and then 8-bit binary format. 
     
  • Divide the binary Plain Text string into two halves: left half (L1)and right half (R1) 
     
  • Generate a random binary keys (K1 and K2) of length equal to the half the length of the Plain Text for the two rounds. 
     

First Round of Encryption 

  • a. Generate function f1 using R1 and K1 as follows:
f1= xor(R1, K1)
  • b. Now the new left half(L2) and right half(R2) after round 1 are as follows:
R2= xor(f1, L1)
L2=R1

Second Round of Encryption 

  • a. Generate function f2 using R2 and K2 as follows: 
     
f2= xor(R2, K2)
  • b. Now the new left half(L3) and right half(R3) after round 2 are as follows:
R3= xor(f2, L2)
L3=R2
  • Concatenation of R3 to L3 is the Cipher Text
  • Same algorithm is used for decryption to retrieve the Plain Text from the Cipher Text.

Examples: 

Plain Text is: Hello
Cipher Text:  E1!w(
Retrieved Plain Text is:  b'Hello'

Plain Text is: Geeks
Cipher Text: O;Q
Retrieved Plain Text is:  b'Geeks'

 

Python3




# Python program to demonstrate
# Feistel Cipher Algorithm
 
import binascii
 
# Random bits key generation
def rand_key(p):
     
    import random
    key1 = ""
    p = int(p)
     
    for i in range(p):
         
        temp = random.randint(0,1)
        temp = str(temp)
        key1 = key1 + temp
         
    return(key1)
  
# Function to implement bit exor
def exor(a,b):
     
    temp = ""
     
    for i in range(n):
         
        if (a[i] == b[i]):
            temp += "0"
             
        else:
            temp += "1"
             
    return temp
 
# Defining BinarytoDecimal() function
def BinaryToDecimal(binary):
       
    # Using int function to convert to
    # string   
    string = int(binary, 2)
       
    return string
 
# Feistel Cipher
PT = "Hello"
print("Plain Text is:", PT)
 
# Converting the plain text to
# ASCII
PT_Ascii = [ord(x) for x in PT]
 
# Converting the ASCII to
# 8-bit binary format
PT_Bin = [format(y,'08b') for y in PT_Ascii]
PT_Bin = "".join(PT_Bin)
 
n = int(len(PT_Bin)//2)
L1 = PT_Bin[0:n]
R1 = PT_Bin[n::]
m = len(R1)
  
# Generate Key K1 for the
# first round
K1= rand_key(m)
  
# Generate Key K2 for the
# second round
K2= rand_key(m)
  
# first round of Feistel
f1 = exor(R1,K1)
R2 = exor(f1,L1)
L2 = R1
  
# Second round of Feistel
f2 = exor(R2,K2)
R3 = exor(f2,L2)
L3 = R2
  
# Cipher text
bin_data = L3 + R3
str_data =' '
 
for i in range(0, len(bin_data), 7):
       
    # slicing the bin_data from index range [0, 6]
    # and storing it in temp_data
    temp_data = bin_data[i:i + 7]
        
    # passing temp_data in BinarytoDecimal() function
    # to get decimal value of corresponding temp_data
    decimal_data = BinaryToDecimal(temp_data)
        
    # Decoding the decimal value returned by 
    # BinarytoDecimal() function, using chr() 
    # function which return the string corresponding 
    # character for given ASCII value, and store it 
    # in str_data
    str_data = str_data + chr(decimal_data)
     
print("Cipher Text:", str_data)
 
# Decryption
L4 = L3
R4 = R3
  
f3 = exor(L4,K2)
L5 = exor(R4,f3)
R5 = L4
  
f4 = exor(L5,K1)
L6 = exor(R5,f4)
R6 = L5
PT1 = L6+R6
  
 
PT1 = int(PT1, 2)
RPT = binascii.unhexlify( '%x'% PT1)
print("Retrieved Plain Text is: ", RPT)


Output:

Plain Text is: Hello
Cipher Text:  E1!w(
Retrieved Plain Text is:  b'Hello'

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



Similar Reads

Difference between Monoalphabetic Cipher and Polyalphabetic Cipher
A Monoalphabetic Cipher is a cipher where each letter in the plaintext is always mapped to the same letter in the ciphertext While a Polyalphabetic Cipher is a cipher where each letter in the plaintext can be encrypted to multiple possible letters in the ciphertext, depending on its position and a more complex algorithm. In this article, we will se
3 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
Encrypt using XOR Cipher with Repeating Key
Computer Architectures have predefined ASCII values & 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
Implementation of Affine Cipher
The Affine cipher is a type of monoalphabetic substitution cipher, wherein each letter in an alphabet is mapped to its numeric equivalent, encrypted using a simple mathematical function, and converted back to a letter. The formula used means that each letter encrypts to one other letter, and back again, meaning the cipher is essentially a standard
10 min read
Implementing Atbash Cipher
Definition: Atbash cipher is a substitution cipher with just one specific key where all the letters are reversed that is A to Z and Z to A. It was originally used to encode the Hebrew alphabets but it can be modified to encode any alphabet. Relationship to Affine: Atbash cipher can be thought of as a special case of Affine cipher with both the keys
7 min read
Keyword Cipher
Keyword cipher is a form of monoalphabetic substitution. A keyword is used as the key, and it determines the letter matchings of the cipher alphabet to the plain alphabet. Repeats of letters in the word are removed, then the cipher alphabet is generated with the keyword matching to A, B, C, etc. until the keyword is used up, whereupon the rest of t
15+ min read
Null Cipher
A null cipher, also known as concealment cipher, is an ancient form of encryption where the plaintext is mixed with a large amount of non-cipher material. Today it is regarded as a simple form of steganography, which can be used to hide ciphertext. There are various options of using the Null Cipher. Here we are taking the first letter from each wor
6 min read
Columnar Transposition Cipher
Given a plain-text message and a numeric key, cipher/de-cipher the given text using Columnar Transposition Cipher The Columnar Transposition Cipher is a form of transposition cipher just like Rail Fence Cipher. Columnar Transposition involves writing the plaintext out in rows, and then reading the ciphertext off in columns one by one. Examples: Enc
12 min read
What is Round Cipher?
Round ciphers are also known as block ciphers, and they are a classification of encryption algorithms that work systematically, converting the plaintext into ciphertext. These algorithms work on a limited number of bits at a time and subject them to a set of mathematical processes called rounds which are used to bring about the act of encryption. I
10 min read
What is Cipher?
Ciphers are the most vital components of cryptography, as it is through them that the protection of information is made possible in the ever-growing digital environment. In the present generation, given the technological advancement especially in the field of communication, the aspect of security is critical. Cipher is used in securing financial tr
7 min read
Transposition Cipher Techniques in Cryptography
Transposition Ciphers are an essential part of cryptography that uses systematic shuffling of plain text characters or bits to secure data by altering their positions based on some defined way or algorithm. Moreover, unlike substitutive codes where different letters substitute others, in these, you just shift about original letters hence it does no
5 min read
Caesar Cipher in Cryptography
The Caesar Cipher is one of the simplest and oldest methods of encrypting messages, named after Julius Caesar, who reportedly used it to protect his military communications. This technique involves shifting the letters of the alphabet by a fixed number of places. For example, with a shift of three, the letter 'A' becomes 'D', 'B' becomes 'E', and s
12 min read
What is Monoalphabetic Cipher?
Monoalphabetic Cipher is a part of the substitution technique in which a single cipher alphabet is used per message (mapping is done from plain alphabet to cipher alphabet). Monoalphabetic cipher converts plain text into cipher text and re-convert a cipher text to plain text. Monoalphabetic Cipher eliminates the brute-force techniques for cryptanal
4 min read
Playfair Cipher with Examples
The Playfair cipher was the first practical digraph substitution cipher. The scheme was invented in 1854 by Charles Wheatstone but was named after Lord Playfair who promoted the use of the cipher. In playfair cipher unlike traditional cipher we encrypt a pair of alphabets(digraphs) instead of a single alphabet.It was used for tactical purposes by B
15+ min read
What is Multiplicative Cipher in Cryptography?
A multiplicative cipher is a type of cipher that comes under a monoalphabetic cipher, in which each letter that is present in the plaintext is replaced by a corresponding letter of the ciphertext, according to a fixed multiplication key. In this article, we will learn about the multiplicative cipher and its working for the encryption and decryption
9 min read
Polybius Square Cipher
A Polybius Square is a table that allows someone to convert letters into numbers. To make the encryption little harder, this table can be randomized and shared with the recipient. In order to fit the 26 letters of the alphabet into the 25 cells created by the table, the letters 'i' and 'j' are usually combined into a single cell. Originally there w
5 min read
Substitution Cipher
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 w
6 min read
Autokey Cipher | Symmetric Ciphers
The Autokey Cipher is a method of encrypting messages to keep them secret. It uses a keyword to start the process, but instead of repeating that keyword, it merges letters from the actual message as part of the key. This makes it harder for anyone trying to decode the message without knowing the key. Each letter in the message is shifted based on t
6 min read
Python Tutorial | Learn Python Programming Language
Python Tutorial - Python is one of the most popular programming languages today, known for its simplicity and ease of use. Whether you're just starting with coding or looking to pick up another language, Python is an excellent choice. Its clean and straightforward syntax makes it beginner-friendly, while its powerful libraries and frameworks are pe
13 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether you’re a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow. Here’s a list of Python projects from beginner to advanced leve
10 min read
Top 50+ Python Interview Questions and Answers (Latest 2024)
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify, and many more because of its performance and its powerful libraries. To get into these companies and organizations as a Python developer, you need to master some important Python Interview Questions to crack their Python O
15+ min read
Defaultdict in Python
Python Defaultdict is a container-like dictionaries present in the module collections. It is a sub-class of the dictionary class that returns a dictionary-like object. The functionality of both dictionaries and defaultdict is almost the same except for the fact that defaultdict never raises a KeyError. It provides a default value for the key that d
5 min read
How to Install PIP on Windows ?
PIP is a powerful package management system used to install and manage software packages and libraries written in Python. PIP stands for "Preferred Installer Program" or "Pip Installs Packages." To use PIP, you must install Python on your Windows machine. This article provides a step-by-step guide on how to install and configure PIP on Windows, alo
5 min read
f-strings in Python
Python offers a powerful feature called f-strings (formatted string literals) to simplify string formatting and interpolation. f-strings is introduced in Python 3.6 it provides a concise and intuitive way to embed expressions and variables directly into strings. The idea behind f-strings is to make string interpolation simpler. How to use f-strings
5 min read
Python map() function
The map() function is used to apply a given function to every item of an iterable, such as a list or tuple, and returns a map object (which is an iterator). Let's start with a simple example of using map() to convert a list of strings into a list of integers. [GFGTABS] Python s = ['1', '2', '3', '4'] res = map(int, s
4 min read
Enumerate() in Python
Often, when dealing with iterators, we also need to keep a count of iterations. Python eases the programmers' task by providing a built-in function enumerate() for this task. The enumerate () function adds a counter to an iterable and returns it in the form of an enumerating object. This enumerated object can then be used directly for loops or conv
5 min read
three90RightbarBannerImg