Cryptography – AES Key Expansion Algorithm ”; Previous Next For use in AES encryption, a single initial key can be expanded into a series of round keys using the AES (Advanced Encryption Standard) key expansion technique. These round keys are needed for each round of AES encryption and decryption. The AES key expansion method receives a four-word (16-byte) key and returns a linear array of 44 words (176 bytes). This is sufficient to provide both the initial AddRoundKey step and a four-word round key for each of the cipher”s ten rounds. How algorithm works? In simple terms, the AES key expansion algorithm functions as follows − Initial Key − The algorithm makes use of an initial key. Depending on the level of security needed, this key”s length can range from 128 to 256 bits. Round Constants − The approach makes use of a set of round constants, which are predefined values used in the key expansion process. Word Size − The key divides words into individual blocks. A word typically has 32 bits in it. For example, four 32-bit words are created from a 128-bit key. Key Schedule − The term “key schedule” refers to a set of round keys generated using the key expansion process. The initial round key and the extra round keys that were derived from it are both included in this schedule. Expansion Rounds − The algorithm performs several tasks in each expansion round, such as − RotWord − This function rotates the bytes in a word. SubWord − Applyes a substitution operation using a predetermined S-box. Rcon − XORs the word using a round constant. Round Keys − The order of round keys that are still in place following all expansion rounds defines the key schedule. Each round key is used in the corresponding round of AES encryption or decryption. Overall, the key expansion method increases security and prevents cryptographic attacks by ensuring that each AES encryption and decryption round has a unique round key. Mathematical Representation Let us denote − K is the first key, having N bits in its length. The word count (Nk) of the key is its total word count (e.g., 4 for a 128-bit key, 6 for a 192-bit key, and 8 for a 256-bit key). Nr, the AES round identifier, is 10 for AES-128, 12 for AES-192, and 14 for AES-256. Key Expansion Process Step 1: Make the round keys first. Establish the first word K in a word array W. Iterate to generate (Nr + 1) round keys − for i = N_k to (4 * (N_r + 1) – 1): if i mod N_k == 0: temp = RotWord(W[i-1]) ^ SubWord(W[i-1]) ^ Rcon(i / N_k) else: temp = W[i-1] ^ W[i-N_k] W[i] = temp Step 2: Finalize Round Keys: After the loop, the array W has all round keys. Notations RotWord(w) − Rotate the word w”s bytes in a manner that is cyclic. SubWord(w) − Use the AES S-box to swap out each byte in the word w. Rcon(i) − Produce the current round”s i ”s round constant, or Rcon. Compute the Round Constant Rcon The round constant for the i-th round can be found by computing Rcon(i)=(RC[i],0,0,0), where RC[i] is the i-th element of the round constant array. This representation provides a mathematical description of how the original key is transformed into a set of round keys used in AES encryption and decoding. Example of AES Key Expansion Now we are going to discuss the AES (Advanced Encryption Standard) key expansion algorithm with an example. For this example, we will be using AES-128, so our initial key will be 128 bits (16 bytes). The first key can be considered as a set of bytes − 2b 7e 15 16 28 ae d2 a6 ab f7 97 66 76 15 13 1 This key is 128 bits long. Let”s look at every step of the key expansion process − Initial Key 2b 7e 15 16 28 ae d2 a6 ab f7 97 66 76 15 13 1 Expansion Rounds We start by adding the first key to our list of round keys. Following that, we iteratively generate more round keys until we reach a total of 11. Round 1 In the RotWord, SubWord, and XOR operations, we use the round constant − RotWord: 7e 15 16 2b SubWord: 63 cb e7 8c Rcon: 01 00 00 00 Round 1 Key: 63 cb e7 8c 09 cf 4f 3c 3b a9 82 fb 11 13 d8 2c Round 2 The word from the previous round key is XORed four positions back − Round 2 Key: a0 fa fe 17 88 54 2c b1 23 a3 39 39 2a 6c 76 05 Subsequent Rounds Round keys are generated in this way until a total of 11 keys have been generated. Final Round Keys Round 0 (Initial Key): 2b 7e 15 16 28 ae d2 a6 ab f7 97 66 76 15 13 1 Round 1: 63 cb e7 8c 09 cf 4f 3c 3b a9 82 fb 11 13 d8 2c Round 2: a0 fa fe 17 88 54 2c b1 23 a3 39 39 2a 6c 76 05 … Round 10: 3d 47 0e 52 77 37 2e 10 1f 7e 0e 20 6a 51 7f a7 In this example, an original key was expanded into a number of round keys using the AES key expansion technique. Every round key is created from the one before it using round constants and operations like XOR, RotWord, and SubWord. These round keys are then used in each round of AES encryption to increase security and prevent cryptographic attacks. Summary The AES key expansion method creates an initial key and a collection of round keys, which are needed for AES encryption and decryption. In operations like RotWord, SubWord, and XOR, it makes use of round constants. Security is increased since each round key ensures a unique key for each encryption round. The process improves security
Category: cryptography
Cryptography – Transposition Techniques ”; Previous Next The transposition technique is a kind of encryption that works by performing permutation on the given plaintext. Transposition ciphers are created by using the transposition technique to map normal text into ciphertext. This chapter will cover multiple uses of the transposition technique as well as the variations between transposition and the substitution technique. On the other hand, the substitution approach substitutes a symbol in plaintext with a symbol in ciphertext. However, the transposition method generates the ciphertext by applying permutation to the original plaintext. Transposition Techniques Rail Fence Transposition Columnar Transposition Columnar Transposition – Multiple Rounds Book Cipher/Running Key Cipher Vernam Cipher Let us discuss these techniques one by one in the below sections − Rail Fence Transposition Rail-Fence is a basic Transposition method in which plaintext is written as a series of diagonals, which is then read row by row to generate the ciphertext. Algorithm Step 1: A series of diagonals is used to write the plaintext. Step 2: The text is then read as a sequence of rows in order to extract the ciphertext. To help you understand it, let me to give you an example. Plaintext: Let us meet Today We will now write this simple sentence in a diagonal format, as you can see below, following a specific order − We can see why it was given the term “Rail Fence” by looking at the image, which actually looks like a rail fence. After writing the message as a series of diagonals, you must read it as a series of rows in order to extract the ciphertext. Therefore, after reading the first row, the ciphertext”s first half will be − Ltsetoa We will decipher the second part of the ciphertext by reading the second row of the Rail Fence − eumeTdy Now, we will add the two sides of the ciphertext together to get the full ciphertext, which is as follows − Ciphertext: LTSETOAEUMETDY The rail fence cipher is simple to use and even simpler to break for a cryptanalyst. Thus, a more complex method is required. Columnar Transposition In comparison to the rail fence, the columnar transposition cipher is more complex. To get ciphertext using this method, use these steps − Algorithm Step 1: The plain text is written in a row-by-row pattern in a rectangular matrix of the given size. Step 2: To get the ciphertext, read the text from a rectangular matrix column by column. However, before reading the data column by column, you must first permute the column order. The received message is the ciphertext message. To understand columnar transposition, consider this example − Plain text: Let us meet Today Place the plaintext in a predefined−size rectangle. In our case, the rectangle”s defined size is 3×5. The image below shows plaintext placed in a 3×5 rectangle. Also, we permuted the column order. To get the ciphertext, we need to read the plaintext column by column in a permuted column order. So the ciphertext created using columnar transposition cipher is as follows − Ciphertext: LUETAESEOYEMTD Similar to the rail fence cipher, the columnar cipher can be easily broken. The cryptanalyst just needs to test a few permutations and combinations of the column order to obtain the permuted column order resulting in the original message. As a result, a more complicated method had to be used to secure the encryption. Columnar Transposition – Multiple Rounds/ Improved Columnar Transposition It is same as the simple columnar method but offers an improvement. This columnar method is applied to the plaintext more than once. The steps for using the columnar approach with multiple rounds are as follows − Algorithm Step 1: Plaintext is written in a predefined rectangle, row by row. Step 2: To get the ciphertext, read the plaintext in the rectangle, column by column. Before reading the text in a rectangle column by column, rearrange the columns in the same manner as in the basic columnar technique. Step 3: To produce the final ciphertext, repeat the steps above several times. So now we will perform first round as per the above method and after first round the ciphertext will be as mentioned below − Ciphertext: LUETAESEOYEMTD To decipher the ciphertext for round 2, arrange the first round”s ciphertext in a 3×5 rectangle and rearrange the columns. The extracted ciphertext for round 2 is LSYETMOATTEMUD. In this method, we can execute as many iterations as needed. Increasing the number of repetitions increases the complexity. Book Cipher/Running Key Cipher The book cipher, also known as the running key cipher, operates on the same basic principles as the one-time pad cipher. In onetime pad cipher, the key has the same length as the plaintext and is deleted after use. Every time a new key is used to send a new message. The key or onetime pad is extracted from the book, which is an improvement over the onetime pad in Book Cipher. Let us outline the various stages − Step 1: Convert plaintext to numeric form: A=0, B=1, C=3, …Z=25. Step 2: Take a one-time pad or key from any of the books and convert it to numeric format. But the key has to be the same length as the plain text. Step 3: Now combine the numeric forms of plain text and key, matching each plaintext letter with the corresponding key text letter. If the sum of any plaintext letter and the matching key text letter exceeds 26, subtract 26. Let us discuss this with an example − Plain text: Meet tomorrow. The key is from the book: ANENCRYPTION. Now we have to turn this plaintext and key text into numeric form and combine them to get ciphertext, as seen in the image below − Add the numeric form of plaintext and key text. So after adding both the values we will get 12 7 8 32 21 31 36 29 36 25 28 35 − Now we have some numbers in the above outcome (shown
Cryptography – Columnar Transposition ”; Previous Next One type of transposition cipher that represents plaintext in matrix form is called the Columnar Transposition Cipher. Writing the plaintext out in rows and reading the ciphertext out one column at a time is known as columnar transposition. In this tutorial, we have described the columnar transposition cipher”s encryption and decryption methods. Probably the most researched transposition cipher is columnar transposition. How it Works? The message is structured as a 2-dimensional array. The length of the message determines how many rows and columns there will be. If the message is 30 characters long (including spaces), there is a 50% chance that there will be 15 rows and 2 columns, 10 rows, 3 rows, 5 rows, or 6 rows. Keep in mind that we have to append a dummy letter at the end of the message if its length exceeds 29. Encryption See the encryption process of Columnar transposition cipher below − First, the plaintext is written in the rows that are defined in advance, with the key determining the length. The order in which the plaintext”s columns are transposed can be determined using the key. The ciphertext is then created by reading the transposed plaintext column by column. Decryption So the decryption process of the columnar transposition cipher is as follows − Using the same key that was used for encryption, the ciphertext is first transposed by columns. The plaintext can be retrieved by reading the transposed ciphertext row by row. Example of Columnar Transposition If the message says, “The attack will start on Monday,” so as we can see that it is 28 characters long. However, if we add the dummy letters “x” and “x” at the end, the message will be 30 characters long. We can figure out 30 = 10 X 3 and In the case that (2,3,1) is the key, the columns are arranged as follows − The Plaintext: “the attack will start on Monday” The Ciphertext − “HAA LSROMDXETCWLTTNOAXT TKI A NY” is the Ciphertext, which is calculated from the reading on the table by columns. We rearrange the letters of a keyword, like “TWO,” in an alphabetical order to make the key easier to recall. Thus, the array columns will be rearranged using the key (2,3,1). Key Features The key features for Columnar Transposition cipher is as follows − One kind of transposition cipher is the columnar cipher, which requires rearranging the plaintext into columns before encryption. Since the key is symmetric, it can be used for both encryption and decryption. The columnar transposition cipher allows for a variable key size. The key comprises of a permutation of the integers 1 to N, where N is the plaintext”s length. Cryptanalysis can break a columnar transposition cipher, particularly when the plaintext has repetitive patterns or the key is short. Use Cases of Columnar Transposition Cipher Applications for columnar transposition cipher are many like data protection, military communications, and espionage. It works particularly well for situations when the plaintext includes long, repetitive patterns, like binary data or DNA sequences. To increase the security of the encrypted data, columnar transposition ciphers can also be used when combined with other encryption techniques, like substitution ciphers. Implementation Now we will implement the Columnar Transposition Cipher using Python, Java, C++ and Javascript. Implement using Python The code will demonstrate how to encrypt a plaintext message and then decrypt the ciphertext back to plaintext using the Columnar Transposition Cipher in Python programming language. Example def columnar_encrypt(plaintext, keyword): matrix = create_encryption_matrix(len(keyword), plaintext) keyword_sequence = get_keyword_sequence(keyword) ciphertext = “” for num in range(len(keyword_sequence)): pos = keyword_sequence.index(num + 1) for row in range(len(matrix)): if len(matrix[row]) > pos: ciphertext += matrix[row][pos] return ciphertext def create_encryption_matrix(width, plaintext): r = 0 c = 0 matrix = [[]] for pos, ch in enumerate(plaintext): matrix[r].append(ch) c += 1 if c >= width: c = 0 r += 1 matrix.append([]) return matrix def get_keyword_sequence(keyword): sequence = [] for pos, ch in enumerate(keyword): previous_letters = keyword[:pos] new_number = 1 for previous_pos, previous_ch in enumerate(previous_letters): if previous_ch > ch: sequence[previous_pos] += 1 else: new_number += 1 sequence.append(new_number) return sequence def columnar_decrypt(ciphertext, keyword): matrix = create_encryption_matrix(len(keyword), ciphertext) keyword_sequence = get_keyword_sequence(keyword) plaintext = “” index = 0 for num in range(len(keyword_sequence)): pos = keyword_sequence.index(num + 1) for row in range(len(matrix)): if len(matrix[row]) > pos: matrix[row][pos] = ciphertext[index] index += 1 for row in range(len(matrix)): for col in range(len(matrix[row])): plaintext += matrix[row][col] return plaintext # Execution of the functions plaintext = “Tutorialspoint is best” keyword = “railfence” ciphertext = columnar_encrypt(plaintext, keyword) print(“The Encrypted Text:”, ciphertext) decrypted_text = columnar_decrypt(ciphertext, keyword) print(“The Decrypted Text:”, decrypted_text) Following is the output of the above example − Input/Output The Encrypted Text: uoelsi s rttisontaiTpb The Decrypted Text: Tutorialspoint is best Implement using Java So now we will implement the Columnar transposition cipher using Java programming language. And we will use util package of java which is used to import the Map interface and the HashMap class. So the code is as follows − Example import java.util.*; public class ColumnarCipher { // Define the Key static final String encryptionKey = “BEST”; static Map<Character, Integer> keyMap = new HashMap<>(); static void setPermutationOrder() { // Add the permutation order into the map for (int i = 0; i < encryptionKey.length(); i++) { keyMap.put(encryptionKey.charAt(i), i); } } // Encryption Function static String encrypt(String plaintext) { int rows, columns; StringBuilder ciphertext = new StringBuilder(); // Number of columns in the matrix columns = encryptionKey.length(); // Maximum number of rows in the matrix rows = (int) Math.ceil((double) plaintext.length() / columns); char[][] matrix = new char[rows][columns]; for (int i = 0, k = 0; i < rows; i++) { for (int j = 0; j < columns; ) { if (k < plaintext.length()) { char ch = plaintext.charAt(k); if (Character.isLetter(ch) || ch == ” ”) { matrix[i][j] = ch; j++; } k++; } else { /* Add padding character ”_” */ matrix[i][j] = ”_”; j++; } } } for (Map.Entry<Character, Integer> entry :
Cryptography – AES Transformation Function ”; Previous Next We will now go through each of the four AES transformations one by one. We describe the forward (encryption) algorithm, the inverse (decryption) algorithm, and the stage”s rationale for each step. Substitute Bytes Transformation The primary phase in the AES encryption process is the Substitute Bytes transformation, or SubBytes. Now we are going to study it − Purpose Making the encryption process non-linear is the goal of the SubBytes transformation. Using a pre-made substitution table called the S-box, each byte in the state matrix is changed to a new byte. This modification increases the encryption process” resilience to cryptanalysis techniques by introducing confusion. S−box An S-box is a fixed 16×16 matrix with 256 predefined byte values. Each byte in the S-box has a value that is determined by a specific mathematical process. The S-box”s one-to-one mapping of input and output bytes allows for reversibility. How it Works? During the SubBytes transformation, each byte in the state matrix is changed to match a byte from the S-box. Every byte in the state matrix is replaced individually, resulting in the creation of a new state matrix. This substitution phase improves the encryption process”s defence against various kinds of attacks, including differential cryptanalysis, by introducing non-linearity. Advantages SubBytes breaks any symmetries in the plaintext, which adds difficulty to the encryption. It increases the diffusion and confusion characteristics required for strong encryption. When a preset S-box is used, the inverse S-box ensures a constant and reversible replacement method, which makes it useful for decryption. As a result, the SubBytes transformation is important to the AES encryption process because it improves the non-linearity and confusion of the encrypted data, hence enhancing its security. It is a crucial component of the well-known AES encryption method that secures private information. ShiftRows Transformation The ShiftRows transformation is an important phase in the Advanced Encryption Standard (AES) encryption process. Let us see the working of this transformation − Purpose The purpose of the ShiftRows transformation is to produce diffusion in the state matrix, distributing each byte”s influence across the matrix. It contributes to creating uncertainty and raising the encryption”s complexity, which improves the ciphertext”s security. How it works? During the ShiftRows transformation, the bytes in each row of the state matrix are shifted continually to the left. The third row is moved by two positions, the fourth row by three positions, and the second row is shifted to the left by one position. The initial row remains unchanged. The shifting, which is carried out independently for each row in the state matrix, results in a new state matrix. Example Assume that our state matrix is 4×4 − [a0, a1, a2, a3] [b0, b1, b2, b3] [c0, c1, c2, c3] [d0, d1, d2, d3] Following the ShiftRows transformation − [a0, a1, a2, a3] [b1, b2, b3, b0] [c2, c3, c0, c1] [d3, d0, d1, d2] Advantages ShiftRows adds diffusion to the encryption process by rearranging the bytes within each row of the state matrix. It increases the overall security of the encryption by making sure that each byte in the state matrix influences several bytes in subsequent encryption rounds. A key component of the AES encryption process, the ShiftRows transformation adds to the difussion and confusion properties needed for robust encryption. It is essential to maintaining the security of encrypted data since it distributes each byte”s impact across the state matrix. MixColumns Transformation The MixColumns transformation is an additional step in the AES (Advanced Encryption Standard) encryption process. Let”s examine it now − Purpose The MixColumns transformation attempts to add diffusion and strengthen encryption security. It operates on the columns of the state matrix by treating each column as a polynomial over a finite field. MixColumns provide confusion and make the encryption process resistant to various cryptanalysis techniques. How it Works? During the MixColumns transformation, a fixed matrix transformation is multiplied by each column of the state matrix. This transformation requires multiplying each column by a certain matrix and then translating the output modulo a predefined polynomial. Each column of the original state matrix is multiplied and reduced independently to create a new state matrix. Example Let us consider a matix of 4×4 − [a0, a1, a2, a3] [b0, b1, b2, b3] [c0, c1, c2, c3] [d0, d1, d2, d3] After the MixColumns transformation − [a0”, a1”, a2”, a3”] [b0”, b1”, b2”, b3”] [c0”, c1”, c2”, c3”] [d0”, d1”, d2”, d3”] Advantages Diffusion is introduced into the encryption process using MixColumns, which mixes the bytes in each state matrix column. It increases overall encryption security by ensuring that each byte in the state matrix affects many bytes in subsequent encryption rounds. An integral component of the AES encryption process, the MixColumns transformation adds to the diffusion and confusion characteristics needed for strong encryption. By blending the bytes in every state matrix column, it is important for maintaining the security of encrypted data. AddRoundKey Transformation The AddRoundKey transformation is also an important step in the AES (Advanced Encryption Standard) encryption process. Let”s take a close look at it − Purpose The AddRoundKey transformation adds the encryption key to the encryption process. Because of the state matrix and a round key created from the original encryption key, every encryption round now depends on both the plaintext and the encryption key. This step integrates the secret key data into the encryption process to ensure that the resulting ciphertext is safely dependent on both the plaintext and the key. How it Works? During the AddRoundKey transformation, each byte in the state matrix is XORed with the corresponding byte of the round key. The original encryption key helps to generate the round key that is used in each round through the process of key expansion. A separate XOR operation is carried out for each byte in the state matrix, creating a new state matrix. Example Let us say we have our state matrix of 4×4 − [a0, a1, a2, a3] [b0, b1, b2, b3]
Cryptography – MonoAlphabetic Cipher ”; Previous Next The substitution cipher is one of the oldest types of encryption algorithms because it produces each character in a plaintext message and then uses a substitution method to replace it with a new character in the ciphertext. The Monoalphabetic Substitution Cipher is also known as the “Simple Substitution Cipher”. Monoalphabetic Substitution Ciphers use an individual key mapping function K to replace a specific character α with a character from the mapping K (α). A mono-alphabetic substitution cipher is one in which the equivalent letters of the plaintext are replaced with the identical letters from the ciphertext. Mono, which means one, indicates that each letter of the plaintext has a single substitution in the ciphertext. Characteristics Mono-alphabetic ciphers are a type of substitution wherein the connection among a symbol in the plaintext and a symbol in the ciphertext is continually one-to-one and remains regular during the encryption system. Example: Caesar cipher Caesar cipher is a monoalphabetic cipher. It uses a similar replacement mechanism to get the ciphertext characters for each plaintext character. Caesar cipher makes it easy for a hacker to crack the key because it only supports 25 keys in total. This pit is covered with a monoalphabetic cipher. Example Analysis If the plaintext is “TREE”, the ciphertext can be “ADOO”, indicating that the cipher is potentially mono-alphabetic because both “O”s in the plaintext are encrypted with “E”s in the cypher text. Types of Monoalphabetic Ciphers There are mainly 4 types of Mono-alphabetic Ciphers − Additive Ciphers Additive ciphers are monoalphabetic ciphers that change each individual character in the plaintext to a different character within the ciphertext based totally on the key value utilised. For example, if the plaintext carries the character ”a” and the value of the key is 4, ”a” will be replaced with ”e” because to the fact that ”e” is 4 characters away from ”a” according to the key we have used for the additive monoalphabetic cipher process. The additive cipher is mathematically represented as follows − To encrypt plaintext using an additive monoalphabetic cipher, use the formula C=(P+k) mod 26. In this, P represents the plaintext character, k is the encryption key, and C offers the needed ciphertext. The formula for decrypting ciphertext to plaintext in additive ciphers is P=(C-k) mod 26. Here, P is the plaintext, C is the ciphertext to be converted, and k is the key. Caeser Cipher Caeser cipher is a monoalphabetic cipher in which each character in plaintext is transferred to another character by a distance of three. It is simply an additive cipher with a constant key value of 3. For example, if the plaintext contains the character ”a”, the ciphertext counterpart will have the value ”d” because the Caeser cipher”s key value is 3. The Caeser cipher is mathematically represented as follows − Encryption Process − The Caeser cipher uses the formula C=(P+3) mod 26 to encode plaintext into ciphertext. Here, P is the plaintext, C is the ciphertext, and 3 is the key, which is always the same in the Caeser cipher. Decryption process − To decrypt ciphertext into plaintext using Caeser cipher, use the formula P=(C-3) mod 26. In this example, P and C represent plaintext and ciphertext, respectively, while 3 is the key. Multiplicative Cipher A multiplicative cipher is a sort of monoalphabetic cipher in which a character in the plaintext is multiplied by the key, followed by the modulus function. For example, if the plaintext contains the character ”h” and the key is set to 4, the value of the ciphertext is ”x”. Multiplicative cipher is mathematically represented as follows − Encryption Process − To encrypt plaintext using a multiplicative cipher, use the formula C=(P*k) mod 26. Here, P represents plaintext, C is ciphertext, and K is the key. Decryption Process − The formula for decrypting ciphertext to plaintext in multiplicative ciphers is P=(C*multiplicative inverse of k) mod 26. Affine Cipher Affine cIpher is one of the most powerful monoalphabetic ciphers. The affine cipher has two keys and uses a combination of additive and multiplicative ciphers to generate ciphertext from plaintext. The mathematical representation of the affine cipher is − Encryption process − To encrypt plaintext in an affine cipher, use the formula C=(P*k1+k2) mod 26. Here, C represents ciphertext, P represents plaintext, and k1 and k2 are the two keys used in an affine cipher. Decryption Process − The formula for decrypting ciphertext to plaintext in an affine cipher is P=((C-k2)/k1) mod 26. Advantages The substitute character symbols in Monoalphabetic cipher allow for a random permutation of 26 letters of the alphabet 26! The maximum number of alphabet permutations is 4*10^26. This complicates the hacker”s ability to get the key using brute force attacks. Vulnerability The Monoalphabetic Substitution cipher is vulnerable to frequency analysis attacks; such ciphers are not safe and are susceptible to a variety of attacks, one of them being their fixed key substitution. We will look at how frequency analysis-based attacks can be used against various ciphers. The concept behind frequency analysis depends on the fact that each letter in any language has a unique personality. The most noticeable characteristic of letters is the frequency with which they appear in a language. In English, the letter “Z” appears significantly less frequently than “A”. In the past, if you wanted to determine the frequencies of letters inside a language, you had to discover a significant amount of text and count each frequency. Now, however, we have computers that can do all of the work for us. But we do not even need to go to this phase because most languages have very precise letter frequency databases compiled from millions of documents. For example, if ”N” is encrypted with ”R” multiple times in a plaintext message, it will always be encrypted to ”R”. Summary Although the hacker will not be able to use brute force attacks, it is possible to consider the key utilising the All-Fearsome Statistical Attack. If a hacker
Cryptography – Decryption Transposition Cipher ”; Previous Next In the last chapter we learned about transposition cipher encryption. Now we will see decryption of transposition ciphers and its implementations using different methods. The decryption process simply involves reversing the steps of the encryption algorithm. We use the same key to find the correct order of reading the columns to recover the actual message. Algorithm for Transposition Cipher Decryption Below is the algorithm for Transposition Cipher decryption − Inputs Ciphertext − The encrypted message. Key − The same key used for encryption. Steps First we need to divide the ciphertext into rows as per the key length. Means we will create one row for each character in the key. Now we will create an empty grid with the same number of rows as the key length and a number of columns equal to the length of the ciphertext divided by the key length. Next we have to fill the grid as per the key. So iterate over the ciphertext characters to determine its column index. And add the character to the respective cell in the grid. Start with the first column and read characters downwards, moving to the next column once you reach the bottom. Continue this process for all columns. This rearranges the characters as per the original transposition order. Print the plaintext message. Example Inputs Ciphertext: OLHEL LWRDO Key: SECRET For example, if we know the key that is “SECRET” and the original message was transposed as per the order of the letters in the key. We can rearrange the columns like below − Key: S E C R E T Columns: 5, 1, 2, 4, 6, 3 Now, we will reorder the columns of the transposed message “OLHEL LWRDO” as per the key like this − S: O L E: H E C: L W R: H R E: E D T: L O Finally, we read the characters row by row to get the original message − Original Message: HELLO WORLD So, the decrypted message for the encrypted message “OLHEL LWRDO” using the key “SECRET” is “HELLO WORLD”. Yay! We have decrypted our message using a transposition cipher. Implementation using Python The decryption for transposition cipher can be implemented using different methods − Using Math Module Using Pyperclip module So let us see these two methods one by one in the following sections − Using Math Module This Python code decrypts a message that has been encrypted using a transposition cipher. And we will use a math module to perform mathematical operations mainly to calculate the number of columns needed to decrypt the message. And math.ceil() is used to round up the result of dividing the length of the message by the key. So this code efficiently decrypts transposition cipher messages. Example Below is a Python code for the transposition cipher decryption algorithm using the Math module. See the program below − import math def transposition_decrypt(key, message): num_of_columns = math.ceil(len(message) / key) num_of_rows = key num_of_shaded_boxes = (num_of_columns * num_of_rows) – len(message) plaintext = [””] * num_of_columns col = 0 row = 0 for symbol in message: plaintext[col] += symbol col += 1 if (col == num_of_columns) or (col == num_of_columns – 1 and row >= num_of_rows – num_of_shaded_boxes): col = 0 row += 1 return ””.join(plaintext) ciphertext = ”Toners raiCntisippoh” key = 6 plaintext = transposition_decrypt(key, ciphertext) print(“Cipher Text: “, ciphertext) print(“The plain text is: “, plaintext) Following is the output of the above example − Input/Output Cipher Text: Toners raiCntisippoh The plain text is: Transposition Cipher In the above output you can see that the ciphertext message was Toners raiCntisippoh and the decrypted message is Transposition Cipher. Using Pyperclip module In this example we will use the pyperclip module of Python and it is used to copy and paste clipboard functions. So we will use this module to copy our decrypted message on the clipboard. This code is similar to the above code but in this code we are using pyperclip module to copy the decrypted message to the clipboard. Example Below is a Python code for transposition cipher decryption algorithm using pyperclip module. Please check the code below − import math import pyperclip def transposition_decrypt(key, message): num_of_columns = math.ceil(len(message) / key) num_of_rows = key num_of_shaded_boxes = (num_of_columns * num_of_rows) – len(message) plaintext = [””] * num_of_columns col = 0 row = 0 for symbol in message: plaintext[col] += symbol col += 1 if (col == num_of_columns) or (col == num_of_columns – 1 and row >= num_of_rows – num_of_shaded_boxes): col = 0 row += 1 return ””.join(plaintext) ciphertext = ”Toners raiCntisippoh” key = 6 plaintext = transposition_decrypt(key, ciphertext) print(“Cipher Text:”, ciphertext) print(“The plain text is:”, plaintext) # Copy the decrypted plaintext to the clipboard pyperclip.copy(plaintext) print(“The Decrypted Message is Copied to the Clipboard”) Following is the output of the above example − Input/Output Cipher Text: Toners raiCntisippoh The plain text is: Transposition Cipher The Decrypted Message is Copied to the Clipboard In the above output we can see that the plain text is copied to the clipboard and there is a message seen that “The Decrypted Message is Copied to the Clipboard”. Implementation using Java In this we are going to use Java programming langugage to implement the decryption of transposition cipher. Basically we will reverse the process of encryption in this implementation using Java. See the code below in Java − Example public class TranspositionCipher { // Function to decrypt using transposition cipher public static String decrypt(String ciphertext, int key) { StringBuilder plaintext = new StringBuilder(); int cols = (int) Math.ceil((double) ciphertext.length() / key); char[][] matrix = new char[cols][key]; // Fill matrix with ciphertext characters int index = 0; for (int j = 0; j < key; ++j) { for (int i = 0; i < cols; ++i) { if (index < ciphertext.length()) matrix[i][j] = ciphertext.charAt(index++); else matrix[i][j] = ” ”; } } // Read matrix row-wise to get plaintext for (int i = 0; i <
Cryptography – Hacking Monoalphabetic Cipher ”; Previous Next In recent years, technology has become taken over in everyday life. It streamlines tasks like bill payment and online shopping. However, people often store sensitive information in online accounts, unaware of the ease with which hackers can access it. To understand this vulnerability, one must adopt the mindset of a hacker to recognize how they bypass security measures employed by companies. In cybersecurity, while companies are responsible for 50% of the protection, the other half lies with users and their effective use of provided security tools. Hackers employ techniques such as Frequency Analysis, Brute Force, and Phishing. Frequency Analysis is a basic cryptanalytic method used to crack monoalphabetic ciphers. Methods for Hacking Monoalphabetic Cipher Here are some of the methods for hacking or cryptanalysis a monoalphabetic cipher − Frequency Analysis − Different letters show up more often in English. The most common one is “E.” Studying how often letters pop up in the coded text can help you figure out which letter might stand for “E.” Once you know that, you can figure out the other letters. Pattern Spotting − See if there are any sequences that keep coming up in the coded text. Some combos of letters, like “TH” or “ING,” happen a lot in English. If you notice these combos, you can take a stab at which letters they represent. Guess and Check − Make smart guesses based on context. Example: If you suspect a word is “THE,” guess the letters that likely represent “T,” “H,” and “E.” Use this to uncover additional letters. Known Plaintext Attack − If you have both the original message (plaintext) and the encrypted message (ciphertext), you can use this information to figure out the encryption key. This method is very effective but often requires more resources. Brute Force − As a last resort, try every possible combination of letters until you find the correct one. This method takes a lot of time and is usually only feasible for short messages. Implementation using Python A monoalphabetic cipher uses a fixed substitution to encrypt the entire message. A monoalphabetic cipher utilising a Python dictionary and JSON objects. With the use of this dictionary, we can encrypt the letters and store the corresponding letters as values in JSON. The following program creates a monoalphabetic program in the form of a class that includes all encryption and decryption functions. Example from string import ascii_letters, digits from random import shuffle def random_monoalpha_cipher(pool=None): if pool is None: pool = ascii_letters + digits original_pool = list(pool) shuffled_pool = list(pool) shuffle(shuffled_pool) return dict(zip(original_pool, shuffled_pool)) def inverse_monoalpha_cipher(monoalpha_cipher): inverse_monoalpha = {} for key, value in monoalpha_cipher.items(): inverse_monoalpha[value] = key return inverse_monoalpha def encrypt_with_monoalpha(message, monoalpha_cipher): encrypted_message = [] for letter in message: encrypted_message.append(monoalpha_cipher.get(letter, letter)) return ””.join(encrypted_message) def decrypt_with_monoalpha(encrypted_message, monoalpha_cipher): return encrypt_with_monoalpha( encrypted_message, inverse_monoalpha_cipher(monoalpha_cipher) ) # Generate a random monoalphabetic cipher cipher = random_monoalpha_cipher() print(“Cipher:”, cipher) # Encrypt a message message = ”Hello all you hackers out there!” encrypted = encrypt_with_monoalpha(message, cipher) print(“Encrypted:”, encrypted) # Decrypt the message decrypted = decrypt_with_monoalpha(encrypted, cipher) print(“Decrypted:”, decrypted) When you implement the code given above, you will get the following output. Input/Output As a result, you can crack a monoalphabetic cipher using a defined key value combination, converting the ciphertext to plaintext. Implementation using Java The Java code is provided below has similar functionality to the Python code we have mentioned above. It can create a random monoalphabetic cipher, encrypt messages using that cipher, and decrypt the encrypted messages. See the code below − Example import java.util.*; public class MonoalphabeticCipher { public static Map<Character, Character> randomMonoalphaCipher(String pool) { List<Character> originalChar = new ArrayList<>(); List<Character> ShuffledChar = new ArrayList<>(); for (char c : pool.toCharArray()) { originalChar.add(c); ShuffledChar.add(c); } Collections.shuffle(ShuffledChar); Map<Character, Character> cipher = new HashMap<>(); for (int i = 0; i < originalChar.size(); i++) { cipher.put(originalChar.get(i), ShuffledChar.get(i)); } return cipher; } public static Map<Character, Character> inverseCharCipher(Map<Character, Character> monoalphaCipher) { Map<Character, Character> inverseChar = new HashMap<>(); for (Map.Entry<Character, Character> entry : monoalphaCipher.entrySet()) { inverseChar.put(entry.getValue(), entry.getKey()); } return inverseChar; } public static String encryptMessage(String message, Map<Character, Character> monoalphaCipher) { StringBuilder etMsg = new StringBuilder(); for (char letter : message.toCharArray()) { etMsg.append(monoalphaCipher.getOrDefault(letter, letter)); } return etMsg.toString(); } public static String decryptMessage(String etMsg, Map<Character, Character> monoalphaCipher) { return encryptMessage(etMsg, inverseCharCipher(monoalphaCipher)); } public static void main(String[] args) { String characters = “abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789”; Map<Character, Character> cipher = randomMonoalphaCipher(characters); System.out.println(“Cipher: ” + cipher); String message = “Hello all you hackers out there!”; String encrypted = encryptMessage(message, cipher); System.out.println(“Encrypted: ” + encrypted); String decrypted = decryptMessage(encrypted, cipher); System.out.println(“Decrypted: ” + decrypted); } } Following is the output of the above example − Input/Output Print Page Previous Next Advertisements ”;
Cryptography – ECDSA Algorithm ”; Previous Next The Elliptic Curve Digital Signature Algorithm, or ECDSA, is one of the most complex public key cryptography encryption techniques. Elliptic curve cryptography generates smaller keys than digital signature methods. A kind of public key encryption known as elliptic curve cryptography takes advantage of the algebraic structure of elliptic curves over finite fields. Elliptic curve cryptography is mostly used for creating pseudo-random numbers and digital signatures, among other things. A digital signature is an authentication mechanism that uses a public key pair and a digital certificate to validate the identity of the recipient or sender of information. What is Elliptic Curve Digital Signature Algorithm? ECDSA performs the same function as any other digital signature, but more efficiently. This is so that ECDSA, like other digital signature algorithms, can offer the same level of security using smaller keys. ECDSA is used to create ECDSA certificates, which are electronic documents used to authenticate the certificate”s owner. Certificates contain information on the key used to create the certificate, the certificate”s owner, and the issuer”s signature, which is a verified trusted entity. This trusted issuer is typically a certificate authority with a signed certificate that can be tracked back through the chain of trust to the original issuing certificate authority. ECDSA operates on elliptic curves by analysing them and selecting a point on the curve. That point is multiplied by another number, resulting in a new point on the curve. Even with the original point available, locating the new point on the curve is quite challenging. ECDSA”s complexity means that it is more secure than current encryption cracking methods. Along with being more secure against current attack methods, ECDSA has a number of additional benefits. Key and Signature Size The bit size of the private key considered to be required by ECDSA is approximately two times that of the security level, in bits, similar to elliptic-curve cryptography in general. For example, an ECDSA private key is approximately 160 bits in size at a security level of 80 bits, which needs an attacker to perform a maximum of around 280 operations to discover the private key. However, the signature size for DSA and ECDSA is the same: approximately 4t bits, where t is the exponent in the formula 2t for an 80 bit security level, that is, approximately 320 bits, or 280 operations. Signature Generation Imagine Alice wants to give Bob a signed message. They have to first agree on the parameters of the curve (CURVE, G, n). G, a base point of prime order on the curve, is required in addition to the field and equation of the curve; n is the multiplicative order of the point G. Parameter CURVE − the equation and field for elliptic curves used. G − base point of an elliptic curve; a point on the curve that produces a big prime order subgroup n. n − integer order of G, this indicates that n x G = O, where O is the identity element. dA − the randomly chosen private key. QA − the key public dA x G (elliptic curve calculation) m − the text to be transmitted The starting point G”s order n needs to be prime. In fact, Z/nZ has to be a field because we assume that each nonzero element of the ring is invertible. It means n has to be a prime number. Alice generates a pair of keys that consist of a public key curve point QA = dA x G and a private key integer dA, which is chosen at random from the interval [1, n-1]. The elliptic curve point multiplication by a scalar is represented by the symbol x. Sign a Message Alice does the following steps in order to sign a message − Determine e = HASH(m). (Here, HASH refers to a cryptographic hash algorithm that converts the output to an integer, like SHA-2.) Let z represent the leftmost Ln bits of e, where Ln denotes the group order n bit length. (Take note that z is not longer than n, although it can be.) Choose k, a random integer that is cryptographically secure, from [1, n-1]. Calculate the curve point where k x G = (x1, y1) = 0. Calculate r by taking x1 mod n. Refer back to step 3 if r = 0. S = k-1 (z + rdA) mod n, must be calculated. Refer back to step 3 if s = 0. The pair (r, s) is the signature. In addition, (r, -s mod n) is a valid signature. An additional method that the ECDSA signature could reveal private keys is if k is produced by an unreliable random number generator. August 2013, users of Android Bitcoin Wallet lost their money due to a random number creation error. You can produce deterministic signatures by deriving k from the message and the private key, so avoiding random number creation completely and ensuring that k is unique for every communication. Implementation of ECDSA using Python So basically we are going to use ecdsa library of python which provides functionality to work with the ECDSA algorithm. And also we will use hashlib library to convert the given message in the hash form. Here is a simple Python implementation of ECDSA with the help of the ecdsa and haslib library − Example from ecdsa import SigningKey, VerifyingKey, SECP256k1 import hashlib # Create a new private key private_key = SigningKey.generate(curve=SECP256k1) # Derive the public key from the private key public_key = private_key.verifying_key # Some message to sign message = b”Hello, Tutorialspoint!” # Hash the message hash_message = hashlib.sha256(message).digest() # Sign the hashed message with the private key signature = private_key.sign(hash_message) # Verify the signature using the public key is_valid = public_key.verify(signature, hash_message) if is_valid: print(“Signature is valid.”) else: print(“Signature is not valid.”) Following is the output of the above example − Input/Output To run the above code we need to install hashlib and ecdsa libraries of Python. To
Cryptosystems
Cryptosystems – Overview ”; Previous Next A cryptosystem uses cryptographic methods and the support structures around them to secure information. It”s also known as a cipher system. Cryptosystem uses algorithms to convert plain text into ciphertext to securely encode or decode messages. The term cryptosystem refers to a computer system that uses cryptography, codes to protect information and communications so only the intended can read and process it. Cryptosystems use algorithms for key creation, encryption, and decoding to keep data secure. Cryptographic keys, bit strings used by algorithms, transform plain text into coded text and vice versa. The key and variable data are provided as input to an algorithm for this operation. The algorithm”s security relies on secure keys. Cryptosystems use private data like credit cards securely online. Secure email uses signatures, hashes, and key management. We will look at a basic cryptosystem model. This model keeps transmitted information confidential. You can see this simple model in the picture below − The figure above shows a sender transmitting a sensitive piece of information to a receiver in such a way that the data cannot be extracted by any authenticated or third party in the communication channel. The goal of this simple crypto scheme is that, at the end of the process, only the sender and receiver will know the private information. Cryptographic Keys The key plays an important role in the variable information submitted as input to a cryptographic algorithm to perform an encryption or decryption process. The security of the cryptographic system relies heavily on how secure the keys are that are used. If an unauthorized party were able to access the keys, they could potentially decrypt encrypted messages, pretending to be someone else, or encrypt misleading messages to pose as another individual. It is vital that keys are kept private and are generated, distributed, and stored securely to maintain the integrity of the cryptographic system. The strength of the encryption also depends on the length and complexity of the keys. Types of Cryptosystems Fundamentally, there are two types of cryptosystems based on the manner in which encryption-decryption is carried out in the system − Symmetric Key Encryption Asymmetric Key Encryption The biggest difference between these cryptosystems is the link between encryption and decryption keys. In any cryptosystem, both keys are logically connected. It is almost impossible to decrypt the ciphertext using a key unrelated to the encryption key. Symmetric Key Encryption The encryption process where the same keys are used for encrypting and decrypting the information is known as Symmetric Key Encryption. The study of symmetric cryptosystems is referred to as symmetric cryptography. Symmetric cryptosystems are also sometimes referred to as secret key cryptosystems. A few well-known examples of symmetric key encryption methods are – Digital Encryption Standard (DES), Triple-DES (3DES), IDEA, and BLOWFISH. Prior to 1970, all cryptosystems employed symmetric key encryption. Even today, its relevance is very high and it is being used extensively in many cryptosystems. It is very unlikely that this encryption will fade away, as it has certain advantages over asymmetric key encryption. The salient features of cryptosystem based on symmetric key encryption are − Persons using symmetric key encryption must share a common key prior to exchange of information. Keys are recommended to be changed regularly to prevent any attack on the system. A robust mechanism needs to exist to exchange the key between the communicating parties. As keys need to be changed on a regular basis, this technique becomes expensive and cumbersome. In a group of n people, to enable two-party communication between any two persons, the number of keys required for the group is n x (n − 1)/2. Length of Key (number of bits) in this encryption is smaller and hence, process of encryption-decryption is faster than asymmetric key encryption. Processing power of a computer system required to run a symmetric algorithm is less. Challenge of Symmetric Key Cryptosystem There are two main challenges of using symmetric key cryptography. Key establishment − Before any communication, both the sender and the receiver need to agree on a secret symmetric key. It needs a secure key management scheme in place. Trust Issue − Since the sender and the receiver use the same symmetric key, there is an implicit requirement that the sender and the receiver ”trust” each other. For example, it may happen that the receiver has lost the key to an attacker and the sender is not informed. These two challenges are highly restraining for modern day communication. Today, people need to exchange information with non-familiar and non-trusted parties. For example, communication between online sellers and customers. These limitations of symmetric key encryption gave rise to asymmetric key encryption schemes. Asymmetric(Public) Key Encryption Asymmetric Key Encryption is the process of encrypting and decrypting information using various keys. Though the keys differ, they are mathematically similar, therefore getting plaintext via decrypting ciphertext is possible. The process is depicted in the following illustration − Asymmetric Key Encryption was invented in the 20th century to overcome the necessity of pre-shared secret key between communicating persons. The salient features of this encryption scheme are as follows − Every user in this system needs to have a pair of dissimilar keys, private key and public key. Because of their mathematical relationship, these keys can be used to decrypt the ciphertext to retrieve the original plaintext when either is used for encryption. It requires putting the public key in a public repository and the private key as a well-guarded secret. Hence, this scheme of encryption is also called Public Key Encryption. Though public and private keys of the user are related, it is computationally not feasible to find one from another. This is a strength of this scheme. When Host1 has to send data to Host2, he gets the public key from the repository, encrypts the file, and sends it. Host2 uses his private key to extract the plaintext. Length of Keys (number of bits) in this encryption is large and hence,
Cryptography – Decryption of Simple Substitution Cipher ”; Previous Next In the last chapter we saw different encryption programs for simple substitution cipher. Now we will discuss the decryption methods to decrypt the given message using a simple substitution cipher using Python, Java and C++. As you may know that decryption is the reverse process of encryption so we will reverse all the programs we have created for encryption in the previous chapter. Implementation using Python We can implement the decryption of simple substitution cipher using below methods − Using a specified shift value Using a Dictionary Mapping Using ASCII Values Directly In the next sections, we will try to describe each of these ways in detail so that you can gain a better understanding of Python cryptography and simple substitution cipher decryption. Approach 1: Using a specified shift value To create a decryption function for the previous encryption program, we can use the same approach but reverse the shift direction. This below function reverses the encryption process by shifting each letter in the encrypted text in the opposite direction of the original shift. It works by subtracting the shift value instead of adding it. So basically we are undoing the encryption. Here is the implementation of decryption process using this approach in Python − Example # function for decryption def substitution_decrypt(encrypted_text, shift): decrypted_text = “” for char in encrypted_text: if char.isalpha(): ascii_val = ord(char) if char.isupper(): # Reverse the shift for uppercase letters shifted_ascii = ((ascii_val – 65 – shift) % 26) + 65 else: # Reverse the shift for lowercase letters shifted_ascii = ((ascii_val – 97 – shift) % 26) + 97 decrypted_char = chr(shifted_ascii) decrypted_text += decrypted_char else: decrypted_text += char return decrypted_text # our cipher text encrypted_text = “Mjqqt, jajwdtsj!” shift = 5 decrypted_text = substitution_decrypt(encrypted_text, shift) print(“Cipher Text: “, encrypted_text) print(“Decrypted text:”, decrypted_text) Following is the output of the above example − Input/Output Cipher Text: Mjqqt, jajwdtsj! Decrypted text: Hello, everyone! Approach 2: Using a Dictionary Mapping Here we will use dictionary mapping to implement a simple substitution cipher decryption. As we have used dictionary mapping in the previous chapter for encrypting the plaintext. Now we will use the same technique but in reverse direction. We need to reverse this mapping. In place of mapping each letter to the next one, we map each letter in the encrypted text back to its original letter in the plaintext. This needs creating a reverse dictionary in which the keys are the characters in the encrypted text and the values are the corresponding characters in the plaintext. Below is the Python implementation for the simple substitution cipher decryption using reverse dictionary mapping − # function for decryption def substitution_decrypt(encrypted_text, key): # a reverse dictionary mapping for decryption reverse_mapping = {key[i]: chr(97 + i) for i in range(26)} # Decrypt the using reverse mapping decrypted_text = ””.join(reverse_mapping.get(char, char) for char in encrypted_text) return decrypted_text # our cipher text encrypted_text = “ifmmp, efbs gsjfoe!” key = “bcdefghijklmnopqrstuvwxyza” # Example substitution key decrypted_text = substitution_decrypt(encrypted_text, key) print(“Cipher Text: “, encrypted_text) print(“Decrypted text:”, decrypted_text) Following is the output of the above example − Input/Output Cipher Text: ifmmp, efbs gsjfoe! Decrypted text: hello, dear friend! Approach 3: Using ASCII Values Directly ASCII is a character encoding standard in which we assign numerical values to letters, digits, and other characters. During encryption, each letter of the plaintext is shifted by a fixed amount using ASCII values. Now we have to decrypt so we will reverse the shifting process by subtracting the same fixed amount from each character. For example, if we are decrypting ”d” (ASCII value 100) shifted by 3, we subtract 3 to get back to ”a” (ASCII value 97). So here is a Python implementation for the simple substitution cipher decryption using ASCII values directly − # function for decryption def substitution_decrypt(encrypted_text, shift): decrypted_text = “” for char in encrypted_text: if char.isalpha(): # Use ASCII values directly to reverse the shift for decryption ascii_val = ord(char) shifted_ascii = ascii_val – shift if char.isupper(): if shifted_ascii < 65: shifted_ascii += 26 elif shifted_ascii > 90: shifted_ascii -= 26 elif char.islower(): if shifted_ascii < 97: shifted_ascii += 26 elif shifted_ascii > 122: shifted_ascii -= 26 decrypted_text += chr(shifted_ascii) else: decrypted_text += char return decrypted_text # our cipher text encrypted_text = “Khoor, pb ghdu froohdjxh!” shift = 3 decrypted_text = substitution_decrypt(encrypted_text, shift) print(“Cipher Text: “, encrypted_text) print(“Decrypted text:”, decrypted_text) Following is the output of the above example − Input/Output Cipher Text: Khoor, pb ghdu froohdjxh! Decrypted text: Hello, my dear colleague! Implementation using Java In this example we will be using Java for implementing decryption of simple substitution cipher. So we will be using Java”s Hashmap and Map library for implementing this functionality. The decryptMessage() method will work similarly to the encryption method but in this we will use the decryption map instead. It will map each encrypted letter back to its actual letter in the alphabet. We will use this method to decrypt the encrypted text we have generated in the previous chapter and get the original plaintext. Example So the implementation using Java”s Hashmap and Map library is as follows − import java.util.HashMap; import java.util.Map; public class SSC { private static final String alphabet = “abcdefghijklmnopqrstuvwxyz”; private static final String encrypted_alphabet = “bcdefghijklmnopqrstuvwxyza”; private static final Map<Character, Character> encryptionMap = new HashMap<>(); private static final Map<Character, Character> decryptionMap = new HashMap<>(); static { for (int i = 0; i < alphabet.length(); i++) { encryptionMap.put(alphabet.charAt(i), encrypted_alphabet.charAt(i)); decryptionMap.put(encrypted_alphabet.charAt(i), alphabet.charAt(i)); } } public static String decryptMessage(String ciphertext) { StringBuilder plaintext = new StringBuilder(); for (char c : ciphertext.toLowerCase().toCharArray()) { if (decryptionMap.containsKey(c)) { plaintext.append(decryptionMap.get(c)); } else { plaintext.append(c); } } return plaintext.toString(); } public static void main(String[] args) { String et = “ifmmp uvupsjbmtqpjou”; System.out.println(“The Encrypted text: ” + et); String dt = decryptMessage(et); System.out.println(“The Decrypted text: ” + dt); } } Following is the output of the above example − Input/Output The Encrypted text: ifmmp uvupsjbmtqpjou The