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

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

Cryptography – Encryption of Simple Substitution Cipher

Cryptography – Encryption of Simple Substitution Cipher ”; Previous Next In the previous chapter we saw what exactly a simple Substitution Cipher is, How it works, Basic implementation and its drawbacks. Now we will see different ways to implement the simple substitution cipher with the help of Python, Java and c++. Implementation in Python So we can implement the encryption of simple substitution cipher using different methods like − Using a specified shift value Using a Dictionary Mapping Using ASCII Values Directly Therefore, we will try to provide a detailed concept of each of these approaches in the sections below so that you may better grasp simple substitution cipher encryption. Approach 1: Using a specified shift value In a substitution cipher, each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. The main concept used in this approach is that we will encrypt the plaintext using a specified shift value. Shift is the number of positions each letter should be shifted in the alphabet. Here is the implementation of this approach using Python − Example # encryption function def substitution_encrypt(plain_text, shift): encrypted_text = “” for char in plain_text: # if the character is a letter if char.isalpha(): # find the ASCII value of the character ascii_val = ord(char) # if the character is uppercase or lowercase if char.isupper(): # shift the character within the range (65-90) shifted_ascii = ((ascii_val – 65 + shift) % 26) + 65 else: # shift the character within the range (97-122) shifted_ascii = ((ascii_val – 97 + shift) % 26) + 97 # change back to a character encrypted_char = chr(shifted_ascii) encrypted_text += encrypted_char else: encrypted_text += char return encrypted_text #our plain text example plaintext = “Hello, everyone!” shift = 5 encrypted_text = substitution_encrypt(plaintext, shift) print(“Plaintext: “, plaintext) print(“Encrypted text:”, encrypted_text) Following is the output of the above example − Input/Output Plaintext: Hello, everyone! Encrypted text: Mjqqt, jajwdtsj! Approach 2: Using a Dictionary Mapping Now we are going to use dictionary mapping to implement a simple substitution cipher encryption. So we create a “map” or “dictionary”, with the help of it we will match each letter of the alphabet to another letter. For example, ”a” can be mapped to ”b”, ”b” can be mapped to ”c”, and so on. Then we will use this map to replace each letter in the plaintext with its respective mapped letter. If a letter is not found in the map (like punctuation or numbers), we keep it unchanged. Below is the Python implementation for the simple substitution cipher encryption using dictionary mapping. See the program below − Example # encryption function def substitution_encrypt(plain_text, key): # a dictionary mapping for substitution mapping = {chr(97 + i): key[i] for i in range(26)} # Encrypt the plaintext encrypted_text = ””.join(mapping.get(char.lower(), char) for char in plain_text) return encrypted_text # our plain text example plaintext = “Hello, dear friend!” key = “bcdefghijklmnopqrstuvwxyza” # substitution key encrypted_text = substitution_encrypt(plaintext, key) print(“Plaintext: “, plaintext) print(“Encrypted text:”, encrypted_text) Following is the output of the above example − Input/Output Plaintext: Hello, dear friend! Encrypted text: ifmmp, efbs gsjfoe! Approach 3: Using ASCII Values Directly As you may know, every character or letter has a unique number related to it in computers called the “ASCII value”. In this approach, we will directly manipulate these ASCII values to shift each letter in the plaintext. For example, ”a” might have an ASCII value of 97, so if we shift it by 5, it becomes 102, which is the letter ”f”. So here is a Python implementation for the simple substitution cipher encryption using the above approach − Example # encryption function def substitution_encrypt(plain_text, shift): encrypted_text = “” for char in plain_text: if char.isalpha(): # use ASCII values directly to shift characters ascii_val = ord(char) shifted_ascii = ascii_val + shift if char.isupper(): if shifted_ascii > 90: shifted_ascii -= 26 elif shifted_ascii < 65: shifted_ascii += 26 elif char.islower(): if shifted_ascii > 122: shifted_ascii -= 26 elif shifted_ascii < 97: shifted_ascii += 26 encrypted_text += chr(shifted_ascii) else: encrypted_text += char return encrypted_text # function execution plaintext = “Hello, my dear colleague!” shift = 3 encrypted_text = substitution_encrypt(plaintext, shift) print(“PlainText: “, plaintext) print(“Encrypted text:”, encrypted_text) Following is the output of the above example − Input/Output PlainText: Hello, my dear colleague! Encrypted text: Khoor, pb ghdu froohdjxh! Implementation using Java In this Java implementation, we will create a simple substitution cipher algorithm. Here we are using a concept in which we have to replace each letter in the plaintext with a respective letter from the encrypted alphabet. We will create a mapping between the regular alphabet and the encrypted alphabet with the help of a HashMap. Then, for each letter in the plaintext, we will see its respective encrypted letter from the mapping and add it to the ciphertext. If a character is not in the mapping (for example, punctuation or spaces), we will leave it unchanged in the ciphertext. Example So the implementation for simple substitution cipher using Java 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<>(); static { for (int i = 0; i < alphabet.length(); i++) { encryptionMap.put(alphabet.charAt(i), encrypted_alphabet.charAt(i)); } } public static String encrypt(String plaintext) { StringBuilder ciphertext = new StringBuilder(); for (char c : plaintext.toLowerCase().toCharArray()) { if (encryptionMap.containsKey(c)) { ciphertext.append(encryptionMap.get(c)); } else { ciphertext.append(c); } } return ciphertext.toString(); } public static void main(String[] args) { String plaintext = “Hello Tutorialspoint”; String encryptedText = encrypt(plaintext); System.out.println(“Our Plaintext: ” + plaintext); System.out.println(“The Encrypted text: ” + encryptedText); } } Following is the output of the above example − Input/Output Our Plaintext: Hello Tutorialspoint The Encrypted text: ifmmp uvupsjbmtqpjou Implementation using C++ This is the implementation using C++ for the simple substitution cipher. So we will use the same approach which we have used in the above

