Cryptography – One−Time Pad Cipher ”; Previous Next The One−Time Pad algorithm is the enhanced version of Vernam Cipher. It is the only known encryption method that is unbreakable, offering complete security. This algorithm encrypts alphabetic text using the substitution technique, assigning numbers to each character in the plaintext. To use the One−Time Pad effectively, three conditions must be met: The length of the encryption key matches the length of the secret message. The encryption key consists solely of symbols generated randomly. Each encryption key is employed only once and never reused for multiple messages. In One−Time Pad Encryption system, every message is scrambled using a unique key that is just as long as the message. The encrypted message (known as ciphertext) seems like complete random and has no resemblance to the original message (called plaintext). This makes it very hard to decipher without the correct key. How One−Time Pad Work? One−time pads involve creating a sequence of characters or numbers equal to or longer than the expected longest message. This sequence is generated randomly, often using computer programs with random number generators. These values are physically recorded on a pad or readable device. Pads are distributed to individuals who may exchange sensitive messages. They can be distributed as multiple keys, with a specific key assigned to each day or a specific number of uses, ensuring that each key is used only once and then discarded. When sending a message, the sender encrypts it character by character using a secret key. Using a computer, each bit in a character (typically eight bits) is combined with the corresponding bit in the key using the XOR operation. In a one-time pad system, XOR is the encryption method. If the key”s randomness is uncertain, it can be combined with algorithms like MD5. This type of encryption is like adding a random noise to the message, and only the sender and receiver have the means to remove the noise. One−Time pads are used only once and must not be reused. Reusing a pad allows an interceptor to compare messages and potentially decipher them. To show how a one-time pad works, consider the message “TEST”. A secret key “FVEB” of equal length is generated. Each letter is assigned a number, TEST: 19, 4, 18, 19 and FVEB: 5, 21, 4, 1. Adding the numbers corresponding to plaintext and secret key: 24, 25, 22, 20. Converting these numbers back to letters: Encrypted message: YZWU To decrypt, simply reverse the process, revealing the original message “TEST”. Why is the One−Time Pad Unbreakable? Unbreakable Nature of the One−Time Pad (OTP) is believed to be uncrackable because, unlike the Vigenere cipher that can be broken through pattern analysis, the OTP key is as long as the message itself. Every possible encrypted symbol has an equal chance of representing the same original symbol, making frequency analysis ineffective in uncovering the correct message. The key used is entirely random and matches the message length, eliminating any predictable patterns for hackers to exploit. The key is discarded after each message is exchanged. Without it, even the sender and receiver cannot decipher the message. Because the key is random and used only once, it leaves no hints or patterns that hackers can guess to break the code. Encryption of One−Time Pad Imagine User1 wants to send a private message to User2. User1 writes down “HELLO” and creates a unique key, “QWERT.” − To keep the message secret, User1 matches each letter of “HELLO” with the corresponding letter in “QWERT.” For example, H = A + Q, E = B + W. User1”s encrypted message becomes “QGNNQ.” User2 receives the encrypted message and uses the same “QWERT” key to decode it. He reverses the rule: H – A = Q, E – W = G. User2 recovers the original message, “HELLO.” As the key is used only once and is completely unpredictable, anyone who intercepts the encrypted message cannot decipher it without having the key. That”s why the One−Time Pad is considered unbreakable. Decryption of One−Time Pad To decrypt the message using one time pad follow the below steps − Gather the encrypted message and the encryption key. Reverse the operations performed during encryption: – If letters were added, subtract them. Apply the reversed operations to each letter using the decryption key. Obtain the original, decrypted message by reversing all transformations. Example To decrypt “QKRRU” using the key “WORLD”: – Subtract “W” from “Q” to get “H”. – Subtract “O” from “K” to get “E”. – Continue this process for all letters. – The resulting message, “HELLO”, is the decrypted plaintext. Advantages Below are some advantages of One time Pad cipher we should consider while working with this cipher − One-time pad encryption offers the strongest possible protection by using a key that is kept confidential and only utilized once. Unlike other encryption techniques, it is immune to weaknesses like brute-force or known-plaintext attacks. One-time pad encryption adapts easily to both textual and binary data. Its implementation is straightforward, allowing it to be executed manually or with the support of a computer. Use Cases for OTP See the use cases of One−Time cipher below − Critical Communication − Essential communication for military and government operations requiring the utmost security. Diplomatic Confidentiality − Secure communication among top officials, diplomats, and intelligence agencies. Business Secrecy − Protection of sensitive financial and business information from competitors. Personal Privacy − Securing private and confidential information, including medical records and legal documents. Drawback While the OTP offers unbreakable security when used correctly, its practical limitations and challenges in key management and distribution make it less suitable for many real-world applications compared to other encryption methods. Summary The One−Time Pad Cipher provides high security by using unique keys for each message, making it very impossible for unauthorized parties to decrypt encrypted data without the relevant key. The encryption and decryption process can be implemented with the help of various methods like modulo operation, addition and subtraction,
Category: cryptography
Cryptography – RSA Encryption ”; Previous Next As we have seen in the previous chapters RSA (Rivest−Shamir−Adleman) is a popular encryption method that protects data shared online. It relies on the mathematical features of very large prime numbers. How RSA Encryption Works? RSA encryption secures data by encoding it in a way that only authorized parties can decipher. Below is a brief overview of how RSA encryption works − Key Generation Start with two large prime numbers, such as p and q. Multiply p and q to get n. Find Φ(n), which is calculated as (p-1) * (q-1). Φ represents Euler”s totient function. Choose an integer e that falls between 1 and Φ(n) and has no common factors with Φ(n) except 1 (they are coprime). Find d, the multiplicative inverse of e modulo Φ(n). This means that when e and d are multiplied, the result is 1 remainder Φ(n), denoted as d * e ≡ 1 (mod Φ(n)). Encryption To encrypt a message, it is first converted into numbers, usually using a pre-defined code like ASCII or Unicode. Each chunk of the message is then encrypted on its own using the public key. Encryption involves raising the numerical form of the message chunk to the power of e and dividing the result by n, taking the remainder. The resulting encrypted message (ciphertext) is a string of numbers that cannot be read and can be sent over insecure channels. Implementation of RSA using Python RSA Encryption can be implemented using different methods like − Using the random module Using the RSA module Using the cryptography module Hence, in the next few sections, we will detail each way in depth to provide you with an idea on how to create RSA encryption and a better understanding of Python. Using the random Module This program will use a random module of Python to create random numbers for key generation. In our code we will have generate_keypair() and encrypt(public_key, plaintext) methods. When the generate_keypair() method is called, it generates random prime numbers p and q. Thus, the random module is required for generating random prime integers p and q, as well as calculating a random public exponent e. These random values are important for the security and randomness of the RSA encryption technique. Example Following is a python program to for RSA encryption using random module of Python − import random def gcd(a, b): while b != 0: a, b = b, a % b return a def extended_gcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = extended_gcd(b % a, a) return (g, x – (b // a) * y, y) def mod_inverse(a, m): g, x, y = extended_gcd(a, m) if g != 1: raise Exception(”Modular inverse does not exist”) else: return x % m def generate_keypair(): p = random.randint(100, 1000) q = random.randint(100, 1000) n = p * q phi = (p – 1) * (q – 1) while True: e = random.randint(2, phi – 1) if gcd(e, phi) == 1: break d = mod_inverse(e, phi) return ((e, n), (d, n)) def encrypt(public_key, plaintext): e, n = public_key cipher = [pow(ord(char), e, n) for char in plaintext] return cipher # our public and private keys public_key, private_key = generate_keypair() # Our secret message message = “Hello, world!” print(“Our plaintext message: “, message) encrypted_message = encrypt(public_key, message) print(“Encrypted message:”, encrypted_message) Following is the output of the above example − Input/Output Our plaintext message: Hello, world! Encrypted message: [5133, 206, 9012, 9012, 7041, 3509, 7193, 3479, 7041, 6939, 9012, 1255, 3267] Using the rsa module RSA cryptography can be easily and efficiently implemented using Python”s rsa package. Installing the rsa Module First, if you do not have already installed the rsa module then you can install it with the help of pip − pip install rsa Generating RSA Keys After installing the module you can generate RSA key pairs with the help of this rsa module. Here is how − import rsa # create a key pair with 1024 bits key length (public_key, private_key) = rsa.newkeys(1024) The above code will generate a pair of RSA keys: one for encryption (the public key) and the second one for decryption (the private key). Encrypting the Messages When you have the key pair, you can use them to encrypt and decrypt messages. # Encrypting a message message = b”Hello, world!” encrypted_message = rsa.encrypt(message, public_key) # Decrypting the message decrypted_message = rsa.decrypt(encrypted_message, private_key) print(“Original message:”, message.decode()) print(“Decrypted message:”, decrypted_message.decode()) Sign and Verify RSA can also be used for digital signatures. Here is how to sign and verify a given message − # Signing a message signature = rsa.sign(message, private_key, ”SHA-256”) # Verifying the signature rsa.verify(message, signature, public_key) Complete code Below is the complete code for your reference. So run the code and see the output − import rsa # create a key pair with 1024 bits key length (public_key, private_key) = rsa.newkeys(1024) # Encrypting a message message = b”Hello, world!” encrypted_message = rsa.encrypt(message, public_key) print(“Original message:”, message.decode()) print(“Encrypted message:”, encrypted_message) # Signing a message signature = rsa.sign(message, private_key, ”SHA-256”) # Verifying the signature rsa.verify(message, signature, public_key) Following is the output of the above example − Input/Output Original message: Hello, world! Encrypted message: b”gx078$xx,5A[x11hrx15v4x0f-?xa8x18xadxdax93xa8x982x1bxf3xaeexd3x85+MZ*=xd0x8fxefVxed5ixc9Axe4xa377x1dxcexf0xb6xa9/:xf8Yxf9xf1x866x8dx1c!xb9Jxf1x9dQ8qdx01tkxd61Ux8c2x81x05wpxcb)g6txe9x03xa0MQRxcbxa6Bhbx05xb5x06fx04rx17x9cxe8B%]x95xd8Dx84Xrx9cx93xc8xaeN[m” Using the Cryptography Module So we can generate RSA key pairs using the cryptography module. This code generates a private RSA key and extracts the matching public key. Both keys are converted to the PEM format and stored in separate files. These keys can be used to encrypt and decrypt messages.The provided code demonstrates encryption using the public key. Example Following is a python implementation for RSA encryption using cryptography module − from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import rsa # Generate an RSA private key private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend() ) # Get the public key from the private key public_key = private_key.public_key() # The keys to PEM format private_key_pem
Cryptography – Multiplicative Cipher ”; Previous Next In this chapter we will deep dive into the Multiplicative Cipher Algorithm and how it works! So let”s see it in the sections below. A multiplicative cipher belongs to the category of monoalphabetic ciphers. In a multiplicative cipher, every letter in the plaintext is substituted with a matching letter from the ciphertext based on a predetermined multiplication key. The main idea behind the multiplicative cipher is to encode and decode the plaintext using the modular arithmetic of the integers modulo, a large prime number used as a multiplication key. Each letter”s numerical value in the plaintext is multiplied by the key all over the encryption process, and the result is then calculated modulo the key. For example, if the plaintext letter is “s” and the key is 7, then the ciphertext letter is (18*7) mod 26 = 22 since the numerical value of “s” is 18. So, in this case, the cipher text symbol for the letter “a” will be “w.” Decryption is just the encryption process done backwards: each letter in the ciphertext is given a numerical value, which is divided by the key, and the result is then taken modulo the key. The multiplicative cipher”s simplicity−that is, its ease of implementation, understanding, and low processing power requirements−is one of its primary benefits. But this method is easy to use and understand, it is not very secure. It is similar to a secret code that is simple for someone else to decipher. For small things, it is suitable, but not for important things that require strong protection. How does Multiplicative Cipher work? Your secret key is a big prime number that you choose. You then modify each letter in your message using mathematical operations. For example, if your key is 7 and your message has the letter ”s”, which is number 18, you do (18 times 7) divided by 26 and take the remainder. This gives you 22, which corresponds to the letter ”w”. So, ”s” becomes ”w” in the secret message. All you have to do is reverse the math to read the secret message. You can divide each letter”s number with the key and get the remainder. If multiplication is used to convert to cipher text, it is called a wrap-around situation. Consider the letters and the associated numbers to be used as shown below − The numbers are what will be multiplied, and the corresponding key is 7. To create a multiplicative cipher in such a situation, the fundamental formula is as follows − Now use the above formula to convert “hello” in cipher text using a key, K. Let us assume our key, K is 3. Here is how we will apply the given formula to each letter in the word “hello” − For ”h”: P (plaintext value of ”h”) = 7 (assuming ”a” is 0, ”b” is 1, …, ”h” is 7) Cipher = (7 + 3) Mod 26 = 10 Mod 26 = 10 For ”e”: P (plaintext value of ”e”) = 4 Cipher = (4 + 3) Mod 26 = 7 Mod 26 = 7 For ”l”: P (plaintext value of ”l”) = 11 Cipher = (11 + 3) Mod 26 = 14 Mod 26 = 14 For ”l”: P (plaintext value of ”l”) = 11 Cipher = (11 + 3) Mod 26 = 14 Mod 26 = 14 For ”o”: P (plaintext value of ”o”) = 14 Cipher = (14 + 3) Mod 26 = 17 Mod 26 = 17 So values regarding the numbers 10, 7, 14, 14, 17 are k, h, o, o, r respectively. So, the ciphertext for “hello” with a key of 3 will be “khoor”. Algorithms for Multiplicative Cipher Encryption Algorithm First you need to choose a prime number as the encryption key. Assign numerical values to each letter in the plaintext message. Multiply each numerical value by the encryption key. Take the result modulo 26 which is the number of letters in the English alphabet to make sure that the result should stay within the range of the alphabet. Convert the resulting numerical values back to letters to get the ciphertext message. Decryption Algorithm Choose the same prime number as the decryption key. Assign numerical values to each letter in the ciphertext message. Divide each numerical value by the decryption key. Take the result modulo 26. Convert the resulting numerical values back to letters to get the original plaintext message. Implementation using Python So we can implement this algorithm in different ways − Using Basic Arithmetics In this example we are going to use basic arithmetic operations for encryption and decryption in the multiplicative cipher. So in the encryption process we will convert the plaintext message to numbers (0-25) using ASCII values. Each number will be multiplied by the encryption key. So the result will be taken modulo 26 to ensure it falls within the range of the alphabet (0-25). And then we will convert the numbers back to characters using ASCII values. In the decryption process we will convert the ciphertext message to numbers (0-25) using ASCII values. Each number is multiplied by the modular multiplicative inverse of the encryption key. The result is then taken modulo 26. And then resulting numbers are converted back to characters using ASCII values. Example Below is a simple Python code for the multiplicative cipher algorithm. See the program below − def multiplicative_encrypt(message, key): cipher_text = ”” for char in message: if char.isalpha(): # Change char to number (0-25) num = ord(char.lower()) – ord(”a”) # Encrypt with the help of (P * K) % 26 encrypted_num = (num * key) % 26 # change back to character cipher_text += chr(encrypted_num + ord(”a”)) else: cipher_text += char return cipher_text def multiplicative_decrypt(ciphertext, key): plain_text = ”” # get the modular multiplicative inverse of the key inverse_key = pow(key, -1, 26) for char in ciphertext: if char.isalpha(): # change char to number (0-25) num = ord(char.lower()) – ord(”a”) # Decrypt
Cryptography – CAST5 Encryption Algorithm ”; Previous Next A general process for creating a family of block ciphers is called CAST. Names for individual ciphers include CAST-128 and CAST-256. The CAST cryptography algorithm is the main topic of discussion in this chapter. What is CAST Ecnryption Algorithm? Usually used for IP security, the CAST method refers to the Fiestal structure, which divides plain text into equal portions and performs encryption. Instead of using DES”s 6*4 S-boxes, they use larger 8*32 S-boxes. They are made to be used with software. Bent functions are used as columns in the CAST S-boxes. S-boxes satisfy the avalanche requirement, which states that each bit of input and each bit of round key effects every bit of round output and increases the probability of every given output bit changing by exactly 50%. What is CAST5? The most popular CAST cipher is CAST-128, also referred to as CAST5. It is a symmetric key block cipher that is the default cipher for both GPG and PGF versions and is utilised in a variety of products. The developers of it, make it accessible for both commercial and non-commercial use globally at no cost to users. The CAST5 encryption technique is made to support key sizes ranging from 40 to 128 bits, in increments of 8 bits. This means that the key sizes that can be used are 40, 48, 56, 64,…, 112, 120, and 128 bits. It is a Feistel Cipher with 16 rounds and 64-bit blocks. The range of key sizes is 40 bits to 128 bits. Eight 8*32 S-boxes are present. Among these eight boxes, four are utilised for scheduling keys, while the remaining four are used for encryption. 37 bits are the round keys. The F function divides the output into bytes, XORs the input with 32 bits of round key, and then passes each byte through a separate S-box to get four 32-bit results. In different rounds, those are nonlinearly mixed using various combining functions. Five more round key bits are used to control the rotation of the output. Implementation using Python For implementing the CAST5 encryption algorithm we will use Crypto.Cipher submodule of Python which is used to implement for both encryption and decryption of a wide range of cryptographic techniques. To use this module we need to install the pycryptodome library first which provides various cryptographic algorithms. The implementation of CAST5 Algorithm using Crypto.Cipher is as follows − Example from Crypto.Cipher import CAST #Encryption function def encrypt(plaintext, key): cipher = CAST.new(key, CAST.MODE_ECB) # Ensure plaintext is a multiple of 8 bytes (64 bits) if len(plaintext) % 8 != 0: plaintext += ” ” * (8 – len(plaintext) % 8) ciphertext = cipher.encrypt(plaintext.encode(”utf-8”)) return ciphertext.hex() #Decryption function def decrypt(ciphertext, key): cipher = CAST.new(key, CAST.MODE_ECB) decrypted = cipher.decrypt(bytes.fromhex(ciphertext)) return decrypted.decode(”utf-8”).rstrip() # Plaintext message: plaintext = “Hello, this is a test message for CAST5 encryption.” key = b”0123456789abcdef” # 16 bytes (128 bits) key encrypted_text = encrypt(plaintext, key) print(“Encrypted:”, encrypted_text) decrypted_text = decrypt(encrypted_text, key) print(“Decrypted:”, decrypted_text) Following is the output of the above example − Input/Output Encrypted: c9c8791f5b73c78e5fbf3c47c7d43be7a773cf757c98d2b35073e2a4d5f454f9c9b9bce4416016b57a1872ef1c19e3f51a778be27a17f11 Decrypted: Hello, this is a test message for CAST5 encryption. Advantages of CAST5 CAST5 has a number of advantages − It is thought that CAST5 is secure. Despite being an older algorithm, there are not many hacks or security breaches. It makes use of a Feistel network structure to increase security. For memory usage and computational capability, CAST5 offers a reasonable level of efficiency. Efficient data encryption and decryption make it suitable for scenarios where speed is important. CAST5 is not based on any specific hardware or software configuration. It can be used on a range of operating systems and architectures without change because it is implemented in software. CAST5 has key sizes ranging from 40 to 128 bits, allowing users to choose the degree of security appropriate for a particular application. By enabling encryption and decryption with a single key, it simplifies key management. One can view the details of CAST5 because it is an open algorithm. This makes it trustworthy by allowing the cryptography community to examine and review it with one another. Disadvantages of CAST5 CAST5 also has some limitations and disadvantages − CAST5 supports keys with lengths ranging from 40 to 128 bits. This flexibility allows for different levels of security, however the 40-bit minimum key length is considered to be inadequate for modern cryptographic standards. Longer keys provide more resilience to brute-force attacks. CAST5 operates on 64-bit blocks. Even while this was reasonable at the time the method was developed, in comparison to more modern block ciphers with larger block sizes, it is now seen as relatively little. This may lead to security problems, especially when encrypting large volumes of data. CAST5 may not provide the same level of security as more current encryption algorithms like AES (Advanced Encryption Standard), even if it has not been compromised in reality. More computer power and advances in cryptography can make older methods more vulnerable to attacks. Print Page Previous Next Advertisements ”;
Cryptography – ROT13 Algorithm ”; Previous Next Till now, you have learnt about reverse cipher and Caesar cipher algorithms. Now, let us discuss the ROT13 algorithm and its implementation. So we are going to discuss the ROT13 cryptography algorithm. Rotate 13 Places is referred to as ROT13. It is a special case of the Caesar cipher encryption algorithm. It is among the simplest methods of encryption. As the algorithm is the same for both encryption and decryption, it is a symmetric key encryption technique. Because the encryption key displays the letters A through Z as the numbers 0 through 25, the cipher text differs by 13 spaces from the plaintext letter. As an example, A turns into N, B into O, and so on. Because the encryption and decryption processes are identical, they can be done programatically. Explanation of ROT13 Algorithm ROT13 cipher refers to the abbreviated form Rotate by 13 places. In this particular Caesar Cipher, shift is always 13. The message is encrypted or decrypted by shifting each letter thirteen places. Let us see the below image to know how ROT13 algorithm works − Every letter has been moved 13 spaces to the right, as you can see. As an example, “B” will become “O,” “D” will become “Q,” and so on. Features of ROT13 Here are some main features of ROT13 − Since ROT13 is symmetric, both encryption and decryption use the same algorithm and key. It works for each of the alphabetic letters, substituting each one with the letter 13 positions forward (or back, based on the decryption) in the alphabet. The rotation value of 13 is fixed in ROT13. When applying ROT13, if the rotation goes beyond ”Z”, it comes back to the beginning of the alphabet ”A”. ROT13 is very easy to implement and use. It provides no security against any determined attacker, as it is easily cracked with simple frequency analysis. Implementation using Python So we can implement this algorithm in different ways − Using For Loop and ord() function We will first encrypt the given message and generate an ROT13 code using a for loop. In this program, the for loop will be used to iterate over each character in the given text. If the character is a letter, we will keep it (uppercase or lowercase) and shift it by thirteen places. Non-alphabetic characters will remain unchanged. Also we will use the ord() function of Python which is used to change a single Unicode character into its integer representation. Example Below is a simple Python code for ROT13 cryptography. See the code below − # Encryption Function def rot13_encrypt(text): encrypted_text = ”” for char in text: if char.isalpha(): shifted = ord(char) + 13 if char.islower(): if shifted > ord(”z”): shifted -= 26 else: if shifted > ord(”Z”): shifted -= 26 encrypted_text += chr(shifted) else: encrypted_text += char return encrypted_text # Decryption Function def rot13_decrypt(text): decrypted_text = ”” for char in text: if char.isalpha(): shifted = ord(char) – 13 # Decryption involves shifting back by 13 if char.islower(): if shifted < ord(”a”): shifted += 26 else: if shifted < ord(”A”): shifted += 26 decrypted_text += chr(shifted) else: decrypted_text += char return decrypted_text # function execution message = “Hello, Tutorialspoint!” encrypted_msg = rot13_encrypt(message) print(“The Encrypted message:”, encrypted_msg) decrypted_msg = rot13_decrypt( encrypted_msg) print(“The Decrypted message:”, decrypted_msg) Following is the output of the above example − Input/Output The Encrypted message: Uryyb, Ghgbevnyfcbvag! The Decrypted message: Hello, Tutorialspoint! Using list comprehension In this example, list comprehension is used to perform the ROT13 encryption. Using the list we will iterate over each character in the input text using the for char in the text part at the end. For each character in the input text we will use a conditional expression to find the encrypted value. Example Below is a simple Python code for the ROT13 algorithm. See the program below − # Encryption function def rot13_encrypt(text): encrypted_text = ””.join([chr(((ord(char) – 65 + 13) % 26) + 65) if ”A” <= char <= ”Z” else chr(((ord(char) – 97 + 13) % 26) + 97) if ”a” <= char <= ”z” else char for char in text]) return encrypted_text # Decryption function def rot13_decrypt(text): decrypted_text = ””.join([chr(((ord(char) – 65 – 13) % 26) + 65) if ”A” <= char <= ”Z” else chr(((ord(char) – 97 – 13) % 26) + 97) if ”a” <= char <= ”z” else char for char in text]) return decrypted_text # Function execution message = “Hello, Everyone!” encrypted_msg = rot13_encrypt(message) print(“The Encrypted message:”, encrypted_msg) decrypted_msg = rot13_decrypt( encrypted_msg) print(“The Decrypted message:”, decrypted_msg) Following is the output of the above example − Input/Output The Encrypted message: Uryyb, Rirelbar! The Decrypted message: Hello, Everyone! Using Dictionary In this example we are going to use two dictionaries to implement the program for ROT13. So the first dictionary will map uppercase letters to their index in the alphabet. And the second dictionary will map shifted indices back to uppercase letters, from ”Z” to ”A”. The encryption function sends the resultant index back to a letter using the second dictionary after identifying each letter”s index using the first dictionary and adding the shift value. And in the decryption function we will reverse the process. Example Following is a simple Python program of ROT13 algorithm in which will use two dictionaries. Check the code below − # Dictionary to lookup the index dictionary1 = {”A”: 1, ”B”: 2, ”C”: 3, ”D”: 4, ”E”: 5, ”F”: 6, ”G”: 7, ”H”: 8, ”I”: 9, ”J”: 10, ”K”: 11, ”L”: 12, ”M”: 13, ”N”: 14, ”O”: 15, ”P”: 16, ”Q”: 17, ”R”: 18, ”S”: 19, ”T”: 20, ”U”: 21, ”V”: 22, ”W”: 23, ”X”: 24, ”Y”: 25, ”Z”: 26} # Dictionary to lookup alphabets dictionary2 = {0: ”Z”, 1: ”A”, 2: ”B”, 3: ”C”, 4: ”D”, 5: ”E”, 6: ”F”, 7: ”G”, 8: ”H”, 9: ”I”, 10: ”J”, 11: ”K”, 12: ”L”, 13: ”M”, 14: ”N”, 15: ”O”, 16: ”P”, 17: ”Q”, 18: ”R”, 19: ”S”, 20:
Cryptography – Key Generation ”; Previous Next Key Management The administration and security of the keys used to encrypt and decrypt data is referred to as key management. This covers − Generation Storage Distribution Revocation Key Generation People use a variety of online softwares and websites these days to transfer data between locations. Cryptographic-based methods are used in software and applications to protect user data from hackers. The cryptographic algorithm”s foundation is the encryption and decryption procedures, which are executed with the use of a key. While one producing key directly interprets the password, cryptographic methods use automatic key generation that begins with the user”s password. The same key is used by symmetric algorithms for both encryption and decryption. Symmetric algorithms use a second or subsidiary approach for key generation. This key generation mechanism protects the password from several types of key attacks. In cryptography, these keys serve as the means to encode and decode the data. Tools or software designed specifically for generating keys are known as key generators or keygens. What are keys? In cryptography, a key is just a really large number. Cryptography relies strongly on keys, which are used in operations like hashing, encryption, and signing to give desired qualities like authenticity (confirming the source of the information), confidentiality (keeping it hidden), and integrity (preventing it from being altered). The number of binary digits, or “bits,” or 1s and 0s, required to represent a key”s value is how long the key is measured. Typically, keys consist of hundreds or maybe even thousands of bits. This provides a compromise between security and computational speed; if the key is too lengthy, cryptography becomes impractical and if it is too short, it is not secure. Key types Keys in cryptography can be of two types: Symmetric Keys Data is usually encrypted and decrypted using symmetric keys. They function to securely “lock” away information (i.e., encrypt it) so that only the owner of the key may “unlock” (i.e., decrypt it), making them comparable to physical keys. The fact that the same key is used for both encryption and decryption gives rise to the term “symmetric.” Symmetric keys need to be kept secret, long, and random in order to be considered secure, or “strong.” Without this secret key, an attacker is unable to decrypt the data, even if they are aware of the encryption scheme that was used. An attacker cannot guess (or “brute force”) a strong key and a high-quality symmetric encryption method in a reasonable amount of time, not even with a highly powerful computer capable of trying millions of key guesses per second. Used for encrypting and decrypting data. The key is shared by both parties. Asymmetric Keys Asymmetric keys are typically found in pairs, each of which consists of a “public key” and a “private key” that are linked mathematically. The public key is intended for public distribution, while the private key must be kept secret. “Public key cryptography” is made possible by these keys. The data can be encrypted with the help of the public key by anybody, but it can only be decrypted or decoded by the owner of the private key because of the features of asymmetric keys. Sending someone a private message is benificial because all they need is your public key. Sending someone a private message is advantageous since all they need is your public key. Verifying a message”s authenticity also can be executed via asymmetric keys. To create a “digital signature,” the message is first compressed the usage of a device referred to as a “hash function,” and the ensuing “fingerprint” is then encrypted with the private key. Then, all people may additionally fast and without problems decrypt this signature using the sender”s public key to confirm that it produces the equal end result as hashing the message themselves; if not, most effective the owner of the associated personal key can signed it. Key Life−Cycle The period of time from the moment a key is created until it is completely destroyed is referred to as the key life-cycle. Many things can happen to a key in its lifetime. It may be authorised, backed up, shared, or withdrawn. Also, a key can be updated on a regular basis (that is, its value changes even though it logically remains the same with the same meta-data). This is a smart security practice because the longer a key is used, the higher chances that it will be compromised. Generating Symmetric Keys Symmetric keys are often created using random number generators (RNGs) or pseudorandom number generators (PRNGs). To create random numbers, use programming libraries or built-in functions in your programming language of your choice. Make sure that random number creation is secure and unpredictable. Example Here is a simple example of symmetric key generation in Python using the secrets module − This code uses Python”s secrets module to generate cryptographically strong random numbers suited for creating keys. The generate_symmetric_key function produces a random key of a given length in bytes. These keys are very much important for encrypting and decrypting data. For added security, the generated key is displayed in a hexadecimal format, making it difficult for unauthorized parties to interpret. import secrets def generate_symmetric_key(key_length): # Generate a random key with the specified length key = secrets.token_bytes(key_length) return key # Create a symmetric key with a length of 32 bytes (256 bits) key = generate_symmetric_key(32) print(“Symmetric Key:”, key.hex()) Output Symmetric Key: 58441e28a9515d10aa56d7f379e7320922211088a9dcd927278c42dc024d37df Generating Asymmetric Key A public key and a private key are the two linked parts of an asymmetric key. Many cryptographic toolkits contain methods such as RSA and ECC for generating these keys. To create an asymmetric key, you will need a public key and its corresponding private key. While the public key can be shared publicly, the private key must be kept secret. You may use cryptographic libraries, like the cryptography in Python, for asymmetric key generation. Here is an example using RSA − Example This code creates an
Cryptography – MixColumns Transformation ”; Previous Next The AES (Advanced Encryption Standard) algorithm, which uses the MixColumns transformation, is used for both data encryption and decryption. The AES data matrix”s every column is subjected to this mathematical process. How it works? For the MixColumns transformation in AES to work properly, each column of the state matrix needs to undergo a mathematical operation. Polynomial arithmetic in GF(28), an original algebraic field called the Galois Field (GF), forms the fundamental component of this operation. Here is an in−depth description of how it operates − State Matrix Representation − The data being processed is stored in a 4×4 grid called the state matrix. Fixed Matrix − A fixed matrix is used in the MixColumns transformation. This matrix remains same throughout the encryption and decryption procedure. Multiplication Column−wise − Each column of the state matrix is considered a polynomial in GF(2^8). The polynomial is then multiplied by the fixed matrix”s corresponding column. Polynomial Multiplication − When multiplying polynomials in GF(2^8), there are a few rules that must be followed. Firstly, modulo arithmetic must be used with a fixed polynomial called the irreducible polynomial. In the case of AES, this polynomial is x8 + x4 + x3 + x + 1 represented in hexadecimal as 0x11B. XOR Operation − Following the multiplication stage, the results are XORed (exclusively ORed) to produce the final result for each column. Resultant State Matrix − By executing the multiplication and XOR operations for every column, the converted state matrix−which shows the MixColumns transformation−is produced. The data”s diffusion and confusion resulting from this method enhance the encryption process” security. By ensuring that modifications to a single byte in the input data affect numerous bytes in the output, it becomes more challenging for attackers to access and decrypt the encrypted data. Implementation using Python In order to perform the MixColumns transformation on a state matrix, the Python code implements two helper functions: mix_columns and gf_multiply. The state matrix”s columns are converted by combining the bytes in each column with the help of a fixed matrix multiplication at a stage of the AES encryption process called MixColumns. Example def mix_columns(state): fixed_matrix = [ [0x02, 0x03, 0x01, 0x01], [0x01, 0x02, 0x03, 0x01], [0x01, 0x01, 0x02, 0x03], [0x03, 0x01, 0x01, 0x02] ] new_state = [] for col in range(4): new_column = [] for row in range(4): val = 0 for i in range(4): val ^= gf_multiply(fixed_matrix[row][i], state[i][col]) new_column.append(val) new_state.append(new_column) return new_state def gf_multiply(a, b): p = 0 for _ in range(8): if b & 1: p ^= a hi_bit_set = a & 0x80 a <<= 1 if hi_bit_set: a ^= 0x1B # irreducible polynomial b >>= 1 return p if p < 0x80 else p ^ 0x11B # Example usage: state_matrix = [ [0x32, 0x88, 0x31, 0xe0], [0x43, 0x5a, 0x31, 0x37], [0xf6, 0x30, 0x98, 0x07], [0xa8, 0x8d, 0xa2, 0x34] ] new_state = mix_columns(state_matrix) # Displaying output in matrix form for row in new_state: print(row) Following is the output of the above example − Input/Output [484, 6, 101, 424] [67, 506, 318, 232] [11, 322, 214, 421] [170, 424, 414, 120] Implementation using Java The Java implementation”s mixColumns function receives a 4×4 state matrix as input and outputs the modified state matrix following the application of the MixColumns transformation. The gfMultiply function is used to perform polynomial multiplication for each matrix element in GF(2^8). So the code using Java is given below − Example public class MixColumns { public static int[][] mixColumns(int[][] state) { int[][] fixedMatrix = { {0x02, 0x03, 0x01, 0x01}, {0x01, 0x02, 0x03, 0x01}, {0x01, 0x01, 0x02, 0x03}, {0x03, 0x01, 0x01, 0x02} }; int[][] newState = new int[4][4]; for (int col = 0; col < 4; col++) { for (int row = 0; row < 4; row++) { int val = 0; for (int i = 0; i < 4; i++) { val ^= gfMultiply(fixedMatrix[row][i], state[i][col]); } newState[row][col] = val; } } return newState; } public static int gfMultiply(int a, int b) { int p = 0; for (int i = 0; i < 8; i++) { if ((b & 1) != 0) { p ^= a; } int hiBitSet = a & 0x80; a <<= 1; if (hiBitSet != 0) { a ^= 0x1B; // irreducible polynomial } b >>= 1; } return p; } public static void main(String[] args) { int[][] stateMatrix = { {0x32, 0x88, 0x31, 0xe0}, {0x43, 0x5a, 0x31, 0x37}, {0xf6, 0x30, 0x98, 0x07}, {0xa8, 0x8d, 0xa2, 0x34} }; int[][] newState = mixColumns(stateMatrix); // Displaying output in matrix form for (int[] row : newState) { for (int val : row) { System.out.print(String.format(“%02X “, val)); } System.out.println(); } } } Following is the output of the above example − Input/Output FF 158 0B 1B1 11D E1 142 B3 65 13E D6 85 1A8 E8 1A5 163 Implementation using C++ In this implementations we are going to use C++ and we will have a function called mixColumns which takes a 4×4 state matrix as input and returns the transformed state matrix after using the MixColumns transformation. So the code is as follows − Example #include <iostream> #include <vector> int gfMultiply(int a, int b); std::vector<std::vector<int>> mixColumns(std::vector<std::vector<int>> state) { std::vector<std::vector<int>> fixedMatrix = { {0x02, 0x03, 0x01, 0x01}, {0x01, 0x02, 0x03, 0x01}, {0x01, 0x01, 0x02, 0x03}, {0x03, 0x01, 0x01, 0x02} }; std::vector<std::vector<int>> newState(4, std::vector<int>(4, 0)); for (int col = 0; col < 4; col++) { for (int row = 0; row < 4; row++) { int val = 0; for (int i = 0; i < 4; i++) { val ^= gfMultiply(fixedMatrix[row][i], state[i][col]); } newState[row][col] = val; } } return newState; } int gfMultiply(int a, int b) { int p = 0; for (int i = 0; i < 8; i++) { if (b & 1) { p ^= a; } int hiBitSet = a & 0x80; a <<= 1; if (hiBitSet) { a ^= 0x1B; // irreducible polynomial } b >>= 1; } return p; } int main() { std::vector<std::vector<int>> stateMatrix = { {0x32,
Cryptosystems – Dictionary Attack ”; Previous Next What is Dictionary Attack? A dictionary attack occurs when someone tries multiple words from a list such as a dictionary to guess the password. They try different words until they find the right one. It”s like trying to open a lock by trying multiple keys until one works. In other words, a dictionary attack is a type of malicious attack in which hackers who try to guess the password of their online user account by typing common combinations of words, phrases and numbers, can get access to things like social media profiles, even password protected files etc. This is when an attacker can be a real problem for the victim. How does dictionary attack work? This hacking uses a systematic method to crack passwords. Basically, there are three steps to mastering these hacks and understanding them can help in learning how to prevent dictionary attacks − Typically, an attacker will create a custom list of password options-a brute force dictionary-that specifies popular combinations of words and numbers Automated software then uses this brute-force dictionary to try to access online accounts. If a dictionary attack successfully penetrates a vulnerable account, the hacker uses any sensitive data stored in the profile to create his own access. This could be fraud, acting in bad faith, or simply accessing an account to make money. To gather the potential passwords, an attacker will typically use the names of common pets, recognizable pop culture figures, or athletes from major leagues, for example the, because many people use words that make sense to them and they create passwords that are easy to remember. Often, variations of these will be included in the list, such as different combinations of words or the addition of special characters. Building this list with automated tools also makes dictionary attacks easier to succeed. Using a password list and collaboration tools makes it much faster than trying to crack a password and log into an online account. If this were done manually, the attack would take much longer to give the account owner or system administrator time to notice and implement protection against the attack. Because of the methodology, these dictionary attacks rarely have any individual targets. Instead, they work in the hope that one of the passwords on the list will be correct. However, if the attacker is targeting a specific location or organization, a more focused and localized list of terms will be produced. For example, if they plan to invade Spain, they can use standard Spanish words instead of English. Or, if they are targeting a specific organization, they can use words associated with that company. Dictionary Attack vs Brute Force While a dictionary attack is a form of brutal attack, there is an important difference between the two. Whereas dictionary attacks use a fixed set of words to systematically break down a mathematical word, brute force hacks do not use letters but rather, any combination of letters, symbols, and numbers that they are not intentionally passable so that dictionary attacks are often more effective-and more likely to succeed. Since they have far fewer combinations to test. With 26 letters in the alphabet and 10 single numbers 36 digits in all the number of possible combinations for a successful brute force attack is almost impractical. According to the context, a brutal attack on a 10-character input would be in 3.76 squares of possible alphanumeric password runs. However, the advantage of brute force attacks is that their trial and error method often cracks complex and unique passwords because they use such a complete list of possible passwords, so eventually that attack will have the appropriate character combination for a password. How to prevent Dictionary Attacks To prevent dictionary attacks you can − Use Strong and Unique Passwords − Choose passwords that are hard for others to guess, don’t let common words appear in dictionaries. Avoid Easy Passwords − Unexpectedly many people use simple, easy-to-hack word and number combinations as passwords, like “Password123” or “abcd1234”. These are the most vulnerable to hacking since dictionary attacks are specifically designed to crack easy-to-guess passwords. Enable Multi Factor Authentication − This adds an extra layer of security by requiring an additional method of authentication along with your password, such as a code sent to your phone. Limit Login Attempts − Some systems can block or slow down repeated logins after a certain number of failed attempts, making it harder for attackers to guess passwords. Use Account Lockout Policy − Automatically lock out user accounts after multiple unsuccessful login attempts, preventing further review. Update Passwords Regularly − Change your passwords periodically to reduce the chances of long-term guessing. Check for Suspicious Activity − Watch for any unusual login attempts or actions on your accounts and investigate immediately. Forced reset − Dictionary hacking usually relies on repeated attempts to crack a password. Reduce the chances of a successful attack by forcing the password to be reset after a certain number of failed attempts. If this is not an option you can work with on your accounts, you can make it manual by enabling online accounts to send you an email in the event of a failed login attempt, if you are notified if someone is trying to access an account, especially if you receive these notifications in rapid succession You can change the password to ensure it remains secure. Summary Dictionary attacks are a way for hackers to guess a password by trying many words from a list such as a dictionary, until they find the right one. This attack is based on words, phrases, or characters as it is usually used by people as a password. Organizations and individuals can implement several preventive measures to defend against dictionary attacks, such as using strong unique passwords, enabling multi factor authentication, effort to limit access, implement account lockout procedures, regular password updates, monitor suspicious activity, enforce passwords -Enforcement is also configured after a certain amount unsuccessful attempts
Cryptography – Polyalphabetic Cipher ”; Previous Next Polyalphabetic ciphers use multiple alphabets to substitute letters, determining the encryption based on the letter”s position in the text. Unlike basic ciphers, polyalphabetic ciphers create a one-to-many relationship, where each letter has several possible encryptions. The Alberti Cipher, invented in 1467, is the earliest known polyalphabetic cipher. It utilizes a series of random alphabets for encryption, signified by uppercase letters in the ciphertext that indicate switches between alphabets. It can use this cipher, and Alberti used a cipher disc to show how plaintext letters are connected with ciphertext letters. In this cipher, each ciphertext character is determined by both the plaintext character and its place in the message. As the name suggests, polyalphabetic means using numerous keys rather than just one. This means that the key should be a stream of subkeys, with each subkey depending on the position of the plaintext character that requires the subkey for encipherment. How it works? It is required to have a key stream k = (K1, K2, K3,. . .) in which Ki is used to encipher the ith character in the plaintext and make the ith character in the encrypted text. Vigenere cipher is the most well-known and simple among these algorithms. The Vigenere cipher is one of the most simple and widely used polyalphabetic ciphers. In this method, the alphabetic text is encrypted with a series of Caesar ciphers depending on the letters of a keyword. The Caesar cipher restores each letter in the plaintext, keeping the letters in a constant position to the right in alphabet. This shift is implemented modulo 26. For example, in a Caesar cipher with shift 3, A can become D, B can become E, and so on. The Vigenere cipher consists of a series of simple substitution ciphers with various shift values. This cipher repeats the keyword right before it joins with the plaintext”s duration. Encryption is performed by going to the row in the table corresponding to the key and determining the column heading of the corresponding letter of the plaintext character; the letter at the intersection of the corresponding row and column of the Vigenere Square generates the ciphertext character. The remaining plaintext is encrypted using a similar approach. Features These approaches share the following common features − A set of related monoalphabetic substitution rules is applied. A key determines the rule used for a transformation. Example For example, ”a” can be encoded as ”d” in the beginning of the text but as ”n” in the middle. The polyalphabetic ciphers have the advantage of concealing the letter frequency of the fundamental language. As a result, the attacker cannot divide the ciphertext using static individual letter frequencies. Names of Polyalphabetic Cipher Polyalphabetic ciphers are a form of encryption process in which different letters are replaced in unique ways, making them harder to crack. Below are some examples of polyalphabetic ciphers − Vigenere Cipher Beaufort Cipher Playfair Cipher Autokey Cipher Running Key Cipher These ciphers use different techniques for changing the substitution pattern, making them more secure than basic ciphers like the Caesar cipher. MonoAlphabetic Cipher vs. Polyalphabetic Cipher See the difference between MonoAlphabetic Cipher and Polyalphabetic Cipher in detail below − Sr.No. MonoAlphabetic Cipher Polyalphabetic Cipher 1 In a monoalphabetic cipher, every character in the original message (plaintext) is consistently replaced by a specific character in the encrypted message (ciphertext). Polyalphabetic ciphers employ multiple different sets of letters (alphabets) to substitute the original message, making the encryption more secure and complex. 2 In this type of cipers, a character in plaintext has a one-to-one relationship with the characters in ciphertext. In this kind of ciphers, a character in plaintext has a one-to-many relationship with characters in ciphertext. 3 In a monoalphabetic stream cipher, the value of the key used to encrypt each character in the plaintext does not change based on the location of that character within the plaintext sequence. In a stream cipher, the key changes based on the location of the plaintext character within the data sequence, making it a polyalphabetic cipher. 4 Every letter in the original message (plaintext) is replaced by a specific letter in the coded message (ciphertext). Every letter in the original message can be replaced by any of ”m” different letters in the encrypted message. 5 It is a basic substitution cipher. It is a multiple substitution cipher. 6 It contains additive, multiplicative, affine, and monoalphabetic substitution ciphers. The text showcases various encryption techniques, including autokey, Playfair, Vigenere, Hill, the unbreakable one-time pad, rotor machines, and the famous Enigma cipher. 7 Monoalphabetic ciphers are not as strong as polyalphabetic ciphers. Polyalphabetic ciphers are significantly stronger. 8 The Monoalphabetic Cipher is a substitution cipher that relies on the same fixed mappings from plaintext to cipher letters throughout the text. Polyalphabetic Cipher is a substitution cipher in which plaintext characters in various locations are enciphered with distinct cryptoalphabets. Print Page Previous Next Advertisements ”;
Cryptography – Feistel Block Cipher ”; Previous Next A framework or design model called the Feistel cipher which is used to create different symmetric block ciphers, including DES. Components of this design framework can either be self-invertible, non-invertible, or invertible. The encryption and decryption algorithms are also the same as those used by the Feistel block cipher. The Feistel structure demonstrates the implementation processes of confusion and diffusion and is based on the Shannon structure that was first described in 1945. Using a substitution method, confusion creates a complex relationship between the encryption key and the ciphertext. But diffusion uses a permutation process for creating a complex link between plaintext and cipher text. The framework for implementing substitution and permutation alternately was proposed by the Feistel cipher. Substitution uses ciphertext to take the place of plaintext elements. Instead of having one element replace another as is done with substitution, permutation rearranges the elements of plaintext. Algorithm Make a list of every character in plaintext. After converting the plaintext to ascii, format it in 8-bit binary. Separate the binary plaintext string into its left (L1) and right (R1) parts. For each of the two rounds, generate two random binary keys (K1 and K2), each of equal length to the plaintext. Encryption There are multiple rounds of processing plaintext in the Feistel cipher encryption process. The substitution step and the permutation step are included in every round. Take a look at the example that following, which describes the encryption structure used in this design framework. Step 1 − The plaintext is split up into fixed-size blocks, and only one block is handled at a time in this initial phase. Two inputs for the encryption technique are a block of plaintext and a key K. Step 2 − Split the block of plaintext into two parts. The plaintext block will have two distinct representations: LE0 for the left half of the block and RE0 for the right half. To create the ciphertext block, the two parts of the plaintext block (LE0 and RE0) will undergo multiple rounds of plaintext processing. The encryption function is applied to the key Ki as well as the right half REi of the plaintext block for each round. Next, the left half of LEj is XORed with the function results. In cryptography, the logical operator XOR is used to compare two input bits and generate one output bit. For the following round, RE i+1, the output of the XOR function becomes the new right half. For the next round, the left half LEi+1 replaces the prior right half REi. The same function, which implements a substitution function by applying the round function to the right half of the plaintext block, will be executed on each round. The left half of the block is used to XOR the function”s output. After that, the two halves are switched using a permutation function. The next round”s permutation results are given. Actually, the Feistel cipher model resembles the previously discussed Shannon structure in that it uses the substitution and permutation processes in an alternating manner. Feistel Cipher Design Features When using block ciphers, the following Feistel cipher design features are taken into account − Block size − Larger block sizes are considered to make block ciphers more secure. Larger block sizes, but it slow down how quickly the encryption and decryption processes execute. Block ciphers typically contain 64-bit blocks, while more recent versions, such as AES (Advanced Encryption Standard), have 128-bit blocks. Simple analysis − By making block ciphers simple to analyze, cryptanalytic vulnerabilities can be found and fixed, leading to the development of strong algorithms. Key size − Similar to block size, higher key sizes are considered to be more secure, but they can additionally cause the encryption and decryption process to take time to complete. The previous 64-bit key has been replaced by a 128−bit key in modern ciphers. The quantity of rounds − The quantity of rounds has an effect on a block cipher”s security as well. More rounds boost security, but they also make the encryption harder to crack. The number of rounds therefore depends on the kind of data protection that a firm wants. Round function − An complex round function increases the security of the block cipher. Subkey generation function − Expert cryptanalysts find it more challenging to decrypt ciphers with more complex subkey generating functions. Fast software encryption and decryption − It is advantageous to use software that may boost block ciphers” rate of execution. Decryption The fact that the Feistel cipher model uses the same algorithm for both encryption and decryption may surprise you. A few important guidelines to keep in mind when decrypting are as follows − The encrypted text block is divided into two parts, the left (LD0) and the right (RD0), as seen in the above picture. The round function is used with the key Kn-1 to operate on the right half of the cipher block, just like the encryption algorithm. The left half of the ciphertext block is XORed with the function”s result. The output of the XOR function becomes the new right half (RD1), and RD0 swaps places with LD0 for the subsequent cycle. In fact, the identical function is used in each round, and the plaintext block is reached after a certain number of rounds are completed. Implementation in Python Let us implement the Feistel Block Cipher with the help of Python”s binascii and random modules − The Feistel Cipher algorithm for encryption and decryption is shown using this Python program. To recover the original plaintext, it first encrypts the input, which it then decrypts. Example import binascii import random def random_key(p): key = “” p = int(p) for _ in range(p): temp = random.randint(0, 1) temp = str(temp) key = key + temp return key def exor_func(a, b): temp = “” for i in range(len(a)): if a[i] == b[i]: temp += “0” else: temp += “1” return temp def convert_bin_to_dec(binary): string =