php aes加密解密是PHP开发者在构建安全应用时必须掌握的核心技能之一。AES(Advanced Encryption Standard,高级加密标准)作为全球广泛采用的对称加密算法,以其高强度、高效率、标准化程度高等优势,成为数据保护的基石技术。在Web开发中,无论是用户密码存储、敏感信息传输、API参数加密,还是数据库字段加密,php aes加密解密能力都直接影响系统的安全纵深与合规性。
值得注意的是,AES本身是一种算法规范,其安全性高度依赖于具体实现细节。许多开发者仅调用openssl_encrypt()或mcrypt_encrypt()(已废弃)等函数,却忽略了初始化向量(IV)、填充模式、密钥派生、编码格式等关键环节,导致实际应用中存在严重安全隐患。例如,重复使用相同IV、硬编码密钥、使用ECB模式加密、未验证完整性等,均可能造成数据泄露或被暴力破解。
在《网络安全法》《个人信息保护法》《数据安全法》等法规日益严格的背景下,php aes加密解密已不仅是技术问题,更关乎企业合规底线。例如,医疗、金融、教育等行业对用户隐私数据加密存储有明确要求,未按规范实现AES加密可能导致重大法律风险。
本指南将系统梳理AES加密解密的技术细节,从原理到实践,从基础到进阶,帮助开发者构建安全、高效、可维护的加密体系。
AES由Joan Daemen和Vincent Rijmen设计,于2001年被美国国家标准与技术研究院(NIST)采纳为FIPS PUB 197标准。其前身是Rijndael算法,支持128/192/256位密钥长度,但AES标准仅固定分组大小为128位(16字节),密钥长度可选128/192/256位。
核心加密过程包括以下轮变换(以AES-128为例):
轮数取决于密钥长度:AES-128为10轮,AES-192为12轮,AES-256为14轮。轮密钥通过密钥扩展算法从主密钥生成,确保每轮使用不同子密钥。
由于AES是分组加密算法,明文长度需为16字节的整数倍。因此需使用填充(Padding)机制:
分组模式(Block Cipher Mode)决定如何将明文分组加密:
| 模式 | 特点 | 是否需要IV | 推荐场景 | 风险提示 |
|---|---|---|---|---|
| ECB | 电子密码本,分组独立加密 | 否 | 不推荐 | 相同明文块加密结果相同,暴露数据模式 |
| CBC | 密码分组链接,前一密文块与当前明文块异或 | 是(必须随机) | 通用加密 | 需防填充预言机攻击(Padding Oracle) |
| CFB | 密码反馈,将密文反馈至移位寄存器 | 是 | 流式加密 | 错误传播:单字节错误影响后续分组 |
| OFB | 输出反馈,内部状态与密钥独立 | 是 | 流式加密 | 重复IV导致密钥流重复 |
| GCM | 伽罗瓦计数器,提供认证加密(AEAD) | 是(唯一性要求极高) | 高安全场景 | IV复用将导致密钥泄露 |
php aes加密解密实践中,CBC与GCM模式最为常用。GCM支持认证加密(Authenticated Encryption with Associated Data, AEAD),同时提供机密性与完整性校验,是现代应用的首选方案。
密钥是AES安全性的核心。密钥长度直接影响抗暴力破解能力:
安全密钥管理原则:
random_bytes())OpenSSL是PHP中最可靠的加密扩展,支持AES-GCM等现代模式:
【示例】AES-256-CBC加密解密
<?php
function encryptAesCbc($plaintext, $key, $iv) {
$cipher = 'AES-256-CBC';
$options = OPENSSL_RAW_DATA;
// 验证密钥长度(32字节=256位)
if (strlen($key) !== 32) {
throw new InvalidArgumentException('Key must be 256 bits (32 bytes)');
}
// 验证IV长度(16字节=128位)
if (strlen($iv) !== 16) {
throw new InvalidArgumentException('IV must be 128 bits (16 bytes)');
}
$ciphertext = openssl_encrypt($plaintext, $cipher, $key, $options, $iv);
if ($ciphertext === false) {
throw new RuntimeException('Encryption failed: ' . openssl_error_string());
}
// 返回base64编码的IV + 密文
return base64_encode($iv . $ciphertext);
}
function decryptAesCbc($encrypted, $key) {
$cipher = 'AES-256-CBC';
$options = OPENSSL_RAW_DATA;
$data = base64_decode($encrypted, true);
if ($data === false) {
throw new InvalidArgumentException('Invalid base64 data');
}
// 提取IV和密文
$iv = substr($data, 0, 16);
$ciphertext = substr($data, 16);
if (strlen($iv) !== 16) {
throw new InvalidArgumentException('Invalid IV length');
}
$plaintext = openssl_decrypt($ciphertext, $cipher, $key, $options, $iv);
if ($plaintext === false) {
throw new RuntimeException('Decryption failed: ' . openssl_error_string());
}
return $plaintext;
}
// 使用示例
$key = random_bytes(32); // 生成256位密钥
$iv = random_bytes(16); // 生成128位IV
$original = '敏感数据:身份证号110101199003072316';
$encrypted = encryptAesCbc($original, $key, $iv);
$decrypted = decryptAesCbc($encrypted, $key);
echo "原文: $original\n";
echo "密文: $encrypted\n";
echo "解密: $decrypted\n";
?>
【关键细节】
random_bytes()生成加密安全随机数,禁止使用rand()或mt_rand()OPENSSL_RAW_DATA选项,避免自动base64编码GCM模式提供机密性+完整性校验,是现代应用的首选:
【示例】AES-256-GCM加密解密(需PHP 7.1+)
<?php
function encryptAesGcm($plaintext, $key, $iv) {
$cipher = 'AES-256-GCM';
$options = 0;
$tagLength = 16; // 认证标签长度(12-16字节)
if (strlen($key) !== 32) {
throw new InvalidArgumentException('Key must be 256 bits (32 bytes)');
}
// GCM要求IV为12字节(96位),RFC推荐值
if (strlen($iv) !== 12) {
throw new InvalidArgumentException('IV must be 96 bits (12 bytes) for GCM');
}
$ciphertext = openssl_encrypt(
$plaintext,
$cipher,
$key,
$options,
$iv,
$tag,
'', // AAD(关联数据)
$tagLength
);
if ($ciphertext === false) {
throw new RuntimeException('Encryption failed: ' . openssl_error_string());
}
// 返回IV + 标签 + 密文(按RFC 8452格式)
return base64_encode($iv . $tag . $ciphertext);
}
function decryptAesGcm($encrypted, $key) {
$cipher = 'AES-256-GCM';
$options = 0;
$data = base64_decode($encrypted, true);
if ($data === false) {
throw new InvalidArgumentException('Invalid base64 data');
}
// 提取IV、标签、密文
$iv = substr($data, 0, 12);
$tag = substr($data, 12, 16);
$ciphertext = substr($data, 28);
if (strlen($iv) !== 12 || strlen($tag) !== 16) {
throw new InvalidArgumentException('Invalid IV or tag length');
}
$plaintext = openssl_decrypt(
$ciphertext,
$cipher,
$key,
$options,
$iv,
$tag,
'', // AAD
16
);
if ($plaintext === false) {
throw new RuntimeException('Decryption failed: ' . openssl_error_string());
}
return $plaintext;
}
// 使用示例
$key = random_bytes(32);
$iv = random_bytes(12); // GCM固定12字节IV
$original = '支付密码:888888';
$encrypted = encryptAesGcm($original, $key, $iv);
$decrypted = decryptAesGcm($encrypted, $key);
echo "原文: $original\n";
echo "密文: $encrypted\n";
echo "解密: $decrypted\n";
?>
用户密码通常不足256位且熵值低,需通过密钥派生函数(KDF)生成AES密钥:
【示例】使用PBKDF2派生AES密钥
<?php
function deriveKeyFromPassword($password, $salt, $keyLength = 32) {
// 使用SHA-256的PBKDF2
$key = hash_pbkdf2('sha256', $password, $salt, 100000, $keyLength, true);
if ($key === false) {
throw new RuntimeException('Key derivation failed');
}
return $key;
}
// 使用示例
$password = 'MySecurePassword123!';
$salt = random_bytes(16); // 每个用户应有唯一盐值
$key = deriveKeyFromPassword($password, $salt);
// 保存salt到数据库(与加密数据关联)
// 实际应用中salt需与密文一起存储
echo "派生密钥(32字节): " . bin2hex($key) . "\n";
?>
【最佳实践】
典型场景:加密用户身份证号、银行卡号、手机号等PII数据,防止数据库泄露导致大规模数据泄露。
【示例】数据库字段加密存储类
<?php
class AesEncryptor {
private $key;
private $cipher = 'AES-256-CBC';
public function __construct($key) {
if (strlen($key) !== 32) {
throw new InvalidArgumentException('Key must be 32 bytes');
}
$this->key = $key;
}
public function encrypt($data) {
$iv = random_bytes(16);
$encrypted = openssl_encrypt($data, $this->cipher, $this->key, OPENSSL_RAW_DATA, $iv);
if ($encrypted === false) {
throw new RuntimeException('Encryption failed');
}
return base64_encode($iv . $encrypted);
}
public function decrypt($encryptedData) {
$data = base64_decode($encryptedData, true);
if ($data === false) {
throw new InvalidArgumentException('Invalid base64 data');
}
$iv = substr($data, 0, 16);
$ciphertext = substr($data, 16);
$decrypted = openssl_decrypt($ciphertext, $this->cipher, $this->key, OPENSSL_RAW_DATA, $iv);
if ($decrypted === false) {
throw new RuntimeException('Decryption failed');
}
return $decrypted;
}
}
// 使用示例
try {
// 从环境变量或密钥管理服务获取密钥
$key = hex2bin('0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef');
$encryptor = new AesEncryptor($key);
// 加密存储
$userId = 12345;
$idCard = '110101199003072316';
$encryptedIdCard = $encryptor->encrypt($idCard);
// 保存到数据库(字段类型:TEXT/BLOB)
// INSERT INTO users (id, encrypted_id_card) VALUES (?, ?)
// 查询时解密
// $decryptedIdCard = $encryptor->decrypt($encryptedIdCardFromDb);
} catch (Exception $e) {
error_log('Encryption error: ' . $e->getMessage());
}
?>
【注意事项】
场景:防止中间人攻击窃取API请求参数(如转账金额、接收方账户)。
【示例】API请求加密传输协议
<?php
// 客户端加密请求
function buildEncryptedRequest($payload, $publicKey, $aesKey) {
// 1. 生成随机AES密钥(会话密钥)
if ($aesKey === null) {
$aesKey = random_bytes(32);
}
// 2. 使用AES加密请求体
$iv = random_bytes(16);
$encryptedData = openssl_encrypt(
json_encode($payload),
'AES-256-CBC',
$aesKey,
OPENSSL_RAW_DATA,
$iv
);
// 3. 使用RSA公钥加密AES密钥
openssl_public_encrypt($aesKey, $encryptedAesKey, $publicKey);
// 4. 构建协议包
return base64_encode($iv . $encryptedAesKey . $encryptedData);
}
// 服务端解密请求
function decryptRequest($encryptedRequest, $privateKey) {
$data = base64_decode($encryptedRequest, true);
// 提取IV(16字节)、加密后的AES密钥(RSA密钥长度)、密文
$iv = substr($data, 0, 16);
$rsaKeySize = 256; // RSA-2048加密后长度
$encryptedAesKey = substr($data, 16, $rsaKeySize);
$ciphertext = substr($data, 16 + $rsaKeySize);
// 1. 使用RSA私钥解密AES密钥
openssl_private_decrypt($encryptedAesKey, $aesKey, $privateKey);
// 2. 使用AES密钥解密数据
$decrypted = openssl_decrypt($ciphertext, 'AES-256-CBC', $aesKey, OPENSSL_RAW_DATA, $iv);
return json_decode($decrypted, true);
}
// 使用示例
$publicKey = openssl_pkey_get_public(file_get_contents('public.pem'));
$privateKey = openssl_pkey_get_private(file_get_contents('private.pem'), 'key_password');
$request = ['amount' => 999.99, 'to_account' => '6222080200123456789'];
$encrypted = buildEncryptedRequest($request, $publicKey, null);
$decrypted = decryptRequest($encrypted, $privateKey);
print_r($decrypted); // 输出原始请求数据
?>
【关键设计】
在CBC模式下,重复使用相同IV会导致相同明文块加密结果相同,攻击者可推断数据模式。例如:
【错误示例】
$iv = '0000000000000000'; // 固定IV = 严重漏洞!
【正确做法】
当解密失败时返回详细错误信息(如"Invalid padding"),攻击者可通过观察响应差异逐步破解明文。
【危险响应】
Decryption failed: Wrong last 2 bytes
【安全实践】
将密钥写入源码或配置文件是高危行为:
【错误示例】
$key = 'my-secret-key-123!'; // 硬编码密钥 = 重大漏洞!
【正确做法】
mcrypt扩展自PHP 7.1起废弃,7.2移除,继续使用将导致兼容性问题:
【过时代码】
// mcrypt_encrypt() 已废弃!
$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);
【迁移建议】
对大量小数据加密时,避免循环调用加密函数,改用批量处理:
【优化方案】
// ❌ 低效:循环加密1000条记录
foreach ($records as $record) {
$encrypted = encryptAesCbc($record['data'], $key, $iv);
}
// ✅ 高效:合并加密(需设计数据结构)
$batch = json_encode(array_column($records, 'data'));
$encryptedBatch = encryptAesCbc($batch, $key, $iv);
【注意】批量加密需设计解密后的数据映射逻辑,适用于日志归档等场景。
加密大文件时避免一次性加载全部数据:
【示例】流式加密大文件
<?php
function encryptFileStream($inputFile, $outputFile, $key) {
$cipher = 'AES-256-CBC';
$iv = random_bytes(16);
$options = OPENSSL_RAW_DATA;
$cipherCtx = openssl_encrypt_init($cipher, $key, $iv, $options);
$inHandle = fopen($inputFile, 'rb');
$outHandle = fopen($outputFile, 'wb');
// 写入IV
fwrite($outHandle, $iv);
// 流式读取加密
while (!feof($inHandle)) {
$chunk = fread($inHandle, 8192);
$encryptedChunk = openssl_encrypt_update($cipherCtx, $chunk);
fwrite($outHandle, $encryptedChunk);
}
// 完成加密
$finalChunk = openssl_encrypt_final($cipherCtx);
fwrite($outHandle, $finalChunk);
fclose($inHandle);
fclose($outHandle);
}
?>
对固定数据(如配置项)可预加密并缓存结果:
php aes加密解密与RSA常组合使用(混合加密):
| 特性 | AES | RSA |
|---|---|---|
| 加密速度 | 快(100x+ RSA) | 慢 |
| 密钥长度 | 短(128/256位) | 长(2048/4096位) |
| 适用场景 | 大文件加密 | 密钥交换、小数据加密 |
| 对称性 | 对称加密 | 非对称加密 |
【典型协作流程】
常见误区:将AES加密用于密码存储(如openssl_encrypt($password, ...))
【严重错误】
密码应使用单向哈希(如bcrypt、Argon2),不可逆!
【正确实践】
password_hash() + password_verify()不同行业对加密有特定要求:
| 库/扩展 | 支持算法 | PHP版本 | 推荐度 |
|---|---|---|---|
| OpenSSL | AES, RSA, ChaCha20... | 5.0+ | ★★★★★ |
| Sodium | ChaCha20-Poly1305, AES-GCM... | 7.2+ | ★★★★☆ |
| libsodium | Sodium子集 | 需安装扩展 | ★★★★☆ |
| mcrypt | 已废弃 | ≤7.1 | ★★☆☆☆ |
【Sodium推荐用法】
<?php
// 加密
$nonce = random_bytes(SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES);
$ciphertext = sodium_crypto_aead_encrypt($plaintext, $additional_data, $nonce, $key);
// 解密
$plaintext = sodium_crypto_aead_decrypt($ciphertext, $additional_data, $nonce, $key);
?>
实施AES加密前,请确认以下要点:
random_bytes())