PHP加密工具功能对比

```html PHP加密工具功能对比:从mcrypt到sodium

PHP加密工具功能对比:从mcrypt到sodium

PHP 提供了多套加密扩展,但功能定位与安全性差异显著。本文对比三类主流工具:mcrypt(已废弃)、openssl(通用主力)和 sodium(现代首选),助你选择合适方案。

1. mcrypt — 已淘汰,切勿使用

mcrypt 在 PHP 7.1 中被弃用,7.2+ 彻底移除。其 API 设计陈旧、默认不校验完整性,易引发填充预言攻击(Padding Oracle)。

⚠️ 警告:任何新项目都应避免使用 mcrypt;遗留代码请尽快迁移。

2. OpenSSL — 灵活强大,需谨慎配置

openssl_encrypt() 支持 AES-128-CBC、AES-256-GCM 等算法,但需手动处理 IV、密钥派生与认证标签,易出错:

// ✅ 推荐:AES-256-GCM(带认证加密)
$key = openssl_random_pseudo_bytes(32);
$iv = openssl_random_pseudo_bytes(12); // GCM推荐12字节IV
$plaintext = "Hello, secure world!";
$ciphertext = openssl_encrypt($plaintext, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag);

// 解密时必须传入 $tag
$decrypted = openssl_decrypt($ciphertext, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag);
echo $decrypted; // Hello, secure world!

3. Sodium — 简洁安全,默认最佳实践

PHP 7.2+ 内置 sodium 扩展(基于 libsodium),提供「开箱即用」的加密原语。无需手动管理 IV 或认证标签:

// ✅ 推荐:使用 crypto_secretbox(对称加密)
$key = sodium_crypto_secretbox_keygen();
$nonce = sodium_crypto_secretbox_noncegen();
$message = "Secret message";
$ciphertext = sodium_crypto_secretbox($message, $nonce, $key);

// 自动验证并解密
$decrypted = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);
if ($decrypted === false) {
    throw new Exception("Decryption failed!");
}
echo $decrypted; // Secret message

核心功能对比表

特性 OpenSSL Sodium
默认认证加密 ❌ 需显式选 GCM/CCM secretbox / box 均含认证
密钥派生(PBKDF2) hash_pbkdf2() sodium_crypto_pwhash()(抗 GPU 攻击)
密钥交换(X25519) ❌ 不支持 sodium_crypto_box_keypair()
API 安全性 ⚠️ 易误用(如忽略 $tag) ✅ 类型安全、零配置默认安全

结论:新项目请优先选用 sodium——它更简洁、更安全、更现代;openssl 适用于需兼容旧系统或特殊算法(如 RSA-OAEP)的场景。始终避免 mcrypt 及不带认证的 CBC 模式。

🔐 加密不是功能,而是责任。选择工具前,请先理解你的威胁模型。

```