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

Cryptography – One-Time Pad Cipher

Cryptography – One−Time Pad Cipher ”; Previous Next The One−Time Pad algorithm is the enhanced version of Vernam Cipher. It is the only known encryption method that is unbreakable, offering complete security. This algorithm encrypts alphabetic text using the substitution technique, assigning numbers to each character in the plaintext. To use the One−Time Pad effectively, three conditions must be met: The length of the encryption key matches the length of the secret message. The encryption key consists solely of symbols generated randomly. Each encryption key is employed only once and never reused for multiple messages. In One−Time Pad Encryption system, every message is scrambled using a unique key that is just as long as the message. The encrypted message (known as ciphertext) seems like complete random and has no resemblance to the original message (called plaintext). This makes it very hard to decipher without the correct key. How One−Time Pad Work? One−time pads involve creating a sequence of characters or numbers equal to or longer than the expected longest message. This sequence is generated randomly, often using computer programs with random number generators. These values are physically recorded on a pad or readable device. Pads are distributed to individuals who may exchange sensitive messages. They can be distributed as multiple keys, with a specific key assigned to each day or a specific number of uses, ensuring that each key is used only once and then discarded. When sending a message, the sender encrypts it character by character using a secret key. Using a computer, each bit in a character (typically eight bits) is combined with the corresponding bit in the key using the XOR operation. In a one-time pad system, XOR is the encryption method. If the key”s randomness is uncertain, it can be combined with algorithms like MD5. This type of encryption is like adding a random noise to the message, and only the sender and receiver have the means to remove the noise. One−Time pads are used only once and must not be reused. Reusing a pad allows an interceptor to compare messages and potentially decipher them. To show how a one-time pad works, consider the message “TEST”. A secret key “FVEB” of equal length is generated. Each letter is assigned a number, TEST: 19, 4, 18, 19 and FVEB: 5, 21, 4, 1. Adding the numbers corresponding to plaintext and secret key: 24, 25, 22, 20. Converting these numbers back to letters: Encrypted message: YZWU To decrypt, simply reverse the process, revealing the original message “TEST”. Why is the One−Time Pad Unbreakable? Unbreakable Nature of the One−Time Pad (OTP) is believed to be uncrackable because, unlike the Vigenere cipher that can be broken through pattern analysis, the OTP key is as long as the message itself. Every possible encrypted symbol has an equal chance of representing the same original symbol, making frequency analysis ineffective in uncovering the correct message. The key used is entirely random and matches the message length, eliminating any predictable patterns for hackers to exploit. The key is discarded after each message is exchanged. Without it, even the sender and receiver cannot decipher the message. Because the key is random and used only once, it leaves no hints or patterns that hackers can guess to break the code. Encryption of One−Time Pad Imagine User1 wants to send a private message to User2. User1 writes down “HELLO” and creates a unique key, “QWERT.” − To keep the message secret, User1 matches each letter of “HELLO” with the corresponding letter in “QWERT.” For example, H = A + Q, E = B + W. User1”s encrypted message becomes “QGNNQ.” User2 receives the encrypted message and uses the same “QWERT” key to decode it. He reverses the rule: H – A = Q, E – W = G. User2 recovers the original message, “HELLO.” As the key is used only once and is completely unpredictable, anyone who intercepts the encrypted message cannot decipher it without having the key. That”s why the One−Time Pad is considered unbreakable. Decryption of One−Time Pad To decrypt the message using one time pad follow the below steps − Gather the encrypted message and the encryption key. Reverse the operations performed during encryption: – If letters were added, subtract them. Apply the reversed operations to each letter using the decryption key. Obtain the original, decrypted message by reversing all transformations. Example To decrypt “QKRRU” using the key “WORLD”: – Subtract “W” from “Q” to get “H”. – Subtract “O” from “K” to get “E”. – Continue this process for all letters. – The resulting message, “HELLO”, is the decrypted plaintext. Advantages Below are some advantages of One time Pad cipher we should consider while working with this cipher − One-time pad encryption offers the strongest possible protection by using a key that is kept confidential and only utilized once. Unlike other encryption techniques, it is immune to weaknesses like brute-force or known-plaintext attacks. One-time pad encryption adapts easily to both textual and binary data. Its implementation is straightforward, allowing it to be executed manually or with the support of a computer. Use Cases for OTP See the use cases of One−Time cipher below − Critical Communication − Essential communication for military and government operations requiring the utmost security. Diplomatic Confidentiality − Secure communication among top officials, diplomats, and intelligence agencies. Business Secrecy − Protection of sensitive financial and business information from competitors. Personal Privacy − Securing private and confidential information, including medical records and legal documents. Drawback While the OTP offers unbreakable security when used correctly, its practical limitations and challenges in key management and distribution make it less suitable for many real-world applications compared to other encryption methods. Summary The One−Time Pad Cipher provides high security by using unique keys for each message, making it very impossible for unauthorized parties to decrypt encrypted data without the relevant key. The encryption and decryption process can be implemented with the help of various methods like modulo operation, addition and subtraction,

Cryptography – RSA Encryption