Implementation of One Time Pad Cipher

Cryptography – Implementation of One Time Pad Cipher ”; Previous Next In the previous chapter we saw what is One−Time Pad cipher, How it works and advantages and drawback of it. So now in this chapter we will see the implementation of One−Time Pad cipher using Python, Java and C++. Implementation in Python This problem can be solved using different methods like − Using modulo operation Using XOR operation Using Python”s onetimepad module Using random, string and sqlite3 modules So we will discuss each of these methods in depth in the sections below. Using modulo operation In the code, the modulo operator (%) makes sure that the resulting letter stays within the range of English uppercase letters (ASCII values from 65 to 90). Here”s a breakdown of how it”s used in encryption and decryption: Encryption − For each character in the message and the corresponding character in the key, their ASCII values are added. The sum is then divided by 26 and the remainder is kept (using modulo). This ensures it falls within the range 0 to 25. 65 is added to this value to bring it back to the range of ASCII values for uppercase letters (65 to 90). Finally, the resulting ASCII value is converted back to its corresponding character using the chr() function. Decryption − Similar to encryption, the ASCII values of corresponding message and key characters are added. Again, modulo 26 is used to ensure the sum falls within the range 0 to 25. To decrypt, 26 is subtracted from this sum and the result is used to get the corresponding character using chr(). Example Below is the Implementation in python using modulo operation for one time pad cipher. def otp_encrypt(message, key): encrypted_message = “” for i in range(len(message)): char = chr((ord(message[i]) + ord(key[i])) % 26 + 65) encrypted_message += char return encrypted_message def otp_decrypt(encrypted_message, key): decrypted_message = “” for i in range(len(encrypted_message)): char = chr((ord(encrypted_message[i]) – ord(key[i])) % 26 + 65) decrypted_message += char return decrypted_message # plaintext and key message = “HELLO” key = “WORLD” encrypted_message = otp_encrypt(message, key) print(“Encrypted message:”, encrypted_message) decrypted_message = otp_decrypt(encrypted_message, key) print(“Decrypted message:”, decrypted_message) Following is the output of the above example − Input/Output Encrypted message: DSCWR Decrypted message: HELLO Using XOR operation Using the XOR operation, the code makes sure that encrypted characters are created and decrypted in a way that makes it very hard to get the original message or key from just the encrypted text. XOR, which stands for “exclusive or,” is a bitwise operation that uses the bits of its inputs to get a result. When you use XOR twice with the same value, you get back the original value. This makes XOR a good choice for encryption in the One-Time Pad method. Example Check the python program below for one time pad cipher using XOR operation − def otp_encrypt(message, key): encrypted_message = “” for i in range(len(message)): char = chr(ord(message[i]) ^ ord(key[i])) encrypted_message += char return encrypted_message def otp_decrypt(encrypted_message, key): decrypted_message = “” for i in range(len(encrypted_message)): char = chr(ord(encrypted_message[i]) ^ ord(key[i])) decrypted_message += char return decrypted_message # plaintext and key message = “HELLO” key = “WORLD” encrypted_message = otp_encrypt(message, key) print(“Encrypted message:”, encrypted_message) decrypted_message = otp_decrypt(encrypted_message, key) print(“Decrypted message:”, decrypted_message) Following is the output of the above example − Input/Output Encrypted message: DSCWR Decrypted message: HELLO Using Python”s onetimepad module To encrypt and decrypt messages using the One−Time Pad method, we utilize the onetimepad module. It provides functions for both encryption and decryption. This module streamlines the process by offering ready-to-use functions for One−Time Pad operations. With just a few lines of code, you can effortlessly encrypt and decrypt messages. Example Check the below code for one time pad cipher using Python”s onetimepad module − import onetimepad def otp_encrypt(message, key): encrypted_message = onetimepad.encrypt(message, key) return encrypted_message def otp_decrypt(encrypted_message, key): decrypted_message = onetimepad.decrypt(encrypted_message, key) return decrypted_message # plain text and key message = “This is a secret message” key = “My key” encrypted_message = otp_encrypt(message, key) print(“Encrypted message:”, encrypted_message) decrypted_message = otp_decrypt(encrypted_message, key) print(“Decrypted message:”, decrypted_message) Following is the output of the above example − Input/Output Encrypted message: 1911491845103e59414b161c2e0b451f4514280a530a021c Decrypted message: This is a secret message Using random, string and sqlite3 modules This Python code implements a simple command-line tool for creating and managing encrypted messages using a one time pad cipher technique. This code sets up the basics for working with encrypted messages. It uses a one time pad cipher technique, and it shows how to generate keys, encrypt messages, and decrypt them. In this Implementation we will be using random, string and sqlite3 modules. These modules are versatile and widely used in Python programming for tasks ranging from basic string manipulation to database management and random data generation. Example Check the Python program below − import random import string import sqlite3 PUNC = string.punctuation ALPHABET = string.ascii_letters def initialize(): connection = sqlite3.connect(“:memory:”, isolation_level=None, check_same_thread=False) cursor = connection.cursor() cursor.execute( “CREATE TABLE used_keys (” “id INTEGER PRIMARY KEY AUTOINCREMENT,” “key TEXT” “)” ) return cursor def create_key(_string, db_cursor): “”” Create the key from a provided string “”” retval = “” set_string = “” used_keys = db_cursor.execute(“SELECT key FROM used_keys”).fetchall() id_number = len(used_keys) + 1 for c in _string: if c in PUNC or c.isspace(): continue set_string += c key_length = len(set_string) acceptable_key_characters = string.ascii_letters for _ in range(key_length): retval += random.choice(acceptable_key_characters) if retval not in [key[0] for key in used_keys]: db_cursor.execute(“INSERT INTO used_keys(id, key) VALUES (?, ?)”, (id_number, retval)) return retval, set_string else: return create_key(_string, db_cursor) def encode_cipher(_string, key): “”” Encode the string using a generated unique key “”” retval = “” for k, v in zip(_string, key): c_index = ALPHABET.index(k) key_index = ALPHABET.index(v) cipher_index = (c_index + key_index) % 52 retval += ALPHABET[cipher_index] return retval def decode_cipher(encoded, key): # Decode the encoded string retval = “” for k, v in zip(encoded, key): c_index = ALPHABET.index(k) key_index = ALPHABET.index(v) decode = (c_index – key_index) % 52 retval += ALPHABET[decode] return retval def main(): # Main function exited

