AES Encryption and Decryption
AES (Advanced Encryption Standard) is a symmetric key encryption algorithm widely used for securing data. It works by encrypting and decrypting data using a single key. AES can operate on different block sizes (e.g., 128, 192, or 256 bits), but the most commonly used key size is 256 bits.
How AES Works
Encryption: AES takes plain text (data to be encrypted) and a key (secret key) as inputs, and it generates ciphertext (encrypted data) as the output.
Decryption: The decryption process takes the ciphertext and the same secret key as input and returns the original plain text.
AES Key Sizes:
AES-128: 128-bit key (16 bytes)
AES-192: 192-bit key (24 bytes)
AES-256: 256-bit key (32 bytes)
AES Encryption and Decryption Example
Here's how to implement AES encryption and decryption in various programming languages:
1. Python (AES Encryption and Decryption)
In Python, we can use the pycryptodome library to perform AES encryption and decryption. Install the library using pip install pycryptodome.
Example:
python
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import os
# Generate a random 256-bit key
key = os.urandom(32) # 256 bits (32 bytes)
# Input plain text
plaintext = b"Hello, this is a secret message!"
# AES Encryption
cipher = AES.new(key, AES.MODE_CBC)
ciphertext = cipher.encrypt(pad(plaintext, AES.block_size))
# Store the IV (Initialization Vector) along with the ciphertext for decryption
iv = cipher.iv
print(f"Ciphertext: {ciphertext.hex()}")
print(f"IV: {iv.hex()}")
# AES Decryption
cipher_decrypt = AES.new(key, AES.MODE_CBC, iv)
decrypted = unpad(cipher_decrypt.decrypt(ciphertext), AES.block_size)
print(f"Decrypted Text: {decrypted.decode()}")
Explanation:
AES.new(key, AES.MODE_CBC): Creates a new AES cipher object using the given key and CBC mode (Cipher Block Chaining).
pad and unpad: Used to ensure the plaintext is a multiple of the AES block size (16 bytes).
cipher.iv: The Initialization Vector (IV) is needed for decryption, so it's saved along with the ciphertext.
Decryption: The same key and IV are used for decryption to recover the original plaintext.
2. JavaScript (AES Encryption and Decryption)
In JavaScript, you can use the Web Crypto API or crypto-js library for AES encryption and decryption. Here's an example using the crypto-js library.
Install crypto-js:
bash
npm install crypto-js
Example:
javascript
const CryptoJS = require("crypto-js");
// Key and IV for AES encryption (256-bit key)
const key = CryptoJS.enc.Utf8.parse('12345678901234567890123456789012'); // 32 bytes (256-bit)
const iv = CryptoJS.enc.Utf8.parse('1234567890123456'); // 16 bytes (128-bit)
const plaintext = "Hello, this is a secret message!";
// AES Encryption
const encrypted = CryptoJS.AES.encrypt(plaintext, key, { iv: iv });
console.log("Encrypted:", encrypted.toString());
// AES Decryption
const bytes = CryptoJS.AES.decrypt(encrypted.toString(), key, { iv: iv });
const decrypted = bytes.toString(CryptoJS.enc.Utf8);
console.log("Decrypted:", decrypted);
Explanation:
CryptoJS.AES.encrypt(): Encrypts the plaintext with the AES algorithm using the provided key and IV.
CryptoJS.AES.decrypt(): Decrypts the ciphertext back to plaintext.
3. Java (AES Encryption and Decryption)
In Java, you can use the javax.crypto library to perform AES encryption and decryption.
Example:
java
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.util.Base64;
public class AESExample {
public static void main(String[] args) throws Exception {
String plaintext = "Hello, this is a secret message!";
// Generate AES Key
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256); // AES-256
SecretKey key = keyGen.generateKey();
// Generate AES IV
byte[] iv = new byte[16];
IvParameterSpec ivSpec = new IvParameterSpec(iv);
// Encrypt the text
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
byte[] ciphertext = cipher.doFinal(plaintext.getBytes());
// Output the ciphertext as a Base64-encoded string
String encryptedText = Base64.getEncoder().encodeToString(ciphertext);
System.out.println("Encrypted Text: " + encryptedText);
// Decrypt the text
cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
byte[] decrypted = cipher.doFinal(ciphertext);
// Output the decrypted text
String decryptedText = new String(decrypted);
System.out.println("Decrypted Text: " + decryptedText);
}
}
Explanation:
KeyGenerator.getInstance("AES"): Generates an AES key.
Cipher.getInstance("AES/CBC/PKCS5Padding"): Initializes the cipher in AES CBC mode with padding.
Base64.getEncoder().encodeToString(ciphertext): Encodes the ciphertext as a Base64 string for easy transmission.
4. PHP (AES Encryption and Decryption)
In PHP, you can use the openssl extension for AES encryption and decryption.
Example:
php
<?php
$plaintext = "Hello, this is a secret message!";
$key = "12345678901234567890123456789012"; // 32 bytes (256-bit key)
$iv = "1234567890123456"; // 16 bytes (128-bit)
// AES Encryption
$ciphertext = openssl_encrypt($plaintext, "aes-256-cbc", $key, 0, $iv);
echo "Encrypted Text: " . $ciphertext . "<br>";
// AES Decryption
$decrypted = openssl_decrypt($ciphertext, "aes-256-cbc", $key, 0, $iv);
echo "Decrypted Text: " . $decrypted;
?>
Explanation:
openssl_encrypt(): Encrypts the plaintext using AES-256-CBC.
openssl_decrypt(): Decrypts the ciphertext back to plaintext.
Key Points
Symmetric Encryption: AES is symmetric, meaning the same key is used for both encryption and decryption.
Block Cipher: AES operates on blocks of data (128 bits), so padding is necessary for data that isn't a multiple of the block size.
Modes of Operation: Common modes of AES include CBC (Cipher Block Chaining), ECB (Electronic Codebook), and GCM (Galois/Counter Mode). CBC is generally recommended for added security.
Why Use AES Encryption?
Security: AES is widely regarded as secure and efficient. It's used in many security protocols like TLS, VPNs, disk encryption, etc.
Performance: AES is fast, efficient, and suitable for encrypting large amounts of data.
Standardization: AES is the industry standard for encryption and is implemented in many systems worldwide.