本文目录导读:

我将为您提供一个完整的AES加密案例,包括不同模式的使用方法和代码示例。
AES加密基础示例(Python)
使用pycryptodome库
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
import base64
import os
class AESUtil:
def __init__(self, key):
"""初始化AES工具类
key: 16, 24, 或 32字节的密钥
"""
self.key = key
def encrypt_ecb(self, plaintext):
"""ECB模式加密"""
cipher = AES.new(self.key, AES.MODE_ECB)
padded_data = pad(plaintext.encode('utf-8'), AES.block_size)
encrypted = cipher.encrypt(padded_data)
return base64.b64encode(encrypted).decode('utf-8')
def decrypt_ecb(self, ciphertext):
"""ECB模式解密"""
cipher = AES.new(self.key, AES.MODE_ECB)
encrypted_data = base64.b64decode(ciphertext)
decrypted_padded = cipher.decrypt(encrypted_data)
decrypted = unpad(decrypted_padded, AES.block_size)
return decrypted.decode('utf-8')
def encrypt_cbc(self, plaintext, iv):
"""CBC模式加密"""
cipher = AES.new(self.key, AES.MODE_CBC, iv)
padded_data = pad(plaintext.encode('utf-8'), AES.block_size)
encrypted = cipher.encrypt(padded_data)
return base64.b64encode(encrypted).decode('utf-8')
def decrypt_cbc(self, ciphertext, iv):
"""CBC模式解密"""
cipher = AES.new(self.key, AES.MODE_CBC, iv)
encrypted_data = base64.b64decode(ciphertext)
decrypted_padded = cipher.decrypt(encrypted_data)
decrypted = unpad(decrypted_padded, AES.block_size)
return decrypted.decode('utf-8')
def encrypt_gcm(self, plaintext):
"""GCM模式加密(认证加密)"""
cipher = AES.new(self.key, AES.MODE_GCM)
ciphertext, tag = cipher.encrypt_and_digest(plaintext.encode('utf-8'))
# 组合nonce, ciphertext, tag
result = {
'nonce': base64.b64encode(cipher.nonce).decode('utf-8'),
'ciphertext': base64.b64encode(ciphertext).decode('utf-8'),
'tag': base64.b64encode(tag).decode('utf-8')
}
return result
def decrypt_gcm(self, encrypted_data):
"""GCM模式解密"""
nonce = base64.b64decode(encrypted_data['nonce'])
ciphertext = base64.b64decode(encrypted_data['ciphertext'])
tag = base64.b64decode(encrypted_data['tag'])
cipher = AES.new(self.key, AES.MODE_GCM, nonce=nonce)
decrypted = cipher.decrypt_and_verify(ciphertext, tag)
return decrypted.decode('utf-8')
# 使用示例
def main():
# 生成密钥(16字节 = AES-128, 24字节 = AES-192, 32字节 = AES-256)
key = get_random_bytes(16) # AES-128
aes_util = AESUtil(key)
print("=" * 50)
print("AES加密演示")
print("=" * 50)
# 原始数据
plaintext = "Hello, AES! 这是一个加密测试。"
print(f"原始数据: {plaintext}")
print(f"密钥(hex): {key.hex()}")
print("\n" + "-" * 30)
print("1. ECB模式")
print("-" * 30)
encrypted_ecb = aes_util.encrypt_ecb(plaintext)
decrypted_ecb = aes_util.decrypt_ecb(encrypted_ecb)
print(f"加密结果: {encrypted_ecb}")
print(f"解密结果: {decrypted_ecb}")
print("\n" + "-" * 30)
print("2. CBC模式")
print("-" * 30)
iv = get_random_bytes(16) # 生成16字节的IV
encrypted_cbc = aes_util.encrypt_cbc(plaintext, iv)
decrypted_cbc = aes_util.decrypt_cbc(encrypted_cbc, iv)
print(f"IV(hex): {iv.hex()}")
print(f"加密结果: {encrypted_cbc}")
print(f"解密结果: {decrypted_cbc}")
print("\n" + "-" * 30)
print("3. GCM模式(推荐)")
print("-" * 30)
encrypted_gcm = aes_util.encrypt_gcm(plaintext)
decrypted_gcm = aes_util.decrypt_gcm(encrypted_gcm)
print(f"加密结果: {encrypted_gcm}")
print(f"解密结果: {decrypted_gcm}")
if __name__ == "__main__":
main()
使用cryptography库(更现代)
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend
import os
import base64
class ModernAESUtil:
def __init__(self, key):
self.key = key
self.backend = default_backend()
def encrypt_cbc(self, plaintext):
"""CBC模式加密"""
iv = os.urandom(16)
cipher = Cipher(
algorithms.AES(self.key),
modes.CBC(iv),
backend=self.backend
)
encryptor = cipher.encryptor()
# 添加PKCS7填充
padder = padding.PKCS7(128).padder()
padded_data = padder.update(plaintext.encode('utf-8')) + padder.finalize()
ciphertext = encryptor.update(padded_data) + encryptor.finalize()
# 返回IV和密文
return {
'iv': base64.b64encode(iv).decode('utf-8'),
'ciphertext': base64.b64encode(ciphertext).decode('utf-8')
}
def decrypt_cbc(self, encrypted_data):
"""CBC模式解密"""
iv = base64.b64decode(encrypted_data['iv'])
ciphertext = base64.b64decode(encrypted_data['ciphertext'])
cipher = Cipher(
algorithms.AES(self.key),
modes.CBC(iv),
backend=self.backend
)
decryptor = cipher.decryptor()
padded_data = decryptor.update(ciphertext) + decryptor.finalize()
# 移除填充
unpadder = padding.PKCS7(128).unpadder()
data = unpadder.update(padded_data) + unpadder.finalize()
return data.decode('utf-8')
Node.js AES加密示例
const crypto = require('crypto');
class AESUtil {
constructor(key) {
this.key = Buffer.from(key, 'hex');
}
// AES-256-CBC加密
encryptCBC(plaintext) {
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes-256-cbc', this.key, iv);
let encrypted = cipher.update(plaintext, 'utf8', 'base64');
encrypted += cipher.final('base64');
return {
iv: iv.toString('base64'),
ciphertext: encrypted
};
}
// AES-256-CBC解密
decryptCBC(encryptedData) {
const iv = Buffer.from(encryptedData.iv, 'base64');
const decipher = crypto.createDecipheriv('aes-256-cbc', this.key, iv);
let decrypted = decipher.update(encryptedData.ciphertext, 'base64', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
// AES-256-GCM加密(认证加密)
encryptGCM(plaintext) {
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', this.key, iv);
let encrypted = cipher.update(plaintext, 'utf8', 'base64');
encrypted += cipher.final('base64');
const authTag = cipher.getAuthTag();
return {
iv: iv.toString('base64'),
ciphertext: encrypted,
tag: authTag.toString('base64')
};
}
// AES-256-GCM解密
decryptGCM(encryptedData) {
const iv = Buffer.from(encryptedData.iv, 'base64');
const authTag = Buffer.from(encryptedData.tag, 'base64');
const decipher = crypto.createDecipheriv('aes-256-gcm', this.key, iv);
decipher.setAuthTag(authTag);
let decrypted = decipher.update(encryptedData.ciphertext, 'base64', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
}
// 使用示例
function main() {
// 生成32字节(256位)密钥
const key = crypto.randomBytes(32).toString('hex');
const aesUtil = new AESUtil(key);
const plaintext = "Hello, AES! 这是一个加密测试。";
console.log("原始数据:", plaintext);
// CBC模式
console.log("\n--- CBC模式 ---");
const encryptedCBC = aesUtil.encryptCBC(plaintext);
console.log("加密结果:", encryptedCBC);
console.log("解密结果:", aesUtil.decryptCBC(encryptedCBC));
// GCM模式
console.log("\n--- GCM模式 ---");
const encryptedGCM = aesUtil.encryptGCM(plaintext);
console.log("加密结果:", encryptedGCM);
console.log("解密结果:", aesUtil.decryptGCM(encryptedGCM));
}
main();
文件加密示例
def encrypt_file(input_file, output_file, key):
"""加密文件"""
chunk_size = 64 * 1024 # 64KB
# 生成IV
iv = get_random_bytes(16)
# 创建加密器
cipher = AES.new(key, AES.MODE_CBC, iv)
with open(input_file, 'rb') as infile:
with open(output_file, 'wb') as outfile:
# 写入IV
outfile.write(iv)
while True:
chunk = infile.read(chunk_size)
if len(chunk) == 0:
break
elif len(chunk) % AES.block_size != 0:
# 填充最后一个块
chunk = pad(chunk, AES.block_size)
encrypted_chunk = cipher.encrypt(chunk)
outfile.write(encrypted_chunk)
def decrypt_file(input_file, output_file, key):
"""解密文件"""
chunk_size = 64 * 1024 # 64KB
with open(input_file, 'rb') as infile:
# 读取IV
iv = infile.read(16)
# 创建解密器
cipher = AES.new(key, AES.MODE_CBC, iv)
with open(output_file, 'wb') as outfile:
while True:
chunk = infile.read(chunk_size)
if len(chunk) == 0:
break
decrypted_chunk = cipher.decrypt(chunk)
# 如果是最后一个块,移除填充
if len(chunk) < chunk_size:
decrypted_chunk = unpad(decrypted_chunk, AES.block_size)
outfile.write(decrypted_chunk)
Java AES加密示例
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESExample {
public static void main(String[] args) throws Exception {
// 生成AES密钥
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256); // 256位密钥
SecretKey secretKey = keyGen.generateKey();
String plaintext = "Hello, AES! 这是一个加密测试。";
byte[] keyBytes = secretKey.getEncoded();
// 加密和解密
String encrypted = encrypt(plaintext, keyBytes);
String decrypted = decrypt(encrypted, keyBytes);
System.out.println("原始数据: " + plaintext);
System.out.println("加密结果: " + encrypted);
System.out.println("解密结果: " + decrypted);
}
public static String encrypt(String plaintext, byte[] keyBytes) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec spec = new SecretKeySpec(keyBytes, "AES");
// 生成随机IV
byte[] iv = new byte[16];
new java.security.SecureRandom().nextBytes(iv);
IvParameterSpec ivSpec = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, spec, ivSpec);
byte[] encrypted = cipher.doFinal(plaintext.getBytes("UTF-8"));
// 将IV和密文组合
byte[] result = new byte[iv.length + encrypted.length];
System.arraycopy(iv, 0, result, 0, iv.length);
System.arraycopy(encrypted, 0, result, iv.length, encrypted.length);
return Base64.getEncoder().encodeToString(result);
}
public static String decrypt(String encrypted, byte[] keyBytes) throws Exception {
byte[] data = Base64.getDecoder().decode(encrypted);
// 提取IV
byte[] iv = new byte[16];
System.arraycopy(data, 0, iv, 0, iv.length);
// 提取密文
byte[] ciphertext = new byte[data.length - iv.length];
System.arraycopy(data, iv.length, ciphertext, 0, ciphertext.length);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec spec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, spec, ivSpec);
byte[] decrypted = cipher.doFinal(ciphertext);
return new String(decrypted, "UTF-8");
}
}
最佳实践建议
- 推荐使用GCM模式:GCM提供认证加密,同时保护机密性和完整性
- 密钥管理:使用安全的密钥存储方式(如HSM、密钥保险库)
- 随机性:确保IV和密钥使用安全的随机数生成器
- 版本控制:在密文中加入版本信息和参数标识
- 适用场景:
- CTR/GCM:流数据、大数据量
- CBC:通用场景
- ECB:仅用于单个数据块(不推荐用于多个块)
安全注意事项
- 不要使用ECB模式处理多块数据
- IV不要重复使用(GCM模式下特别重要)
- 使用足够长的密钥(推荐AES-256)
- 密钥应定期更换
- 考虑使用KMIP或类似协议进行密钥管理
这些示例涵盖了AES加密的主要使用方式和场景,您可以根据具体需求选择合适的模式和实现方式。