Cipher Block Chaining (CBC) Mode

Cryptography – Cipher Block Chaining (CBC) Mode ”; Previous Next It is a A block cipher that encrypts a series of bits as a whole or as a block and applies a ciphertext or encrypted key to the full block of cryptography is known as a cipher block chaining (CBC) mode. Initialization vectors (IVs) of particular characters in length are used in cipher block chaining. One of its main features is that it makes use of chaining, a working technique that makes a ciphertext block”s decryption dependent on every block that came before it. Therefore, the cryptography of the block that comes right before the ciphertext has all of the validity of all blocks that came before it. A single-bit cryptography error in one block of ciphertext affects all subsequent block decryptions. The ciphertext blocks” order can be changed, which corrupts the decryption process. In cipher block chaining, each plaintext block is essentially encrypted using cryptography after being XORed (see XOR) with the block of ciphertext that comes right before it. Only when the same plaintext or original text block is encrypted with the same encryption key and the initialization vector (IV) and the ciphertext block order is left unaltered will the identical ciphertext blocks provide the desired outcome. Because the XORing process masks plaintext patterns, it has an advantage over the Electronic Code Book mode. When two communications are encrypted using the same encryption key, the initialization vector (IV) should differ. While some applications may find it useful and unique, the initialization vector does not necessarily need to be stored or kept secret. Since ECB compromises some security or privacy criteria, cipher block chaining, or CBC, is an improved or more sophisticated version of ECB. After XORing with an initial plaintext block of the cryptography, the preceding cipher block in the CBC is sent as input to the subsequent encryption process. To put it simply, an XOR output of the previous cipher block and the current plaintext or original text block is encrypted to create a cipher block. The process is shown below − Operation The above image shows how the CBC mode works. The following are the steps − The top register should be loaded with the n-bit Initialization Vector (IV). XOR the data value in the top register with the n-bit plaintext block. Use key K to encrypt the output of the XOR operation using the underlying block cipher. Continue the process until all plaintext blocks have been processed by feeding the ciphertext block into the top register. IV data is XORed with the first decrypted ciphertext block in order to decrypt it. In order to decrypt the next ciphertext block, the previous ciphertext block is added as well into the register that replaces IV. Analysis of CBC Mode In CBC mode, the previous ciphertext block and the current plaintext block are combined, and the outcome is then encrypted using the key. Decryption, then, is the opposite procedure, in which the previous ciphertext block is added to the result after the current ciphertext has been decrypted. The benefit of CBC over ECB is that an identical message can use a different ciphertext when the IV is changed. On the negative side, the chaining effect causes the transmission error to propagate to a few further blocks during decryption. It is important to note that CBC mode provides the base for a well-known data origin authentication system. Thus, it benefits applications which need both symmetric encryption and data origin authentication. Bit-Width of CBC Mode The following table show the bit-width of the interfaces that CBC mode offer − plaintext ciphertext cipherkey IV CBC-DES 64 64 64 64 CBC-AES128 128 128 128 128 CBC-AES192 128 128 192 128 CBC-AES256 128 128 128 128 A common block cipher mode of operation that makes use of the block cipher algorithm is the Cipher Block Chaining (CBC) mode. It has the ability to process both the Advanced Encryption Standard (AES) and the Data Encryption Standard (DES) in this version. The cipherkey length for AES should be 128/192/256 bits, and 64 bits for DES. Another drawback is that, but text in the real world comes in a range of lengths, our working mode only supports units of a fixed size (64 or 128 bits for a single block). Therefore, before encryption or decryption, the final block of text given to this primitive needs to be padded to 128 bits. Formula for CBC mode This method can be expressed as follows if it is put it into a formula − Ci = EK(Bi ⊕ Ci-1) where Ci-1 is the cipher that corresponds to Bi-1 and EK is the block encryption technique with key K. Note: It is assuming that C0 is the initialization vector in the formula above. In the same way, the CBC can be used for decryption by using − Bi = DK(Ci)⊕(Ci-1) Where DK stands for the block decryption technique with key K. For decryption, the same initialization vector (C0) will be used. Security Challenge The primary attributes of this scheme are as follows − One additional particular block will be damaged if even a single bit of the conveyed message gets altered or lost. This harm wouldn”t affect other blocks. In the event that a bit is lost or added to the ciphertext, the bits and block borders will move, producing an incorrect decoding of all ensuing blocks of the cryptography”s ciphertext. The factor has the ability to append blocks to the end of the deciphered message, thereby enhancing it with either the original or plain text. Advantages Cipher Block Chaining (CBC) mode has several advantages − When input data is more than one block in size (usually 128 bits or 16 bytes for AES), CBC operates well. Messages of