Cryptography – RSA Encryption ”; Previous Next As we have seen in the previous chapters RSA (Rivest−Shamir−Adleman) is a popular encryption method that protects data shared online. It relies on the mathematical features of very large prime numbers. How RSA Encryption Works? RSA encryption secures data by encoding it in a way that only authorized parties can decipher. Below is a brief overview of how RSA encryption works − Key Generation Start with two large prime numbers, such as p and q. Multiply p and q to get n. Find Φ(n), which is calculated as (p-1) * (q-1). Φ represents Euler”s totient function. Choose an integer e that falls between 1 and Φ(n) and has no common factors with Φ(n) except 1 (they are coprime). Find d, the multiplicative inverse of e modulo Φ(n). This means that when e and d are multiplied, the result is 1 remainder Φ(n), denoted as d * e ≡ 1 (mod Φ(n)). Encryption To encrypt a message, it is first converted into numbers, usually using a pre-defined code like ASCII or Unicode. Each chunk of the message is then encrypted on its own using the public key. Encryption involves raising the numerical form of the message chunk to the power of e and dividing the result by n, taking the remainder. The resulting encrypted message (ciphertext) is a string of numbers that cannot be read and can be sent over insecure channels. Implementation of RSA using Python RSA Encryption can be implemented using different methods like − Using the random module Using the RSA module Using the cryptography module Hence, in the next few sections, we will detail each way in depth to provide you with an idea on how to create RSA encryption and a better understanding of Python. Using the random Module This program will use a random module of Python to create random numbers for key generation. In our code we will have generate_keypair() and encrypt(public_key, plaintext) methods. When the generate_keypair() method is called, it generates random prime numbers p and q. Thus, the random module is required for generating random prime integers p and q, as well as calculating a random public exponent e. These random values are important for the security and randomness of the RSA encryption technique. Example Following is a python program to for RSA encryption using random module of Python − import random def gcd(a, b): while b != 0: a, b = b, a % b return a def extended_gcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = extended_gcd(b % a, a) return (g, x – (b // a) * y, y) def mod_inverse(a, m): g, x, y = extended_gcd(a, m) if g != 1: raise Exception(”Modular inverse does not exist”) else: return x % m def generate_keypair(): p = random.randint(100, 1000) q = random.randint(100, 1000) n = p * q phi = (p – 1) * (q – 1) while True: e = random.randint(2, phi – 1) if gcd(e, phi) == 1: break d = mod_inverse(e, phi) return ((e, n), (d, n)) def encrypt(public_key, plaintext): e, n = public_key cipher = [pow(ord(char), e, n) for char in plaintext] return cipher # our public and private keys public_key, private_key = generate_keypair() # Our secret message message = “Hello, world!” print(“Our plaintext message: “, message) encrypted_message = encrypt(public_key, message) print(“Encrypted message:”, encrypted_message) Following is the output of the above example − Input/Output Our plaintext message: Hello, world! Encrypted message: [5133, 206, 9012, 9012, 7041, 3509, 7193, 3479, 7041, 6939, 9012, 1255, 3267] Using the rsa module RSA cryptography can be easily and efficiently implemented using Python”s rsa package. Installing the rsa Module First, if you do not have already installed the rsa module then you can install it with the help of pip − pip install rsa Generating RSA Keys After installing the module you can generate RSA key pairs with the help of this rsa module. Here is how − import rsa # create a key pair with 1024 bits key length (public_key, private_key) = rsa.newkeys(1024) The above code will generate a pair of RSA keys: one for encryption (the public key) and the second one for decryption (the private key). Encrypting the Messages When you have the key pair, you can use them to encrypt and decrypt messages. # Encrypting a message message = b”Hello, world!” encrypted_message = rsa.encrypt(message, public_key) # Decrypting the message decrypted_message = rsa.decrypt(encrypted_message, private_key) print(“Original message:”, message.decode()) print(“Decrypted message:”, decrypted_message.decode()) Sign and Verify RSA can also be used for digital signatures. Here is how to sign and verify a given message − # Signing a message signature = rsa.sign(message, private_key, ”SHA-256”) # Verifying the signature rsa.verify(message, signature, public_key) Complete code Below is the complete code for your reference. So run the code and see the output − import rsa # create a key pair with 1024 bits key length (public_key, private_key) = rsa.newkeys(1024) # Encrypting a message message = b”Hello, world!” encrypted_message = rsa.encrypt(message, public_key) print(“Original message:”, message.decode()) print(“Encrypted message:”, encrypted_message) # Signing a message signature = rsa.sign(message, private_key, ”SHA-256”) # Verifying the signature rsa.verify(message, signature, public_key) Following is the output of the above example − Input/Output Original message: Hello, world! Encrypted message: b”gx078$xx,5A[x11hrx15v4x0f-?xa8x18xadxdax93xa8x982x1bxf3xaeexd3x85+MZ*=xd0x8fxefVxed5ixc9Axe4xa377x1dxcexf0xb6xa9/:xf8Yxf9xf1x866x8dx1c!xb9Jxf1x9dQ8qdx01tkxd61Ux8c2x81x05wpxcb)g6txe9x03xa0MQRxcbxa6Bhbx05xb5x06fx04rx17x9cxe8B%]x95xd8Dx84Xrx9cx93xc8xaeN[m” Using the Cryptography Module So we can generate RSA key pairs using the cryptography module. This code generates a private RSA key and extracts the matching public key. Both keys are converted to the PEM format and stored in separate files. These keys can be used to encrypt and decrypt messages.The provided code demonstrates encryption using the public key. Example Following is a python implementation for RSA encryption using cryptography module − from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import rsa # Generate an RSA private key private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend() ) # Get the public key from the private key public_key = private_key.public_key() # The keys to PEM format private_key_pem

Cryptography – Multiplicative Cipher

Cryptography – Multiplicative Cipher ”; Previous Next In this chapter we will deep dive into the Multiplicative Cipher Algorithm and how it works! So let”s see it in the sections below. A multiplicative cipher belongs to the category of monoalphabetic ciphers. In a multiplicative cipher, every letter in the plaintext is substituted with a matching letter from the ciphertext based on a predetermined multiplication key. The main idea behind the multiplicative cipher is to encode and decode the plaintext using the modular arithmetic of the integers modulo, a large prime number used as a multiplication key. Each letter”s numerical value in the plaintext is multiplied by the key all over the encryption process, and the result is then calculated modulo the key. For example, if the plaintext letter is “s” and the key is 7, then the ciphertext letter is (18*7) mod 26 = 22 since the numerical value of “s” is 18. So, in this case, the cipher text symbol for the letter “a” will be “w.” Decryption is just the encryption process done backwards: each letter in the ciphertext is given a numerical value, which is divided by the key, and the result is then taken modulo the key. The multiplicative cipher”s simplicity−that is, its ease of implementation, understanding, and low processing power requirements−is one of its primary benefits. But this method is easy to use and understand, it is not very secure. It is similar to a secret code that is simple for someone else to decipher. For small things, it is suitable, but not for important things that require strong protection. How does Multiplicative Cipher work? Your secret key is a big prime number that you choose. You then modify each letter in your message using mathematical operations. For example, if your key is 7 and your message has the letter ”s”, which is number 18, you do (18 times 7) divided by 26 and take the remainder. This gives you 22, which corresponds to the letter ”w”. So, ”s” becomes ”w” in the secret message. All you have to do is reverse the math to read the secret message. You can divide each letter”s number with the key and get the remainder. If multiplication is used to convert to cipher text, it is called a wrap-around situation. Consider the letters and the associated numbers to be used as shown below − The numbers are what will be multiplied, and the corresponding key is 7. To create a multiplicative cipher in such a situation, the fundamental formula is as follows − Now use the above formula to convert “hello” in cipher text using a key, K. Let us assume our key, K is 3. Here is how we will apply the given formula to each letter in the word “hello” − For ”h”: P (plaintext value of ”h”) = 7 (assuming ”a” is 0, ”b” is 1, …, ”h” is 7) Cipher = (7 + 3) Mod 26 = 10 Mod 26 = 10 For ”e”: P (plaintext value of ”e”) = 4 Cipher = (4 + 3) Mod 26 = 7 Mod 26 = 7 For ”l”: P (plaintext value of ”l”) = 11 Cipher = (11 + 3) Mod 26 = 14 Mod 26 = 14 For ”l”: P (plaintext value of ”l”) = 11 Cipher = (11 + 3) Mod 26 = 14 Mod 26 = 14 For ”o”: P (plaintext value of ”o”) = 14 Cipher = (14 + 3) Mod 26 = 17 Mod 26 = 17 So values regarding the numbers 10, 7, 14, 14, 17 are k, h, o, o, r respectively. So, the ciphertext for “hello” with a key of 3 will be “khoor”. Algorithms for Multiplicative Cipher Encryption Algorithm First you need to choose a prime number as the encryption key. Assign numerical values to each letter in the plaintext message. Multiply each numerical value by the encryption key. Take the result modulo 26 which is the number of letters in the English alphabet to make sure that the result should stay within the range of the alphabet. Convert the resulting numerical values back to letters to get the ciphertext message. Decryption Algorithm Choose the same prime number as the decryption key. Assign numerical values to each letter in the ciphertext message. Divide each numerical value by the decryption key. Take the result modulo 26. Convert the resulting numerical values back to letters to get the original plaintext message. Implementation using Python So we can implement this algorithm in different ways − Using Basic Arithmetics In this example we are going to use basic arithmetic operations for encryption and decryption in the multiplicative cipher. So in the encryption process we will convert the plaintext message to numbers (0-25) using ASCII values. Each number will be multiplied by the encryption key. So the result will be taken modulo 26 to ensure it falls within the range of the alphabet (0-25). And then we will convert the numbers back to characters using ASCII values. In the decryption process we will convert the ciphertext message to numbers (0-25) using ASCII values. Each number is multiplied by the modular multiplicative inverse of the encryption key. The result is then taken modulo 26. And then resulting numbers are converted back to characters using ASCII values. Example Below is a simple Python code for the multiplicative cipher algorithm. See the program below − def multiplicative_encrypt(message, key): cipher_text = ”” for char in message: if char.isalpha(): # Change char to number (0-25) num = ord(char.lower()) – ord(”a”) # Encrypt with the help of (P * K) % 26 encrypted_num = (num * key) % 26 # change back to character cipher_text += chr(encrypted_num + ord(”a”)) else: cipher_text += char return cipher_text def multiplicative_decrypt(ciphertext, key): plain_text = ”” # get the modular multiplicative inverse of the key inverse_key = pow(key, -1, 26) for char in ciphertext: if char.isalpha(): # change char to number (0-25) num = ord(char.lower()) – ord(”a”) # Decrypt

Cryptosystems – Stream Cipher

Cryptography – Stream Cipher ”; Previous Next A stream cipher encrypts text by applying a key and algorithm to each bit of a data stream one by one. In contrast, block ciphers process data in blocks of multiple bits at once. Stream ciphers are mainly used to encrypt one byte (8 bits) at a time. Since stream ciphers are linear, messages are encrypted and decrypted with the help of the same key. And, while cracking them is difficult, hackers will have to manage to do it. In this, a keystream, a random series of bits, is generated from a key. To encrypt the data stream, each bit is XORed with an equivalent bit from the keystream. How does it work? Stream ciphers make use of a common key (“symmetric key”) to code their data. Encryption and decryption processes of the data are handled by this symmetric key. Unlike public-key ciphers, stream ciphers utilize one key for encryption as well as decryption, eliminating the need for different keys for each task (for instance, using one key to encrypt and another to decrypt). Cryptographic methods generally conceal data from unauthorized access by scrambling it. However, stream ciphers differ by processing data bit-by-bit, unlike block ciphers that operate on collections of data known as blocks. Stream ciphers involve Plaintext − The original message to be encrypted. Keystreams − Random sequences of characters (e.g., numbers, letters, symbols) that replace the plaintext characters. Ciphertext − The encrypted message. Key generation is a complex mathematical operation, but modern computers can perform it quickly. In a stream cipher, individual bits of plaintext are inputted and subjected to a mathematical operation. The result is jumbled text which needs the right key to decode. Using the proper key, the receiver can reverse the process and convert the scrambled text back to its plaintext. In stream cipher encryption, the key known as a one-time pad is exceptionally secure due to its unique property. It is designed to be equivalent in length to the message being encrypted, ensuring that an attacker cannot mathematically decipher the message without having the original key. Keystream Generation Let us see at a basic example of keystream creation with the help of an XOR-based stream cipher. Let”s say we have the below data − Key: 101011 Initialization Vector (IV): 110100 To create a stream of encrypted data (keystream): Set up the encryption algorithm with a secret key and initialization vector (IV). If needed, adjust the key and IV to be the same length as the message being encrypted. Combine the key and IV using an exclusive OR (XOR) operation to generate the keystream. Here is the step by step process − Key: 101011 IV: 110100 Keystream: 011111 Now, let us say we have a plaintext message as: 1100101. To encrypt this plaintext using the keystream − Plaintext: 1100101 Keystream: 011111 Ciphertext: 1011010 To decrypt the ciphertext, we would use the same keystream − Ciphertext: 1011010 Keystream: 011111 Plaintext: 1100101 This example explains how to generate a keystream, which is then used to encode and decode a message, using a key and an initialization vector. For better safety, more complex methods and bigger key sizes are used in real-world applications. Categories of Stream Ciphers Stream ciphers fall into two main categories with slightly different mechanisms − Synchronous Stream Ciphers − Employ a secret key to produce key streams independent of the plaintext and ciphertext. Self-Synchronizing Stream Ciphers − Utilize a secret key and additional randomization to enhance security against hacking. Alternative encryption options is Block cipher which divides messages into smaller blocks and applies an encryption algorithm to each block. Advantages of Stream Cipher Here are some benefits of Stream Cipher: Speedy Encryption and Decryption: Stream ciphers encrypt and decrypt data at single bit or byte speeds, making them ideal for real-time communication and demanding applications. Low Hardware Requirements: Stream ciphers can be easily implemented in simple performance (such as XOR) hardware, allowing them to be implemented efficiently on a variety of devices and systems. Selective Access: Stream ciphers provide the ability to decrypt particular parts of encrypted data selectively, which is useful when needing to access or modify specific portions without decrypting the entire message. Disadvantages of Stream Cipher Below are some disadvantages of Stream Cipher technique − Vulnerability to Known Plaintext Attacks − Known plaintext attacks are harmful to stream ciphers. An attacker can identify the encryption keystream when they have pieces of both the plaintext and the ciphertext, which include the encrypted message. This can potentially expose the protected data. Lack of Diffusion − Stream ciphers have poor diffusion. When the plaintext changes slightly, the ciphertext also changes only slightly. This makes it easier for attackers to study patterns and possibly restore the original message even without knowing the encryption key. Popular Stream Ciphers Some popular stream ciphers are − RC4 − Because it was quick and easy to use, RC4 was earlier widely used in the SSL/TLS and WEP/WPA protocols, but it was out of date due to security vulnerabilities. Salsa20 − Salsa20, developed by Daniel J. Bernstein, is known for its efficiency and safety. Applications like secure communications and disk encryption frequently use it. ChaCha − ChaCha is a newer version of Salsa20, designed with better diffusion and protection against certain attacks. It”s often used in protocols like TLS and VPNs. HC-128 − Hongjun Wu”s stream cipher offers excellent efficiency along with robust security. It works effectively in devices with limited capabilities, like cell phones. Grain − Martin Hell and Thomas Johansson developed this lightweight stream cipher. It is particularly efficient when implemented in hardware, making it ideal for use in applications such as RFID tags and sensor networks. Print Page Previous Next Advertisements ”;

Modern Symmetric Key Encryption

Cryptography – Symmetric Key Encryption ”; Previous Next Symmetric cryptography is a type of cryptography also known as secret key cryptography or private key cryptography. An encryption technique called symmetric encryption uses the same key to encrypt and decrypt data or transactions. The parties using symmetric encryption methods must securely exchange the key since it is a secret or private key. Once the data is encrypted using a symmetric encryption algorithm, anyone without the key cannot view it because the key is private. However, the data or communication can be decrypted and converted into a form that is easily readable if the recipient have the key. Secret keys might be short, simple keys or large, random strings of characters and integers. Randomised strings can be automatically generated using software algorithms. Before communication starts, both sides must exchange their shared secret key. Each pair of communicating entities needs a distinct shared key. The other communication parties do not have access to the key. Symmetric cryptography has other names for the key include secret key, conventional key, session key, file encryption key, and so on. It is ideal for bulk encryption as it is much faster than asymmetric cryptography. Below is a simple diagram which is showing symmetric cryptography process − In the above diagram − Plaintext − It represents the original message. Encryption − This shows how to use a secret key to transform plaintext into ciphertext. Ciphertext − It represents the encrypted message. Decryption − This shows the process of converting the ciphertext back into plaintext using the same secret key. Last Plaintext − It shows the original message again after decryption. Symmetric cryptography is exactly like having a secret language between friends. Suppose you and your friend have an original way of sending communications that only you two friends know about. You both use the same secret key to encrypt and decrypt your messages. So, if anyone else tries to read your communications, they will not make sense because they do not have the secret key. It is like having a hidden language that only you and your friend can communicate in. Principles The following are some basic principles behind symmetric key algorithms − Symmetric key algorithms use the same key for both encryption and decryption, allowing messages to be reversed between two parties. This means that both parties need the same private key in order to send and receive the message. Since symmetric key algorithms do not need to use complex mathematical operations such as exponentiation, they are generally faster and more efficient than asymmetric key algorithms this makes them ideal for applications such as Internet connection security. All asymmetric key algorithms are more secure than symmetric key algorithms. However, symmetric key algorithms are usually faster and more efficient than asymmetric key algorithms. This is because the encryption and decryption systems use the same key, so if the key is stolen, the security of the system is also compromised. Symmetric Encryption with Authentication With authentication, you are able to add a special mark to our message before you send it in the channel. This mark proves that the message is really from the intended person and has not been modified. So when your friend gets the message, they can check the mark to make sure it is really from you and has not been altered or modified. So we can say it is like putting your signature on a letter to prove that it is written by you. Symmetric Encryption without Authentication Let us see and understand this concept with the help of an example. Let”s say, you and your friend have your secret key for encrypting and decrypting messages. But this time, you are only concerned about keeping the message secret. You do not care if someone changes the message during the transmission. So you encrypt the message with the help of your secret key, and your friend can decrypt it using the same key. This makes sure that only you and your friend can understand the message, but there is no way to know if the message has been modified by someone else. Advantages As symmetric cryptography requires only one key, it can encrypt and decrypt information or data more quickly. There is only one key needed to make this simple to use and understand. The reason this kind of encryption is effective is that it allows for secure communication between a limited group of trusted parties. It is more difficult for unauthorised people to read the message and more secure the longer the key is held. Disadvantages It can be difficult for parties to safely share the secret key with one other. So we can say key Distribution is difficult. If the key is lost or compromised, all encrypted messages become vulnerable. So key management is a difficult task. It is not ideal for large-scale communication in which many parties need to securely exchange messages. This cryptography has limited security. While secure with a strong key, it is susceptible to attacks if the key is weak or poorly managed. Applications For many daily online activities, including banking apps and safe online browsing, symmetric encryption is important. Here are a some of the examples of these applications − Before completing a transaction, many online banking and payment applications demand that personally identifiable information be verified. Predicting accurate information helps in stopping scams and cybercrime. Software like BitLocker and FileVault use symmetric cryptography to encrypt files and folders. Software like BitLocker and FileVault use symmetric cryptography to encrypt files and folders. Symmetric encryption is used to secure the personal data that a website or organisation keeps for its visitors or the business itself. This is done to stop hackers from outside the company or unhappy staff members from within the company from tracking on sensitive data. We can use this cryptography in messaging apps. Many messaging apps like WhatsApp and Telegram use symmetric cryptography to encrypt messages between users. When accessing a secure

Electronic Code Book (ECB) Mode

Cryptography – Electronic Code Book (ECB) Mode ”; Previous Next The Electronic Code Book (ECB) is a basic block cipher mode of operation that is mostly used together with symmetric key encryption. It is a simple method for handling a list of message blocks that are listed in sequence. There are several blocks in the input plaintext. The encryption key is used to independently and individually encrypt each block (ciphertext). Therefore, it is also possible to decrypt each encrypted block individually. Every kind of block can have a different encryption key supported by ECB. Every plaintext block in ECB has a predefined ciphertext value that matches it, and vice versa. Hence, similar ciphertexts can always be encrypted from identical plaintexts using identical keys. This implies that the output ciphertext blocks will always be the same if plaintext blocks P1, P2, and so forth are encrypted several times using the same key. In other words, the ciphertext value will always be equal to the plaintext value. This additionally holds true for plaintexts that include somewhat parts that are identical. For example, largely identical ciphertext parts will be included in plaintexts that have identical letter headers and are encrypted using the same key. Operation To create the first block of ciphertext, the user takes the first block of plaintext and encrypts it using the key. He then uses the same procedure and key to go through the second block of plaintext, and so on. Because the ECB mode is deterministic, the ciphertext blocks that are produced will be identical if plaintext blocks P1, P2,…, and Pm are encrypted twice with the same key. In reality, we can technically generate a codebook of ciphertexts for every possible block of plaintext for a given key. Then, all that would be required for encryption would be to search for the necessary plaintext and choose the appropriate ciphertext. Because of this, the process is similar to assigning code words in a codebook, which is why it has an official name: Electronic Codebook mode of operation (ECB). Here”s a visual representation of it − Analysis of ECB Mode In real life, application data typically contain guessable partial information. For example, one can figure out the salary range. If the plaintext message is contained in a predictable area, an attacker may be able to decipher the ciphertext from ECB by trial and error. For example, an attacker can retrieve a salary figure after a limited number of attempts if the salary figure is encrypted using a ciphertext from the ECB mode. Since most applications do not wish to use deterministic ciphers, the ECB mode should not be used in them. Data Encryption Standard vs. Electronic Code Book IBM created the Data Encryption Standard (DES) in the early 1970s, and in 1977 it was recognised as a Federal Information Processing Standard (FIPS). DES can encrypt data in five different ways. Among these is the original DES mode, or ECB. FIPS Release 81 now includes three new options: Cipher Block Chaining (CBC), Cipher Feedback (CFB), and Output Feedback (OFB). Later, NIST Special Publication 800-38a was updated to include a fifth mode called Counter Mode. The design concepts of these modes vary, including whether using initialization vectors, whether to use blocks rather than streams, and whether or not encryption faults are likely to spread to subsequent blocks. Implementation Using Python This implementation performs ECB encryption and decryption using simple byte-level operations. It is crucial to keep in mind that, in most cases, ECB mode is not secure and needs to be substituted by more secure modes like CBC or GCM. Below is a simple Python implementation of ECB mode encryption and decryption − Example # ECB encryption & decryption def pad(text, block_size): padding_length = block_size – (len(text) % block_size) padding = bytes([padding_length] * padding_length) return text + padding def unpad(padded_text): padding_length = padded_text[-1] return padded_text[:-padding_length] def xor_bytes(byte1, byte2): return bytes([a ^ b for a, b in zip(byte1, byte2)]) #Encryption Method def encrypt_ecb(key, plaintext): block_size = len(key) padded_plaintext = pad(plaintext, block_size) num_blocks = len(padded_plaintext) // block_size cipher_text = b”” for i in range(num_blocks): block_start = i * block_size block_end = block_start + block_size block = padded_plaintext[block_start:block_end] encrypted_block = xor_bytes(block, key) cipher_text += encrypted_block return cipher_text # Decryption Method def decrypt_ecb(key, ciphertext): block_size = len(key) num_blocks = len(ciphertext) // block_size plain_text = b”” for i in range(num_blocks): block_start = i * block_size block_end = block_start + block_size block = ciphertext[block_start:block_end] decrypted_block = xor_bytes(block, key) plain_text += decrypted_block return unpad(plain_text) # key and plaintext key = b”ABCDEFGHIJKLMNOP” # 16 bytes key for AES-128 plaintext = b”Hello, Tutorialspoint!” ciphertext = encrypt_ecb(key, plaintext) print(“Ciphertext:”, ciphertext) decrypted_plaintext = decrypt_ecb(key, ciphertext) print(“Decrypted plaintext:”, decrypted_plaintext.decode(”utf-8”)) Output Ciphertext: b”t”/(*jgx1c<>$>$/##1-**1gMBC@AFGDEZ” Decrypted plaintext: Hello, Tutorialspoint! Drawbacks of ECB Mode The following are some disadvantages of using ECB Mode − ECB does not use chaining or an initialization vector; instead, it uses basic substitution. It is simple to implement because of these features. But this is also its biggest weakness. It is cryptologically weak because two identical blocks of plaintext provide two equally identical blocks of ciphertext. When using identical encryption modes and small block sizes (less than 40 bits), ECB is not recommended. Some words and phrases may appear frequently in the plaintext when block sizes are short. It also means that the same repeating part-blocks of the ciphertext may appear, and that the ciphertext can carry patterns from the same plaintext. When plaintext patterns are easily recognised, hackers have a greater chance of figuring them out and executing a codebook attack. Even though ECB security is not enough, each block”s random pad bits could be added to improve it. Larger blocks (64 bits or more) may have enough entropy, or special characteristics, to prevent a codebook attack. Print Page Previous Next Advertisements ”;

Cryptography – SHA Algorithm

Cryptography – SHA Algorithm ”; Previous Next SHA stands for secure hashing algorithm. Data and certificates are hashed using SHA, a modified version of MD5. A hashing algorithm compresses the input data into a smaller, incomprehensible form using bitwise operations, modular additions, and compression functions. You can be asking if hashing can be hacked or decoded. Hashing is one-way, meaning that once data is hashed, a brute force attack is needed to break the resulting hash digest. This is the primary difference between hashing and encryption. Check out the below image to find out how the SHA algorithm works. Even in the event that a single character changes in the message, SHA is intended to provide a unique hash. Hashing two similar but distinct messages, like “Heaven” and “heaven is different,” is one example. All that differs, however, is one small and one capital letter. SHAs also help to identify any alterations made to the original message. A user can determine whether a single letter has been altered by comparing the hash digests to the original ones, as they will differ significantly. The deterministic nature of SHA is one of their key features. This means that any computer or user can reproduce the hash digest as long as they know the hash algorithm that was used. One of the reasons that all SSL certificates on the Internet must have been hashed using a SHA-2 method is because of the finite nature of SHAs. Types of SHA SHA stands for Secure Hash Algorithm family of cryptographic hash functions. Every SHA type is distinct and comes in a range of numbers. Here are a few common types − SHA-1 − This was the first version of SHA. It is currently believed to be less secure as a result of these weaknesses. SHA-2 − This includes several hash algorithms with different digest sizes, such as SHA-224, SHA-256, SHA-384, and SHA-512. They are more secure than SHA-1 and are frequently used. SHA-3 − The newest member of the SHA family, it was created using different methods than SHA-1 and SHA-2. They include SHA3-224, SHA3-256, SHA3-384, and SHA3-512. Every kind of SHA generates a unique hash value-a fixed-length character string-from the input data. Among other security-related tasks, these hash values are used in the generation of digital signatures and data integrity verification. Features of SHA For cryptography, the Secure Hash Algorithm, or SHA, is useful for several important reasons − Data Integrity − SHA generates a fixed-size hash result (often 160, 256, 384, or 512 bits) from input data of arbitrary size. Since a small change in the input data would produce a significantly different hash value, it can be used to verify the integrity of data. If the hash values match, this suggests that the input data has not been altered. Uniqueness − SHA tries to produce unique hash results for a range of inputs. While it is still theoretically possible, modern SHA versions (such SHA-256 and SHA-3) are meant to reduce the probability of two different inputs producing the same hash value (a collision). Cryptographic Security − Pre-image, second pre-image, collision, and other types of cryptographic attacks are all things that SHA is meant to handle. This means that it will be challenging for an attacker to determine two distinct inputs that result in the same hash value or to reverse-engineer the original input data from its hash value. Efficiency − SHA algorithms can produce hash values quickly, even for huge amounts of input data, because they are computationally efficient. Wide Use − SHA is widely used in a number of security applications, like blockchain technology, digital signatures, message authentication codes (MACs), and password hashing. Implementations So now we will implement SHA Algorithm using Python, Java and C++ − Implement using Python So first we will implement SHA using Python”s hashlib library to calculate SHA hashes for a given input string. Here the specific version of SHA can be chosen as per your requirement. The code using Python is as follows − Example import hashlib def calculate_sha(input_data): sha_hash = hashlib.sha256() # Choose different versions sha1(), sha224(), sha384(), etc. sha_hash.update(input_data.encode(”utf-8”)) return sha_hash.hexdigest() input_data = “Hello, Tutorialspoint!” sha_hash = calculate_sha(input_data) print(“SHA hash:”, sha_hash) Following is the output of the above example − Input/Output SHA hash: caba24f8a70cc24277bffcc27aa952723fbf369f315b9657eebf7c7e42b7a1f9 Implement using Java Now we will implement SHA using Java”s MessageDigest library to calculate SHA hashes for a given input string. The code using Java is given below − Example import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class SHAExample { public static void main(String[] args) { String input = “Hello, Everyone!”; try { MessageDigest shaDigest = MessageDigest.getInstance(“SHA-256”); // Choose different versions like “SHA-1”, “SHA-224”, “SHA-384”, etc. byte[] hashBytes = shaDigest.digest(input.getBytes()); StringBuilder sb = new StringBuilder(); for (byte b : hashBytes) { sb.append(String.format(“%02x”, b)); } String shaHash = sb.toString(); System.out.println(“SHA hash: ” + shaHash); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } } Following is the output of the above example − Input/Output SHA hash: 06b1f0e2138fdb9f0ae8b37cb7a0c77e9e9af1293aa1bfb4d17e57a36542348c Future of Hashing SHA-2 is now the industry standard for hashing algorithms, however SHA-3 may someday overtake it. SHA-3 was released in 2015 by the NIST, which also created SHA-1 and SHA-2. Although, it was never accepted as the industry standard for a number of reasons. When SHA-3 was released, most organisations were already switching from SHA-1 to SHA-2, therefore it made no sense to switch to SHA-3 when SHA-2 was still quite secure. In addition, this is not exactly correct, SHA-3 was seen as being slower than SHA-2. SHA-3 continues to advance with every year, and while it is slower in software, it is faster in hardware when compared to both SHA-1 and SHA-2. Avelanche Effect The hash digest for the original message ”Heaven”, hashed with SHA-1, is “06b73bd57b3b938786daed820cb9fa4561bf0e8e.” The hash digest for the second ”heaven”, similar message hashed using SHA-1 looks like this: “66da9f3b8d9d83f34770a14c38276a69433a535b.” We call this phenomenon the avalanche effect. This effect is crucial to cryptography since it means that any modification to the input

Cryptosystems – Key Generation

Cryptography – Key Generation ”; Previous Next Key Management The administration and security of the keys used to encrypt and decrypt data is referred to as key management. This covers − Generation Storage Distribution Revocation Key Generation People use a variety of online softwares and websites these days to transfer data between locations. Cryptographic-based methods are used in software and applications to protect user data from hackers. The cryptographic algorithm”s foundation is the encryption and decryption procedures, which are executed with the use of a key. While one producing key directly interprets the password, cryptographic methods use automatic key generation that begins with the user”s password. The same key is used by symmetric algorithms for both encryption and decryption. Symmetric algorithms use a second or subsidiary approach for key generation. This key generation mechanism protects the password from several types of key attacks. In cryptography, these keys serve as the means to encode and decode the data. Tools or software designed specifically for generating keys are known as key generators or keygens. What are keys? In cryptography, a key is just a really large number. Cryptography relies strongly on keys, which are used in operations like hashing, encryption, and signing to give desired qualities like authenticity (confirming the source of the information), confidentiality (keeping it hidden), and integrity (preventing it from being altered). The number of binary digits, or “bits,” or 1s and 0s, required to represent a key”s value is how long the key is measured. Typically, keys consist of hundreds or maybe even thousands of bits. This provides a compromise between security and computational speed; if the key is too lengthy, cryptography becomes impractical and if it is too short, it is not secure. Key types Keys in cryptography can be of two types: Symmetric Keys Data is usually encrypted and decrypted using symmetric keys. They function to securely “lock” away information (i.e., encrypt it) so that only the owner of the key may “unlock” (i.e., decrypt it), making them comparable to physical keys. The fact that the same key is used for both encryption and decryption gives rise to the term “symmetric.” Symmetric keys need to be kept secret, long, and random in order to be considered secure, or “strong.” Without this secret key, an attacker is unable to decrypt the data, even if they are aware of the encryption scheme that was used. An attacker cannot guess (or “brute force”) a strong key and a high-quality symmetric encryption method in a reasonable amount of time, not even with a highly powerful computer capable of trying millions of key guesses per second. Used for encrypting and decrypting data. The key is shared by both parties. Asymmetric Keys Asymmetric keys are typically found in pairs, each of which consists of a “public key” and a “private key” that are linked mathematically. The public key is intended for public distribution, while the private key must be kept secret. “Public key cryptography” is made possible by these keys. The data can be encrypted with the help of the public key by anybody, but it can only be decrypted or decoded by the owner of the private key because of the features of asymmetric keys. Sending someone a private message is benificial because all they need is your public key. Sending someone a private message is advantageous since all they need is your public key. Verifying a message”s authenticity also can be executed via asymmetric keys. To create a “digital signature,” the message is first compressed the usage of a device referred to as a “hash function,” and the ensuing “fingerprint” is then encrypted with the private key. Then, all people may additionally fast and without problems decrypt this signature using the sender”s public key to confirm that it produces the equal end result as hashing the message themselves; if not, most effective the owner of the associated personal key can signed it. Key Life−Cycle The period of time from the moment a key is created until it is completely destroyed is referred to as the key life-cycle. Many things can happen to a key in its lifetime. It may be authorised, backed up, shared, or withdrawn. Also, a key can be updated on a regular basis (that is, its value changes even though it logically remains the same with the same meta-data). This is a smart security practice because the longer a key is used, the higher chances that it will be compromised. Generating Symmetric Keys Symmetric keys are often created using random number generators (RNGs) or pseudorandom number generators (PRNGs). To create random numbers, use programming libraries or built-in functions in your programming language of your choice. Make sure that random number creation is secure and unpredictable. Example Here is a simple example of symmetric key generation in Python using the secrets module − This code uses Python”s secrets module to generate cryptographically strong random numbers suited for creating keys. The generate_symmetric_key function produces a random key of a given length in bytes. These keys are very much important for encrypting and decrypting data. For added security, the generated key is displayed in a hexadecimal format, making it difficult for unauthorized parties to interpret. import secrets def generate_symmetric_key(key_length): # Generate a random key with the specified length key = secrets.token_bytes(key_length) return key # Create a symmetric key with a length of 32 bytes (256 bits) key = generate_symmetric_key(32) print(“Symmetric Key:”, key.hex()) Output Symmetric Key: 58441e28a9515d10aa56d7f379e7320922211088a9dcd927278c42dc024d37df Generating Asymmetric Key A public key and a private key are the two linked parts of an asymmetric key. Many cryptographic toolkits contain methods such as RSA and ECC for generating these keys. To create an asymmetric key, you will need a public key and its corresponding private key. While the public key can be shared publicly, the private key must be kept secret. You may use cryptographic libraries, like the cryptography in Python, for asymmetric key generation. Here is an example using RSA − Example This code creates an