php实现扩展加密解密
PHP 实现扩展加密解密的方法
使用 OpenSSL 扩展
OpenSSL 是 PHP 中常用的加密解密扩展,支持多种加密算法(如 AES、DES、RSA 等)。以下是一个使用 AES-256-CBC 加密解密的示例:
$plaintext = "需要加密的数据";
$key = openssl_random_pseudo_bytes(32); // 256位密钥
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
// 加密
$ciphertext = openssl_encrypt($plaintext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
$encrypted = base64_encode($iv . $ciphertext);
// 解密
$decoded = base64_decode($encrypted);
$iv = substr($decoded, 0, openssl_cipher_iv_length('aes-256-cbc'));
$ciphertext = substr($decoded, openssl_cipher_iv_length('aes-256-cbc'));
$decrypted = openssl_decrypt($ciphertext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
使用 Sodium 扩展
Sodium 是一个现代加密库,PHP 7.2+ 内置支持。以下是一个使用 Sodium 加密解密的示例:
$plaintext = "需要加密的数据";
$key = sodium_crypto_secretbox_keygen(); // 生成随机密钥
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
// 加密
$ciphertext = sodium_crypto_secretbox($plaintext, $nonce, $key);
$encrypted = base64_encode($nonce . $ciphertext);
// 解密
$decoded = base64_decode($encrypted);
$nonce = substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$ciphertext = substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$decrypted = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);
使用 Mcrypt 扩展(已弃用)
Mcrypt 是 PHP 早期的加密扩展,但在 PHP 7.1 中已被弃用。以下是一个使用 Mcrypt 的示例(仅作参考):
$plaintext = "需要加密的数据";
$key = md5('secret_key', true); // 生成密钥
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));
// 加密
$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $plaintext, MCRYPT_MODE_CBC, $iv);
$encrypted = base64_encode($iv . $ciphertext);
// 解密
$decoded = base64_decode($encrypted);
$iv = substr($decoded, 0, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));
$ciphertext = substr($decoded, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));
$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $ciphertext, MCRYPT_MODE_CBC, $iv);
使用 Libsodium 扩展
Libsodium 是 Sodium 的前身,需要手动安装。以下是一个使用 Libsodium 的示例:
$plaintext = "需要加密的数据";
$key = sodium_crypto_secretbox_keygen(); // 生成随机密钥
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
// 加密
$ciphertext = sodium_crypto_secretbox($plaintext, $nonce, $key);
$encrypted = base64_encode($nonce . $ciphertext);
// 解密
$decoded = base64_decode($encrypted);
$nonce = substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$ciphertext = substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$decrypted = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);
注意事项
- 密钥管理:密钥应安全存储,避免硬编码在代码中。
- IV/Nonce:每次加密都应使用唯一的 IV 或 Nonce。
- 算法选择:优先使用现代加密算法(如 AES-256、ChaCha20)。
- 错误处理:加密解密操作可能失败,应检查返回值并处理异常。
以上方法提供了 PHP 中常见的加密解密实现方式,开发者可根据项目需求选择合适的扩展和算法。







