php 实现des加密
DES 加密的实现方法
在 PHP 中实现 DES 加密可以通过 openssl_encrypt 和 openssl_decrypt 函数完成。DES 是一种对称加密算法,密钥长度通常为 8 字节(64 位),但实际有效密钥长度为 56 位。
加密函数示例
function desEncrypt($data, $key) {
$method = 'DES-ECB'; // 使用 ECB 模式
$iv = ""; // ECB 模式不需要 IV
$options = OPENSSL_RAW_DATA;
$encrypted = openssl_encrypt($data, $method, $key, $options, $iv);
return base64_encode($encrypted); // 返回 Base64 编码结果
}
解密函数示例
function desDecrypt($data, $key) {
$method = 'DES-ECB';
$iv = "";
$options = OPENSSL_RAW_DATA;
$decrypted = openssl_decrypt(base64_decode($data), $method, $key, $options, $iv);
return $decrypted;
}
使用示例
$key = '12345678'; // 密钥必须是 8 字节
$plaintext = 'Hello, DES!';
$encrypted = desEncrypt($plaintext, $key);
echo "加密结果: " . $encrypted . "\n";
$decrypted = desDecrypt($encrypted, $key);
echo "解密结果: " . $decrypted . "\n";
注意事项
- DES 密钥长度必须为 8 字节,不足或超过会导致错误。
- ECB 模式安全性较低,建议使用 CBC 模式并配合初始化向量(IV)。
- DES 已被认为不够安全,建议使用更安全的算法如 AES。
使用 CBC 模式的改进版本
function desEncryptCBC($data, $key, $iv) {
$method = 'DES-CBC';
$options = OPENSSL_RAW_DATA;
return base64_encode(openssl_encrypt($data, $method, $key, $options, $iv));
}
function desDecryptCBC($data, $key, $iv) {
$method = 'DES-CBC';
$options = OPENSSL_RAW_DATA;
return openssl_decrypt(base64_decode($data), $method, $key, $options, $iv);
}
$iv = openssl_random_pseudo_bytes(8); // 生成随机 IV
$encrypted = desEncryptCBC($plaintext, $key, $iv);
$decrypted = desDecryptCBC($encrypted, $key, $iv);






