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
Category: cryptography
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
Cryptography – Key Generation ”; Previous Next Key Management The administration and security of the keys used to encrypt and decrypt data is referred to as key management. This covers − Generation Storage Distribution Revocation Key Generation People use a variety of online softwares and websites these days to transfer data between locations. Cryptographic-based methods are used in software and applications to protect user data from hackers. The cryptographic algorithm”s foundation is the encryption and decryption procedures, which are executed with the use of a key. While one producing key directly interprets the password, cryptographic methods use automatic key generation that begins with the user”s password. The same key is used by symmetric algorithms for both encryption and decryption. Symmetric algorithms use a second or subsidiary approach for key generation. This key generation mechanism protects the password from several types of key attacks. In cryptography, these keys serve as the means to encode and decode the data. Tools or software designed specifically for generating keys are known as key generators or keygens. What are keys? In cryptography, a key is just a really large number. Cryptography relies strongly on keys, which are used in operations like hashing, encryption, and signing to give desired qualities like authenticity (confirming the source of the information), confidentiality (keeping it hidden), and integrity (preventing it from being altered). The number of binary digits, or “bits,” or 1s and 0s, required to represent a key”s value is how long the key is measured. Typically, keys consist of hundreds or maybe even thousands of bits. This provides a compromise between security and computational speed; if the key is too lengthy, cryptography becomes impractical and if it is too short, it is not secure. Key types Keys in cryptography can be of two types: Symmetric Keys Data is usually encrypted and decrypted using symmetric keys. They function to securely “lock” away information (i.e., encrypt it) so that only the owner of the key may “unlock” (i.e., decrypt it), making them comparable to physical keys. The fact that the same key is used for both encryption and decryption gives rise to the term “symmetric.” Symmetric keys need to be kept secret, long, and random in order to be considered secure, or “strong.” Without this secret key, an attacker is unable to decrypt the data, even if they are aware of the encryption scheme that was used. An attacker cannot guess (or “brute force”) a strong key and a high-quality symmetric encryption method in a reasonable amount of time, not even with a highly powerful computer capable of trying millions of key guesses per second. Used for encrypting and decrypting data. The key is shared by both parties. Asymmetric Keys Asymmetric keys are typically found in pairs, each of which consists of a “public key” and a “private key” that are linked mathematically. The public key is intended for public distribution, while the private key must be kept secret. “Public key cryptography” is made possible by these keys. The data can be encrypted with the help of the public key by anybody, but it can only be decrypted or decoded by the owner of the private key because of the features of asymmetric keys. Sending someone a private message is benificial because all they need is your public key. Sending someone a private message is advantageous since all they need is your public key. Verifying a message”s authenticity also can be executed via asymmetric keys. To create a “digital signature,” the message is first compressed the usage of a device referred to as a “hash function,” and the ensuing “fingerprint” is then encrypted with the private key. Then, all people may additionally fast and without problems decrypt this signature using the sender”s public key to confirm that it produces the equal end result as hashing the message themselves; if not, most effective the owner of the associated personal key can signed it. Key Life−Cycle The period of time from the moment a key is created until it is completely destroyed is referred to as the key life-cycle. Many things can happen to a key in its lifetime. It may be authorised, backed up, shared, or withdrawn. Also, a key can be updated on a regular basis (that is, its value changes even though it logically remains the same with the same meta-data). This is a smart security practice because the longer a key is used, the higher chances that it will be compromised. Generating Symmetric Keys Symmetric keys are often created using random number generators (RNGs) or pseudorandom number generators (PRNGs). To create random numbers, use programming libraries or built-in functions in your programming language of your choice. Make sure that random number creation is secure and unpredictable. Example Here is a simple example of symmetric key generation in Python using the secrets module − This code uses Python”s secrets module to generate cryptographically strong random numbers suited for creating keys. The generate_symmetric_key function produces a random key of a given length in bytes. These keys are very much important for encrypting and decrypting data. For added security, the generated key is displayed in a hexadecimal format, making it difficult for unauthorized parties to interpret. import secrets def generate_symmetric_key(key_length): # Generate a random key with the specified length key = secrets.token_bytes(key_length) return key # Create a symmetric key with a length of 32 bytes (256 bits) key = generate_symmetric_key(32) print(“Symmetric Key:”, key.hex()) Output Symmetric Key: 58441e28a9515d10aa56d7f379e7320922211088a9dcd927278c42dc024d37df Generating Asymmetric Key A public key and a private key are the two linked parts of an asymmetric key. Many cryptographic toolkits contain methods such as RSA and ECC for generating these keys. To create an asymmetric key, you will need a public key and its corresponding private key. While the public key can be shared publicly, the private key must be kept secret. You may use cryptographic libraries, like the cryptography in Python, for asymmetric key generation. Here is an example using RSA − Example This code creates an
Cryptography – MixColumns Transformation ”; Previous Next The AES (Advanced Encryption Standard) algorithm, which uses the MixColumns transformation, is used for both data encryption and decryption. The AES data matrix”s every column is subjected to this mathematical process. How it works? For the MixColumns transformation in AES to work properly, each column of the state matrix needs to undergo a mathematical operation. Polynomial arithmetic in GF(28), an original algebraic field called the Galois Field (GF), forms the fundamental component of this operation. Here is an in−depth description of how it operates − State Matrix Representation − The data being processed is stored in a 4×4 grid called the state matrix. Fixed Matrix − A fixed matrix is used in the MixColumns transformation. This matrix remains same throughout the encryption and decryption procedure. Multiplication Column−wise − Each column of the state matrix is considered a polynomial in GF(2^8). The polynomial is then multiplied by the fixed matrix”s corresponding column. Polynomial Multiplication − When multiplying polynomials in GF(2^8), there are a few rules that must be followed. Firstly, modulo arithmetic must be used with a fixed polynomial called the irreducible polynomial. In the case of AES, this polynomial is x8 + x4 + x3 + x + 1 represented in hexadecimal as 0x11B. XOR Operation − Following the multiplication stage, the results are XORed (exclusively ORed) to produce the final result for each column. Resultant State Matrix − By executing the multiplication and XOR operations for every column, the converted state matrix−which shows the MixColumns transformation−is produced. The data”s diffusion and confusion resulting from this method enhance the encryption process” security. By ensuring that modifications to a single byte in the input data affect numerous bytes in the output, it becomes more challenging for attackers to access and decrypt the encrypted data. Implementation using Python In order to perform the MixColumns transformation on a state matrix, the Python code implements two helper functions: mix_columns and gf_multiply. The state matrix”s columns are converted by combining the bytes in each column with the help of a fixed matrix multiplication at a stage of the AES encryption process called MixColumns. Example def mix_columns(state): fixed_matrix = [ [0x02, 0x03, 0x01, 0x01], [0x01, 0x02, 0x03, 0x01], [0x01, 0x01, 0x02, 0x03], [0x03, 0x01, 0x01, 0x02] ] new_state = [] for col in range(4): new_column = [] for row in range(4): val = 0 for i in range(4): val ^= gf_multiply(fixed_matrix[row][i], state[i][col]) new_column.append(val) new_state.append(new_column) return new_state def gf_multiply(a, b): p = 0 for _ in range(8): if b & 1: p ^= a hi_bit_set = a & 0x80 a <<= 1 if hi_bit_set: a ^= 0x1B # irreducible polynomial b >>= 1 return p if p < 0x80 else p ^ 0x11B # Example usage: state_matrix = [ [0x32, 0x88, 0x31, 0xe0], [0x43, 0x5a, 0x31, 0x37], [0xf6, 0x30, 0x98, 0x07], [0xa8, 0x8d, 0xa2, 0x34] ] new_state = mix_columns(state_matrix) # Displaying output in matrix form for row in new_state: print(row) Following is the output of the above example − Input/Output [484, 6, 101, 424] [67, 506, 318, 232] [11, 322, 214, 421] [170, 424, 414, 120] Implementation using Java The Java implementation”s mixColumns function receives a 4×4 state matrix as input and outputs the modified state matrix following the application of the MixColumns transformation. The gfMultiply function is used to perform polynomial multiplication for each matrix element in GF(2^8). So the code using Java is given below − Example public class MixColumns { public static int[][] mixColumns(int[][] state) { int[][] fixedMatrix = { {0x02, 0x03, 0x01, 0x01}, {0x01, 0x02, 0x03, 0x01}, {0x01, 0x01, 0x02, 0x03}, {0x03, 0x01, 0x01, 0x02} }; int[][] newState = new int[4][4]; for (int col = 0; col < 4; col++) { for (int row = 0; row < 4; row++) { int val = 0; for (int i = 0; i < 4; i++) { val ^= gfMultiply(fixedMatrix[row][i], state[i][col]); } newState[row][col] = val; } } return newState; } public static int gfMultiply(int a, int b) { int p = 0; for (int i = 0; i < 8; i++) { if ((b & 1) != 0) { p ^= a; } int hiBitSet = a & 0x80; a <<= 1; if (hiBitSet != 0) { a ^= 0x1B; // irreducible polynomial } b >>= 1; } return p; } public static void main(String[] args) { int[][] stateMatrix = { {0x32, 0x88, 0x31, 0xe0}, {0x43, 0x5a, 0x31, 0x37}, {0xf6, 0x30, 0x98, 0x07}, {0xa8, 0x8d, 0xa2, 0x34} }; int[][] newState = mixColumns(stateMatrix); // Displaying output in matrix form for (int[] row : newState) { for (int val : row) { System.out.print(String.format(“%02X “, val)); } System.out.println(); } } } Following is the output of the above example − Input/Output FF 158 0B 1B1 11D E1 142 B3 65 13E D6 85 1A8 E8 1A5 163 Implementation using C++ In this implementations we are going to use C++ and we will have a function called mixColumns which takes a 4×4 state matrix as input and returns the transformed state matrix after using the MixColumns transformation. So the code is as follows − Example #include <iostream> #include <vector> int gfMultiply(int a, int b); std::vector<std::vector<int>> mixColumns(std::vector<std::vector<int>> state) { std::vector<std::vector<int>> fixedMatrix = { {0x02, 0x03, 0x01, 0x01}, {0x01, 0x02, 0x03, 0x01}, {0x01, 0x01, 0x02, 0x03}, {0x03, 0x01, 0x01, 0x02} }; std::vector<std::vector<int>> newState(4, std::vector<int>(4, 0)); for (int col = 0; col < 4; col++) { for (int row = 0; row < 4; row++) { int val = 0; for (int i = 0; i < 4; i++) { val ^= gfMultiply(fixedMatrix[row][i], state[i][col]); } newState[row][col] = val; } } return newState; } int gfMultiply(int a, int b) { int p = 0; for (int i = 0; i < 8; i++) { if (b & 1) { p ^= a; } int hiBitSet = a & 0x80; a <<= 1; if (hiBitSet) { a ^= 0x1B; // irreducible polynomial } b >>= 1; } return p; } int main() { std::vector<std::vector<int>> stateMatrix = { {0x32,
Cryptosystems – Dictionary Attack ”; Previous Next What is Dictionary Attack? A dictionary attack occurs when someone tries multiple words from a list such as a dictionary to guess the password. They try different words until they find the right one. It”s like trying to open a lock by trying multiple keys until one works. In other words, a dictionary attack is a type of malicious attack in which hackers who try to guess the password of their online user account by typing common combinations of words, phrases and numbers, can get access to things like social media profiles, even password protected files etc. This is when an attacker can be a real problem for the victim. How does dictionary attack work? This hacking uses a systematic method to crack passwords. Basically, there are three steps to mastering these hacks and understanding them can help in learning how to prevent dictionary attacks − Typically, an attacker will create a custom list of password options-a brute force dictionary-that specifies popular combinations of words and numbers Automated software then uses this brute-force dictionary to try to access online accounts. If a dictionary attack successfully penetrates a vulnerable account, the hacker uses any sensitive data stored in the profile to create his own access. This could be fraud, acting in bad faith, or simply accessing an account to make money. To gather the potential passwords, an attacker will typically use the names of common pets, recognizable pop culture figures, or athletes from major leagues, for example the, because many people use words that make sense to them and they create passwords that are easy to remember. Often, variations of these will be included in the list, such as different combinations of words or the addition of special characters. Building this list with automated tools also makes dictionary attacks easier to succeed. Using a password list and collaboration tools makes it much faster than trying to crack a password and log into an online account. If this were done manually, the attack would take much longer to give the account owner or system administrator time to notice and implement protection against the attack. Because of the methodology, these dictionary attacks rarely have any individual targets. Instead, they work in the hope that one of the passwords on the list will be correct. However, if the attacker is targeting a specific location or organization, a more focused and localized list of terms will be produced. For example, if they plan to invade Spain, they can use standard Spanish words instead of English. Or, if they are targeting a specific organization, they can use words associated with that company. Dictionary Attack vs Brute Force While a dictionary attack is a form of brutal attack, there is an important difference between the two. Whereas dictionary attacks use a fixed set of words to systematically break down a mathematical word, brute force hacks do not use letters but rather, any combination of letters, symbols, and numbers that they are not intentionally passable so that dictionary attacks are often more effective-and more likely to succeed. Since they have far fewer combinations to test. With 26 letters in the alphabet and 10 single numbers 36 digits in all the number of possible combinations for a successful brute force attack is almost impractical. According to the context, a brutal attack on a 10-character input would be in 3.76 squares of possible alphanumeric password runs. However, the advantage of brute force attacks is that their trial and error method often cracks complex and unique passwords because they use such a complete list of possible passwords, so eventually that attack will have the appropriate character combination for a password. How to prevent Dictionary Attacks To prevent dictionary attacks you can − Use Strong and Unique Passwords − Choose passwords that are hard for others to guess, don’t let common words appear in dictionaries. Avoid Easy Passwords − Unexpectedly many people use simple, easy-to-hack word and number combinations as passwords, like “Password123” or “abcd1234”. These are the most vulnerable to hacking since dictionary attacks are specifically designed to crack easy-to-guess passwords. Enable Multi Factor Authentication − This adds an extra layer of security by requiring an additional method of authentication along with your password, such as a code sent to your phone. Limit Login Attempts − Some systems can block or slow down repeated logins after a certain number of failed attempts, making it harder for attackers to guess passwords. Use Account Lockout Policy − Automatically lock out user accounts after multiple unsuccessful login attempts, preventing further review. Update Passwords Regularly − Change your passwords periodically to reduce the chances of long-term guessing. Check for Suspicious Activity − Watch for any unusual login attempts or actions on your accounts and investigate immediately. Forced reset − Dictionary hacking usually relies on repeated attempts to crack a password. Reduce the chances of a successful attack by forcing the password to be reset after a certain number of failed attempts. If this is not an option you can work with on your accounts, you can make it manual by enabling online accounts to send you an email in the event of a failed login attempt, if you are notified if someone is trying to access an account, especially if you receive these notifications in rapid succession You can change the password to ensure it remains secure. Summary Dictionary attacks are a way for hackers to guess a password by trying many words from a list such as a dictionary, until they find the right one. This attack is based on words, phrases, or characters as it is usually used by people as a password. Organizations and individuals can implement several preventive measures to defend against dictionary attacks, such as using strong unique passwords, enabling multi factor authentication, effort to limit access, implement account lockout procedures, regular password updates, monitor suspicious activity, enforce passwords -Enforcement is also configured after a certain amount unsuccessful attempts
Cryptosystems – Key Storage
Cryptography – Key Storage ”; Previous Next In the previous chapter we have learned about cryptographic key generation now in this chapter we are going to discuss about the key storage. Cryptography keys are similar to secret passwords that are used to lock and unlock private data. These keys are used to encrypt data and messages so that only the intended receiver can decrypt and read them when they are sent securely. The act of storing these keys so that only authorised users can access them safely is known as key storage. Keep your keys in a safe place The security of your keys depends on where you keep them. Your keys should be kept in a location with limited access, robust encryption, and isolation from the data they are meant to secure. Among the alternatives are encrypted files or databases, cloud key management services (KMSs), and hardware security modules (HSMs). Additionally, you need to frequently backup your keys and store them somewhere different in case they get lost or damaged. Key Storage Importance The encrypted data is accessible if your keys are stolen by an unauthorised person. Thus, protecting your keys is important for ensuring the integrity and security of your data. It is becoming more and more important to ensure good key management as the use of PKI-based solutions increases. Now let”s examine some other approaches of storing cryptographic keys − Certificate/Key Stores for Operating Systems and Browsers Mac OS Keychain and Windows Certificate Store are two examples. These are locally stored public/private key pairs that are software-based databases included in operating systems and browsers. Widely used for their simple user interface and easy programme interaction. Offers customisation, including the ability to enable backups and robust private key protection. Potential vulnerabilities in even with non-exportability settings and the requirement for robust password security are taken into account. Suitable with programmes like client authentication, SSL certificates for web servers, and digital signing. Files with .pfx and.jks (Keystores) Keypairs are stored in password-protected files using formats like PKCS#12 (.pfx or.p12) and.jks (Java KeyStore). These files allow you to store them anywhere, even on remote servers. Use precaution when limiting access to these files and make sure your passwords are strong. Suitable for uses like secure communications with government services and code signing. Cryptographic Smart Cards and Tokens By keeping private keys on hardware and rendering them non-exportable, we can boost security. Increase security by requiring password authentication for every use. Enable safe operation on several computers without the need for duplicate keys. Usually used for client authentication, code signing, and document signing. The introduction of cryptographic hardware is sometimes driven by compliance requirements, like FIPS. HSM (Hardware Security Modules) Offer automated workflows and hardware-based key storage. Conventional HSMs are physical appliances; similar benefits can be achieved with cloud-based solutions like Microsoft Azure”s Key Vault. Helpful for achieving regulatory requirements and signing large volumes of documents or codes. Able to provide additional features like unique signing identities and be connected with public CAs. Future−Generation Key Storage Techniques The primary storage solutions that were just covered are a little bit conventional and have been around for a while. Key storage is not immune to the Internet of Things” influence, and new solutions are being created in line with this, just like everything else in the field of information security. PKI-based solutions are becoming more and more popular among developers and manufacturers as more devices come online and require secure communication and authentication. This has resulted in new requirements, technologies, and considerations for private key protection. We have seen the two trends listed below. TPM (Trusted Platform Modules) Although TPMs are not new in and of themselves, using them to protect private keys is becoming more and more common. The root key can be protected and additional keys generated by an application can be stored (or wrapped) in a TPM. This is a highly helpful authentication technique for endpoints like laptops, servers, and IoT device manufacturers, since the application keys are not usable without the TPM. Even though TPMs are already standard on a lot of laptops, we have not seen much use of them in the enterprise market. However, they are widely used in the Internet of Things (IoT) as a hardware root of trust for secure device identity. PUF (Physically Unclonable Functions) The technology known as Physical Unclonable Function (PUF) is a paradigm change in key protection. Keys are not kept in storage, where they might be physically attacked, but are generated from specific physical characteristics of a chip”s SRAM memory and are only present when the device is powered on. That is, the private key can be repeatedly created (for the duration of the device) on demand, instead of being safely stored. These are guaranteed to be unique because they make use of the natural randomness in silicon bit patterns and an SRAM-based PUF. When combined with a Trusted Execution Environment (TEE), PUF technology offers an appealing answer to the market”s need for ultra-secure key protection that is affordable and simple to implement. When combined with PKI, PUF offers a complete identity solution. A Compromised Key: What Happens? Any information that a key is protecting may be compromised if it has been hacked (that is, lost, stolen, or broken). This may result in illegal financial transactions or the disclosure of confidential or private information, and other sensitive or valuable data. This can therefore have a negative impact on an organization”s reputation, result in penalties, and ultimately lower the company”s worth or possibly force it out of existence. Because of this, keys need to be handled with the same consideration as the object they are meant to secure. It is essential to quickly revoke and replace a compromised key and conduct an investigation to determine the severity of the harm caused and the system behind the compromise in order to prevent another incident from occurring. Print Page Previous
Base64 Encoding & Decoding
Cryptography – Base64 Encoding & Decoding ”; Previous Next In this chapter, we will see the process of base64 encoding and decoding in Python, from the fundamentals to advanced approaches. So, let”s get started with base64 encoding and decoding. With the help of Base 64, an effective tool, we can transform binary data into a format that allows secure text transmission. So basically Base64 helps us for encoding and changing bytes into ASCII characters. It is useful when you want to send or use data in systems that only handle text. This encoding helps to ensure that the data remains secure and unchanged during transfer. Details of Base64 encoding Base64 refers to a group of related encoding techniques that encode binary data numerically and translate it into a base-64 representation. The word Base64 comes from a specific MIME-content transfer encoding. Design The specific characters used for making up the 64 characters required for Base64 vary for each implementation. The general rule is to select a set of 64 characters that are 1. part of a subset shared by most encodings, and 2. printable. This combination makes it unlikely that the data will be modified while in transit through systems like email, which were previously not 8-bit clean. For example, the first 62 values in MIME”s Base64 implementation are A-Z, a-z, and 0-9, with the final two being “+” and “/”. Other versions, typically derived from Base64, share this attribute but differ in the symbols used for the last two values; for example, the URL and filename safe “RFC 4648 / Base64URL” variant uses “-” and “_”. Base64 has a specific set of characters − 26 Uppercase letters 26 Lowercase letters 10 Numbers Plus sign (+) and slash (/) for new lines It is commonly used in a variety of applications, including email attachments, data transmission via the internet, and storing complex data in simple text formats. Base64 Module of Python The Base64 module in Python provides functions for encoding and decoding data with the help of the Base64 encoding technique. This encoding strategy turns binary data into text format. Below is an overview of the important functions of Base64 − Key Functions of Base64 Sr.No. Function & Description 1 base64.b64encode(s, altchars=None) This function encodes the input bytes-like object s using Base64 and returns the encoded bytes. To generate URL or file system safe Base64 strings, you can supply an alternate set of characters (altchars) to substitute the standard ”+” and ”/” characters. 2 base64.b64decode(s, altchars=None, validate=False) Decodes the Base64 encoded bytes-like object or ASCII string s and returns the decoded bytes. Similar to the b64encode function, you can specify an alternative set of characters (altchars). If characters outside of the Base64 alphabet are present in the input, you can enable validation (validate=True) to report an error. 3 base64.standard_b64encode(s) This function encodes the input bytes-like object s using the standard Base64 alphabet and returns the encoded bytes. 4 base64.standard_b64decode(s) This function decodes the bytes-like object or ASCII string s using the standard Base64 alphabet and returns the decoded bytes. 5 base64.urlsafe_b64encode(s) This function encodes the input bytes-like object s using a URL- and filesystem-safe alphabet, which substitutes ”-” instead of ”+” and ”_” instead of ”/” in the standard Base64 alphabet. The result may still contain ”=”. 6 base64.urlsafe_b64decode(s) This function decodes the bytes-like object or ASCII string s using the URL- and filesystem-safe alphabet and returns the decoded bytes. Implementation using Python Here is how we can do Base64 encoding and decoding in Python − Encoding using Base64 Encoding is the method in which we transform our plaintext in an encrypted form so that the middle person can not understand it. So here i am providing two different methods for encoding using Base64 in Python − Using the base64.b64encode() function In this code, we will explore how to use Python”s base64 module to encode data in a format that can be transmitted or stored in text-based systems. To encode the message, we will use the method base64.b64encode(). This function converts the data into a format that is safe for transmission over systems that handle only text. It is a simple example for understanding the concept of Base64 encoding. Below is the implementation of Base64 encoding using the above function − Example import base64 def base64_encoding(data): encoded_bytes = base64.b64encode(data) encoded_string = encoded_bytes.decode(”utf-8”) return encoded_string #our plain text message data = b”Hello, World!” encoded_data = base64_encoding(data) print(“Our plain text message:”, data) print(“Encoded data using b64encode():”, encoded_data) Following is the output of the above example − Input/Output Our plain text message: b”Hello, World!” Encoded data using b64encode(): SGVsbG8sIFdvcmxkIQ== Using the base64.standard_b64encode() function The code imports the base64 module, which contains functions for encoding and decoding data using the Base64 encoding method. The function encodes the input data with the help of the base64.standard_b64encode() method. This function converts the data into a Base64-encoded format using the standard Base64 alphabet. Below is the Python implementation using standard_b64encode() function − Example import base64 def base64_encoding(data): encoded_bytes = base64.standard_b64encode(data) encoded_string = encoded_bytes.decode(”utf-8”) return encoded_string # Our plaintext example data = b”Hello, Tutorialspoint!” encoded_data = base64_encoding(data) print(“Our plain text message:”, data) print(“Encoded data using standard_b64encode() :”, encoded_data) Following is the output of the above example − Input/Output Our plain text message: b”Hello, Tutorialspoint!” Encoded data using standard_b64encode() : SGVsbG8sIFR1dG9yaWFsc3BvaW50IQ== Using urlsafe_b64encode() In this example, we will use the urlsafe_b64encode() method to return a base64 encoded text designed to use in URLs. This is useful when we need to add binary data in a URL, like a path segment or a query string. Here is the implementation of Base64 encoding using the above function − Example import base64 data = b”Hello, Bharat!” encoded_data = base64.urlsafe_b64encode(data) print(“Our plaintext message: “, data) print(“Encoded data using urlsafe_b64encode(): “, encoded_data) Following is the output of the above example − Input/Output Our plaintext message: b”Hello, Bharat!” Encoded data using urlsafe_b64encode(): b”SGVsbG8sIEJoYXJhdCE=” Decoding using Base64 Decoding is the way of converting encoded or encrypted data back
Cryptography – Key Distribution ”; Previous Next Two parties may exchange cryptographic keys through a procedure known as key exchange, also known as key distribution, in order to use a cryptographic algorithm. For messages to be exchanged via encryption, both the sender and the recipient must be able to encrypt and decrypt them. Depending on the kind of encryption they want to use different technologies are required. Both will need a copy of the same codebook if they use a code. They will need the right keys if they utilise a cipher. Both will require a copy of the same key if the cipher uses symmetric keys. Both parties will need the public key of the other if the key cipher is asymmetric and has the public/private key characteristic. Channel of Distribution Key Distribution is possible in-band or out-of-band. “Channel of distribution” means the way information or keys are swapped between two parties. “Key exchange” is when two parties share secret codes or ”keys” to communicate securely. “In-band” key exchange means the keys are swapped through the same communication channel being used for the actual data. “Out-of-band” key exchange means the keys are shared through a separate, different communication channel from the one used for the actual data. The Key Exchange Problem The goal of the key distribution problem is to safely change the keys so that communications are only read by those who are intended to see them. Messages were encrypted using just one encryption code in the past. But they needed to find a way to pass this key between them so that no one else could figure it out in order to communicate safely. We now have a very advanced technology known as public-key cryptography. It makes use of two keys: a private one that is kept hidden and a public one that is freely shared. Messages can be encrypted with one key and decrypted with another. A well-known technique that allows parties to freely distribute keys without compromising the security of their messages is the Diffie-Hellman key exchange. It is far more secure than exchanging secret codes in the past. Now let us discuss all the problem for key exchange − Symmetric Key Distribution The conventional approach, known as symmetric key distribution, uses a single secret key that is shared by both sides. Before communicating, they exchange this key via a secure channel. Public Key Distribution With this approach, a public key and a private key are given to each users. While the private key is kept confidential, the public key is freely shared. The recipient”s public key is used to encrypt messages, while their private key is used to decrypt them. Diffie−Hellman key exchange Based on ideas created by Ralph Merkle, Martin Hellman”s PhD student, Whitfield Diffie and Hellman published the Diffie−Hellman key exchange (D−H) cryptography protocol in 1976. Users can safely exchange secret keys because of the protocol, even if someone else is keeping an eye on the communication channel. However, authentication-that is, the issue of knowing for sure the true identity of the person or “entity” on the other end of the communication channel-is not addressed by the D−H key exchange protocol on its own. Authentication is important when an adversary can track and modify messages within the communication channel (also known as man-in-the-middle or MITM attacks). Public key infrastructure The issue of identity authentication has been addressed with the proposal of public key infrastructures (PKIs). In their most common application, each user requests for a digital certificate from a “certificate authority” (CA) that is universally trusted. This certificate acts as an immutable means of identity verification for other users. Even in the event that the CA is hacked, the infrastructure is secure. However, a lot of PKIs offer a mechanism to revoke certificates in case such happens, making other users suspicious of them. Certificate revocation lists, against which any certificate can be compared, are often where revoked certificates are stored. Legislation or regulations supporting PKIs have been passed in a number of nations and other jurisdictions, providing these digital certificates with some degree of legal standing. Quantum key exchange The use of unique features of small particles known as quantum physics in quantum key distribution makes secrets highly encrypted. These particles undergo minor modifications as we observe or quantify them. Using this technology, an attempt to track on a discussion between two people will cause the particles to become impacted, notifying us to the possibility of an issue. This technique only functions if Alice and Bob, the individuals, already set up a unique, secure means of communication. Kerberos Protocol The Kerberos protocol is a network authentication system that offers safe communication over insecure networks by using symmetric key cryptography. It distributes session keys and performs user authentication using a reliable third party called the Key Distribution Centre (KDC). Print Page Previous Next Advertisements ”;
Cryptography – Home
Cryptography Tutorial Table of content Cryptography Tutorial Why to Learn Cryptography? Cryptography Applications Who Should Learn Cryptography? Prerequisites to Learn Cryptography FAQs about Cryptography PDF Version Quick Guide Job Search Discussion Cryptography Tutorial The most common method for securing data transmissions in web applications or computer science projects is modern Cryptography. It is like a secret code language that helps to keep information safe. This tutorial covers the basics of the Cryptography. It explains how programmers and network professionals can use cryptography to maintain the privacy of computer data. Starting with the origins of cryptography, it moves on to explain cryptosystems, various traditional and modern ciphers, public key encryption, data integration, message authentication, digital signatures and many more. After finishing this course, you will be able to apply the fundamental principles of Cryptography to practical situations. Why to Learn Cryptography? Imagine that you have got a secret message, and you only want certain people to crack the code. Cryptography comes to the rescue in the digital realm. It is like keeping your message into an unseen envelope that only the designated receiver can open. Learning cryptography makes it fun and hands-on. You can create your own secret codes and understand how to decode others. And, it is a cool skill to have in today”s digital age. Cryptography Applications Cryptography has many practical applications which can be a valuable skill − We can use cryptography for securing communication by encrypting the messages and emails. Secondly we can use it for protecting our data in the applications by securing user data, like passwords and personal information. Also you can secure file storage by securing confidential files and documents. Next we can also use cryptography to secure our E-commerce platforms by securing online transactions and payment information. We can also build blockchain technology by ensuring the security and integrity of transactions in blockchain-based systems. Cryptography can also be used for password protection for storing and managing passwords securely. And the most important thing is digital signatures for verifying the authenticity of digital messages or documents. Who Should Learn Cryptography? Learning about cryptography is useful because you can use it in real life to keep information safe. There are lots of tools and help available for cryptography. If you learn it, you might find good jobs in cybersecurity because many companies need people who know how to keep data safe. This tutorial is meant for students of computer science who aspire to learn the basics of cryptography. It will be helpful for networking professionals as well who would like to incorporate various cryptographic algorithms to ensure secure data communication over their networks. Prerequisites to Learn Cryptography This tutorial has been prepared with the view to make it useful for almost anyone who is curious about cryptography. A basic knowledge of computer science and a secondary level of mathematics knowledge is sufficient to make the most of this tutorial. Throughout this tutorial, you will learn the basics of cryptographic algorithms and its implementation in different languages. This tutorial is designed with an assumption that the user has an understanding of the basics of cryptography algorithms and basic programming knowledge. Cryptography also involves solving problems logically. Develop your logical thinking skills to understand and create secure codes. FAQs about Cryptography Now we will see some frequently asked questions (FAQ) about Cryptography in the below section − What is Cryptography? Cryptography is the technique of concealing or encoding(changing its original form) the information in such a way that only the authenticated person can decode(get the original form) it. This technique of cryptography plays an important role in keeping our data safe. The data or information can be bank cards, computer passwords or online transactions and other private data. Cryptography is very important in this modern world because it helps to protect your digital stuff from hackers by turning information into secret language or code. Which are the commonly used symmetric key algorithms? Mathematicians and cryptographers create symmetric key encryption methods, like AES, with the goal that the ciphertext should be impossible to decrypt without the encryption key. This is true for current secure symmetric encryption algorithms (such as AES and ChaCha20), but it might not be true for other methods (such as DES and RC4), which are regarded as insecure symmetric encryption. RC5, RC6, Camellia, ARIA, IDEA, Serpent, AES, ChaCha20, CAST, Twofish, and CAST are a few popular symmetric encryption algorithms. All of these methods are considered as secure when properly configured and applied. How does asymmetric key cryptography work? Asymmetric-key cryptography is also called Public key cryptography. It is the cryptographic algorithm which uses pairs or related keys; the keys are known as public and private keys. Public key is used to encrypt the data and private key is used to decrypt the data. And both the key pairs are generated using cryptographic algorithms. And the security of public key cryptography depends on keeping the private key secret and the public key can be shared and distributed publicly. How long does it take to learn Cryptography? Although becoming a cryptographer usually requires a lengthy process, the field can pay more than average. An analytical problem-solver with good mathematical and computing abilities could find incredible fulfilment in cryptography. Cryptographers have to keep up with the ever-evolving world of cyberthreats, thus they must regularly refresh their knowledge. The responsibilities of their profession can also vary daily, adding to its dynamic nature. The job can be difficult at times due to the significance of protecting sensitive digital data, as errors can result in breaches of privacy. To help you make a smart decision regarding this career, consider the benefits and drawbacks of being a cryptographer. What are the four purposes of Cryptography? There are form main purpose of cryptography and they are given below − Confidentiality Integrity Authentication Non-repudiation What are the Applications of Cryptography? Here are some applications where we can use cryptography − Authentication Internet of Things Card Payments PC and different passwords