Output Feedback (OFB) Mode

Cryptography – Output Feedback (OFB) Mode ”; Previous Next The Output Feedback (OFB) Mode is similar to the Cipher Feedback mode, but it delivers encrypted output instead of the XOR output. This output feedback option sends all block bits rather than just a subset of them. The output feedback mode of block cipher is extremely vulnerable to bit transmission errors. This reduces the dependecy of cipher”s need on plaintext. It involves inserting the successive output blocks from the underlying block cipher back into it. In CFB mode, feedback blocks send a string of bits to the encryption algorithm, which then generates the key-stream. The OFB mode needs an IV as the first random n-bit input block. The Initialization Vector does not need to be kept secret. The operation of OFB mode is shown in the below image − Operation The fundamental difference between OFB and CFB is that the OFB mode uses XOR to combine plaintext and ciphertext blocks with larger copies of the initialization vector. This operation can be considered as a one-time pad, and the expanded vectors as pad vectors. The formula below shows how a series of pad vectors is created − Vi = EK(Vi-1) where EK represents the block encryption technique with key K, and Vi and Vi-1 are adjacent vectors. Note that the calculation above assumes V0 to be the initialization vector. After creating a series of pad vectors, the following formula can be used to execute encryption in the OFB mode − Ci = Vi ⊕ Bi Decryption works in a similar way − Bi = Vi ⊕ Ci Note that, like the CFB mode, OFB uses the same encryption algorithm for both encryption and decryption. Analysis of OFB Mode OFB mode gives high security, successful parallel processing, and tolerance for block loss. To avoid any security issues, care must be taken to ensure that the initialization vector is random and unique. Also, the lack of error propagation can call for more precautions to protect data integrity in the case of transmission problems. Bit-Width of OFB Mode The following table show the bit-width of the interfaces that OFB mode offer − plaintext ciphertext cipherkey IV OFB-DES 64 64 64 64 OFB-AES128 128 128 128 128 OFB-AES192 128 128 192 128 OFB-AES256 128 128 256 128 Advantages of CFB Mode Once the pad vectors (also known as keystream) have been created, the OFB (Output Feedback) mode enables for block encryption and decryption in simultaneously. This can lead to improved performance in situations where processing speed is important, as numerous blocks can be handled concurrently. As each block is encrypted independently of the others, OFB mode can withstand the loss of encrypted blocks during transmission. This means that if a block is lost or corrupted, succeeding blocks” decryption will be unaffected, allowing for better error recovery. Disadvantages of OFB Mode Repeatedly encrypting the initialization vector (IV) in OFB mode can generate the same state, possibly revealing a security vulnerability. If the IV is not properly random or changes predictably, the encryption process can reuse the same keystream, allowing an attacker information about the plaintext. Unlike other modes, like CBC (Cipher Block Chaining), OFB mode does not transmit errors. While this can be beneficial in some cases since it prevents errors from affecting succeeding blocks, it also means that problems in the ciphertext may not be recognised or fixed, potentially leading to data damage or security vulnerabilities. Print Page Previous Next Advertisements ”;

