AES加解密
AES对称加密算法,支持多种模式和填充方式,提供加密和解密功能
AES简介
AES(Advanced Encryption Standard,高级加密标准)是一种广泛应用的对称加密算法,支持128、192、256位密钥长度,常用于数据加密传输和存储。常见模式有ECB、CBC等。
算法特点
- 对称加密:加密和解密使用相同的密钥
- 支持多种分组模式(如ECB、CBC)
- 支持多种填充方式
- 高安全性和高性能
常见用途
- 数据加密传输
- 文件加密存储
- 密码保护
- 金融交易安全
代码示例
Python:
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
def aes_encrypt(key, data):
cipher = AES.new(key.encode(), AES.MODE_ECB)
padded_data = pad(data.encode(), AES.block_size)
return cipher.encrypt(padded_data).hex()
def aes_decrypt(key, encrypted_data):
cipher = AES.new(key.encode(), AES.MODE_ECB)
decrypted_data = cipher.decrypt(bytes.fromhex(encrypted_data))
return unpad(decrypted_data, AES.block_size).decode()
Java:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESExample {
public static String encrypt(String key, String data) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes()));
}
public static String decrypt(String key, String encryptedData) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(encryptedData)));
}
}
JavaScript:
const CryptoJS = require('crypto-js');
function aesEncrypt(key, data) {
return CryptoJS.AES.encrypt(data, key).toString();
}
function aesDecrypt(key, encryptedData) {
const bytes = CryptoJS.AES.decrypt(encryptedData, key);
return bytes.toString(CryptoJS.enc.Utf8);
}
PHP:
function aesEncrypt($key, $data) {
return openssl_encrypt($data, 'AES-128-ECB', $key, 0);
}
function aesDecrypt($key, $encryptedData) {
return openssl_decrypt($encryptedData, 'AES-128-ECB', $key, 0);
}
注意事项
- AES密钥长度必须为16/24/32位
- 加密和解密必须使用相同的密钥、模式和填充方式
- 请妥善保管密钥,密钥泄露将导致数据被破解