Cryptography – Benefits & Drawbacks

Cryptography – Benefits & Drawbacks ”; Previous Next Websites have now become global and information has passed through online form as bits and bytes. Sensitive information is now stored, processed and transmitted digitally in computer systems and open communication channels. Because information plays such a central role, hackers target computer systems and open communication channels to steal sensitive information or compromise critical information systems. Modern cryptography provides robust mechanisms for ensuring access to information by legitimate users and preventing the hacker”s malicious intent Here in this chapter we discuss the benefits of cryptography, its limitations, its drawbacks, and the future of cryptography. So let us first see cryptography advantages or Benefits: Benefits of Cryptography Below are some Benefits of Cryptography which you need to know: Confidentiality − Cryptography is useful to keep our messages and data private. It changes the form of original data in an encoded form so only the intended recipient can understand. Suppose you and your colleague are discussing about your project with the help of a messaging app so definitely your conversation is private you do not want to disclose it to third person or hackers. So cryptography helps you to change that message into a secret code so that only you and your colleague can understand. Security − With the help of cryptography we can protect our data or information from being tampered or modified with by an unauthorized identity. So cryptography also work like a locker room. It keeps our most valuable information secure from thieves and hackers. Even if somebody try to read data or change your data, cryptography will make it really hard for them to do so without the proper key. Authentication − Cryptography is also useful to confirm that a message is coming from the authorised person which ensures it is not fake or spam. So when you receive a message it is very important to know it is really from the authorised person. Cryptography adds an extra layer of security which stamp to messages that proves the person who sent the message is genuine. It is just like a secret handshake that only you and your colleague know. Integrity − Cryptography makes sure that data cannot been changed without permission means it also increases reliability. It ensures that the message you receive is the same as the message that was sent without any changes made during the way of transmission. It helps you trust the information you get. All of these basic services provided by cryptography have enabled efficient and effective operation of networks using computer systems. Limitations of Cryptography Cryptography is really good practice to use in your applications but sometimes it is not perfect. There is always a chance that unwanted resources can break the security and get the sensitive information. So let us talk about the limitations of cryptography in the below section: Cryptography is very much dependent on Key Management. Well if you lose the keys(public and private key) or someone else steal the keys, your sensitive data may not be safe anymore. So it is very important to keep track of keys. There is also potential for Human Error. As cryptography relies on people using it correctly. If developers make a mistake in setting it up or using it. It can leave a loophole for hackers or attackers to exploit the security. It is not easy to manage the resource used in the cryptography. Encrypting and decrypting messages may take computer power and time. So if you are encrypting a large amount of data then it can slow things down. Even if the cryptography is strong but it can be vulnerable in implementation. If it is not correctly implemented in software or systems it can leave loopholes for attackers to come in the system. This means the cryptography needs to be carefully designed and tested. It does not protect against all threats. As cryptography is a great way to protect data in transit or at rest it cannot secure against all kinds of threats. For example it cannot stop somebody from taking your password or stealing your device when it is unlocked. Overall, cryptography is a powerful tool for keeping information secure, while it is not always good. It is important to use it properly and understand its limitations. Drawbacks In addition to the four basic elements of information security, there are other issues that affect the effective use of information − Strictly encrypted, authenticated, and digitally signed information can be difficult to reach even for a legitimate user at the critical decision-making moment can attack a network if computer system and has it disabled by an attacker. Encryption cannot be used to ensure high availability, one of the key elements of information security. Additional strategies are needed to protect against threats such as denial of service or outage of the information system altogether. Another key requirement for information security for access options also cannot use cryptography. Similarly, business policies and procedures must be developed. Cryptography does not protect against vulnerabilities and threats resulting from incorrect policies, procedures, and procedures. These need to be resolved by putting in place appropriate policies and backup plans. Cryptography is expensive. Cost in time and money. The addition of cryptographic techniques to information processing leads to delays. Implementing public key cryptography requires setting up and maintaining a public key infrastructure that requires a nice budget. The security of a cryptographic method depends on the computational complexity of the mathematical problems. Any computation in solving such mathematical problems or in increasing computing power can facilitate encryption methods. Print Page Previous Next Advertisements ”;

Cryptography – Transposition Cipher

Cryptography – Transposition Cipher ”; Previous Next Now let us discuss the transposition cipher algorithm. The ciphers we used up to this point have been substitution ciphers, in which characters from the plaintext were changed to other characters, numbers, or symbols. The transposition cipher is an additional type of cipher. Transposition ciphers reorder the letters in the plaintext message while still using them. A transposition cipher should be simple to identify since the letter frequencies should resemble those of English, with high frequencies for the letters a, e, i, n, o, r, s, and t. However, a transposition cipher may be challenging to cryptanalyze. Anagramming, or rearranging the ciphertext letters to “make sense,” is the key strategy. The pattern of rearrangement holds the secret of the cipher. For example the word LAUGH has five different letters. Five different letters can be arranged in 5! 120= ways, and exactly one of those arrangements should result in a word. A brute force attack would try different letter combinations until the word had been identified; at most 120 attempts will be required. Utilising patterns of language to connect word fragments and arrange them to build a word is a more effective strategy. In this chapter, we will see different types of transposition cipher algorithms, their working principles, and their implementation in different ways. How does Transposition Cipher work? As we have seen above a Transposition Cipher works by re arranging the letters in a message as per the specific pattern or rule. So let us imagine that you have a message like “HELLO” and you want to keep it private. Instead of changing the letters themselves, we rearrange them based on a rule. For example, let us say the rule is to write the message in a grid with a specific number of columns. If we use 2 columns, “HELLO” will become − So now we will read the given columns in different order, like from left to right, top to bottom. So the encrypted message will be “HLOEL”. To decrypt it, we just have to know the rule used to rearrange the letters. In this case, we know it was a 2-column grid, so we will rearrange the letters back into “HELLO”. That”s the main concept of how a Transposition Cipher works. It is like playing a game of rearranging letters in a secret way. Types of Transposition Cipher Algorithm Rail Fence cipher − The transposition cipher known as the “Rail Fence” cipher takes its name from how it is encoded. The plaintext of the rail fence cipher is written downward on successive “rails” of an imaginary fence, moving upward at the bottom. Then, rows of the message are read out. Route cipher − A route cipher reads the plaintext in a pattern given in the key after it has been written down in a grid of given dimensions. Compared to a rail fence, route ciphers have a lot more keys. In reality, even with present technology, the number of possible keys could be too large for messages of a suitable length. But not every key is created equal. Weak route selection will result in large sections of plaintext-text that has just been reversed−which will provide cryptanalysts with a hint as to the routes. Columnar transposition − When a message is transposed column by column, it is typed out in rows of a certain length and then read out again, with the columns selected in an irregular order. In most cases, a keyword defines both the row width and the column permutation. Any empty positions in an irregular columnar transposition cipher are left unfilled, whereas in a standard columnar transposition cipher, the spaces are filled with nulls. Lastly, the message is read out in columns in the keyword-designated order. Double transposition − One way to attack a single columnar transposition is to estimate potential column lengths, write the message in its columns and then search for possible anagrams. Therefore, a double transposition was frequently utilised to make it stronger. All that”s going on here is two columnar transpositions. For the two transpositions, one key or two separate keys might be used. Myszkowski transposition − Emile Victor Theodore Myszkowski created a variant type of columnar transposition in 1902, but it required a keyword with recurrent letters. Typically, a keyword letter is regarded as the next letter in alphabetical order when it appears more than once. Disrupted transposition − Certain grid points are blanked out and not used while filling in the plaintext in a disrupted transposition. This disrupts regular patterns and increases the difficulty of the cryptanalyst”s task. Grilles: Grilles, or actual masks with cutouts, are a different type of transposition cipher that does not rely on a mathematical formula. The correspondents must maintain the confidentiality of a physical key in order to achieve the highly irregular transposition that can be produced throughout the duration determined by the grille”s size. Detection and cryptanalysis − A frequency count can be used by the cryptanalyst to quickly identify basic transposition since it has no impact on the frequency of individual symbols. It is most likely a transposition if the frequency distribution of the ciphertext matches that of the plaintext. Anagramming is a common method of attacking this, which involves moving around portions of the ciphertext, searching for passages that appear to be anagrams of English words, then solving the anagrams. Once such anagrams are located, they can be extended because they provide information on the transposition pattern. Combinations − Transposition is frequently used in conjunction with other methods. For example, the weakness of both can be avoided by combining a columnar transposition with a straightforward substitution cipher. Because of the transposition, parts of the plaintext stay hidden when high frequency ciphertext symbols are substituted out for high frequency plaintext letters. The replacement makes it impossible to anagrammatically translate the transposition. This method is very effective when paired with fractionation. Fractionation − When fractionation is used, a prior step that divides each

Cryptography – Encryption Transposition Cipher

Cryptography – Encryption Transposition Cipher ”; Previous Next In the previous chapter we learned about transposition cipher, types basic implementation, features and drawbacks of this technique. Now we will see the transposition cipher encryption algorithm and its implementation using different languages like Python, C++, and Java. So first let us see the transposition algorithm. Algorithm for Transposition Cipher Encryption A transposition cipher is a method of encrypting a message by rearranging its letters. We need a key to understand the specific order in which the characters are rearranged. The key can be a number or a keyword that is used to transposition pattern. Here is the step by step process for encryption − First we need to break the message into smaller units or individual characters. Then define a grid as per the key. The number of rows is found by the length of the key, and the number of columns is by the message length divided by the number of rows. Write the message characters row by row into the grid. If the message does not perfectly fill the grid, we can pad it with additional characters like spaces or underscores. Lastly we can rearrange the columns as per the key. The order of columns shows the order in which we read the characters to get the ciphertext. Example For example, if the keyword is “SECRET”, we have to rearrange the message as per the letters in “SECRET”. So we will write down our message. For example, let”s use the message “HELLO WORLD”. Now, for each letter in our keyword, we will rearrange the letters in our message. So, using the keyword “SECRET”, we will rearrange the letters in “HELLO WORLD” as per the order of the letters in “SECRET”. In this case, the order will be: 5, 1, 2, 4, 6, 3, 7. So, “HELLO WORLD” becomes “OLHEL LWRDO”. Lastly, our encrypted message will be “OLHEL LWRDO”. That is it! We have encrypted our message using a transposition cipher. Implementation using Python The encryption for transposition cipher can be implemented using different methods − Using Python List and range() function Using pyperclip and random modules So let us see these methods one by one in the following sections − Using Python List and range() function First we will build transposition cipher encryption using Python”s list and some built-in functions. So we will use list to create an empty list of encrypted messages and also we will use the range() function to generate a sequence of numbers. It will be used to iterate over the columns in the message. Example Below is a simple Python code for the transposition cipher encryption algorithm using list and range() function. See the program below − def transposition_encrypt(message, key): encrypted = [””] * key for col in range(key): pointer = col while pointer < len(message): encrypted[col] += message[pointer] pointer += key return ””.join(encrypted) message = “Hello Tutorialspoint” key = 7 print(“Original Message: “, message) encrypted_message = transposition_encrypt(message, key) print(“Encrypted message:”, encrypted_message) Following is the output of the above example − Input/Output Original Message: Hello Tutorialspoint Encrypted message: Husetploolrioin atTl In the above output you can see that the actual message was Hello Tutorialspoint and the encrypted message is Husetploolrioin atTl. In the encrypted message all the letters are the same as the original message but their orders are different. Using pyperclip and random modules As you may know that a random module of python is used to generate random numbers within the given range. And the pyperclip module of Python is mainly used to copy and paste clipboard functions. So in this example we are going to use these modules to generate random keys and paste the encrypted message to the clipboard. We will use random.randint() function to create a random integer key within the given range. This randomness adds a layer of unpredictability to the encryption process. Example Here is the implementation of a transposition cipher encryption using the random key. Check the code below − import pyperclip import random def generate_random_key(): return random.randint(2, 10) def transposition_encrypt(message, key): encrypted = [””] * key for col in range(key): pointer = col while pointer < len(message): encrypted[col] += message[pointer] pointer += key return ””.join(encrypted) message = “Have a great day!” key = generate_random_key() print(“Original Message: “, message) encrypted_message = transposition_encrypt(message, key) pyperclip.copy(encrypted_message) print(“Encrypted message:”, encrypted_message) print(“Key used for encryption:”, key) print(“Encrypted message copied to clipboard!”) Following is the output of the above example − Input/Output Original Message: Have a great day! Encrypted message: Heaavte daa yg!r Key used for encryption: 9 Encrypted message copied to clipboard! Original Message: Have a great day! Encrypted message: H r !aaedv aaegty Key used for encryption: 4 Encrypted message copied to clipboard! In the above output you can notice that a random key is used every time to generate an encrypted message. Implementation using Java In this we are going to use Java programming language to implment the encryption transposition cipher. A plaintext string and a key are needed as input parameters for the encrypt method. According to the length of the plaintext and the key, it defines how many rows are needed. Next, it rows-by-row generates a matrix with the plaintext characters. After that, the ciphertext is created by reading the matrix column by column. Then we can use the main the encrypt method in the main method. Example Below is the implementation of the encryption transposition cipher using Java programming langugage − public class TranspositionCipher { // Function to encrypt using transposition cipher public static String encrypt(String plaintext, int key) { StringBuilder ciphertext = new StringBuilder(); int rows = (int) Math.ceil((double) plaintext.length() / key); char[][] matrix = new char[rows][key]; // Fill matrix with plaintext characters int index = 0; for (int i = 0; i < rows; ++i) { for (int j = 0; j < key; ++j) { if (index < plaintext.length()) matrix[i][j] = plaintext.charAt(index++); else matrix[i][j] = ” ”; } } // Read matrix column-wise to get ciphertext

Cryptography – RSA Decryption

Cryptography – RSA Decryption ”; Previous Next In this article we have to implement decryption of RSA Cipher using different technologies. As you may know, Decryption is the process of changing the encrypted message (ciphertext) back into its original form (plaintext) with the help of the private key in asymmetric key cryptography. Or we can say decryption is the technique to find the original message of the encrypted message. Steps for Decryption We can decrypt the message which is encrypted using RSA encryption using the following steps − Receiving the Ciphertext − The receiver gets a scrambled message (ciphertext) that was encrypted using their publicly available key. Using the Private Key − The receiver uses a secret key (private key) to unscramble the ciphertext. This secret key was created alongside the public key during a special setup. Performing the Decryption − To unscramble the message, the receiver uses a complex mathematical operation involving the secret key and large numbers, effectively reversing the encryption process. This results in numerical representations of the original message. Converting to Plaintext − The numerical representations are then converted back into the original message content. Implementation of Decryption in Python RSA decryption can be created with the help of different methods like − Using modular arithmetic and number theory Using the RSA module Using the cryptography module To help you understand RSA decryption, Python programming and functions better, we will discuss each of these ways in depth in the sections below. Using modular arithmetic and number theory In this program we will use modular arithmetic and number theory to decrypt the message. In our code, the decrypt() function takes a private key and a ciphertext message as input. Decrypting the ciphertext involves raising each number in the ciphertext to the power specified by the “d” exponent. Applying a “mod n” calculation (a mathematical operation). Convert the resulting numbers back into characters using the “chr” function. Combine these characters to obtain the decrypted message (plaintext). Example Following is a python program to for RSA decryption using modular arithmetic and number theory − 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 def decrypt(private_key, ciphertext): d, n = private_key plain = [chr(pow(char, d, n)) for char in ciphertext] return ””.join(plain) # our keys public_key, private_key = generate_keypair() # plaintext message = “Hello, world!” encrypted_message = encrypt(public_key, message) print(“Encrypted message:”, encrypted_message) decrypted_message = decrypt(private_key, encrypted_message) print(“Decrypted message:”, decrypted_message) Following is the output of the above example − Input/Output Encrypted message: [5133, 206, 9012, 9012, 7041, 3509, 7193, 3479, 7041, 6939, 9012, 1255, 3267] Decrypted message: Hello, world! Using the rsa module The RSA algorithm can be easily and efficiently implemented using Python”s rsa package. First, if you do not have already installed the rsa module then you can install it with the help of pip – pip install rsa. So first we need to generate keys and then we will decrypt the encrypted message. Generating RSA Keys After installing the module you can generate RSA key pairs with the help of this rsa module. Here is how − Example import rsa # create a key pair with 1024 bits key length (public_key, private_key) = rsa.newkeys(1024) The code will generate a pair of RSA keys: one for encryption (the public key) and the other one for decryption (the private key). Decrypting the Messages When you have the key pair, you can use them to 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(“Encrypted message:”, encrypted_message) print(“Decrypted message:”, decrypted_message.decode()) Complete code Following is the python code for your reference. So run the code and see the output − Example 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) # Decrypting the message decrypted_message = rsa.decrypt(encrypted_message, private_key) print(“Encrypted message:”, encrypted_message) print(“Decrypted message:”, decrypted_message.decode()) Following is the output of the above example − Input/Output Encrypted message: b”+.}anxda8x83xf7Dx0eIxc1xdex9cZxd7xf2xdd}xb0xd4Nx9ex1cjmxe3x12xeax95n8x87ax16Yxb6x7fx9arxf3xd6xe6lexda1xa7{xa1xa4t/qxeax19*qxc5[x87x1bxc0x8f%x83xa1KFxxe6mx97x8efx84xafxe7xdcxcfxd0xe4x80H!xcexefx13xc5x93xc3axc0Pvx07tQx_xbcxaeQ[x:xf3x19xa2xea]xf2x1ex9e9x10xedxf2x83x15W}xbbx89xd7xf6xee” Decrypted message: Hello, world! Using the cryptography module Using the cryptography module, we can create RSA key pairs. This code creates a private RSA key and extracts its corresponding public key. The keys are converted to the PEM format and saved in different files. We can use these keys to encrypt and decrypt messages. The given code shows how the private key is used for decryption. Example Following is a python implementation for RSA Decryption using cryptography module − from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding # 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() # Serialize the keys to PEM format private_key_pem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption() ) public_key_pem = public_key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo ) # Save the keys to files or use them as needed with open(”private_key.pem”, ”wb”) as f: f.write(private_key_pem) with open(”public_key.pem”, ”wb”) as f: f.write(public_key_pem) # Encrypting a message message = b”Hello, world!” encrypted_message = public_key.encrypt( message, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) ) # Decrypting the message decrypted_message = private_key.decrypt( encrypted_message, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None