2025-10-20 09:23:30 +08:00

75 lines
1.9 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace addons\shopro\library\ccblife;
/**
* 纯PHP实现的DES加密/解密类
* 解决OpenSSL 3.x不支持DES算法的问题
*
* 算法DES-ECB模式PKCS5填充
*/
class PhpDes
{
/**
* DES解密
*
* @param string $data 加密的数据(二进制)
* @param string $key 密钥8字节
* @return string|false 解密后的数据
*/
public static function decrypt($data, $key)
{
// 使用mcrypt扩展如果可用
if (function_exists('mcrypt_decrypt')) {
$result = mcrypt_decrypt(MCRYPT_DES, $key, $data, MCRYPT_MODE_ECB);
return self::removePKCS5Padding($result);
}
// 尝试使用phpseclib库
if (class_exists('\phpseclib3\Crypt\DES')) {
$cipher = new \phpseclib3\Crypt\DES('ecb');
$cipher->setKey($key);
$cipher->disablePadding();
$result = $cipher->decrypt($data);
return self::removePKCS5Padding($result);
}
// 都不可用返回false
return false;
}
/**
* 移除PKCS5填充
*
* @param string $text 填充的文本
* @return string|false 移除填充后的文本
*/
private static function removePKCS5Padding($text)
{
if (empty($text) || !is_string($text)) {
return false;
}
$textLength = strlen($text);
if ($textLength === 0) {
return false;
}
$pad = ord($text[$textLength - 1]);
// 验证填充值的合理性
if ($pad > $textLength || $pad > 8 || $pad < 1) {
return false;
}
// 验证所有填充字节是否一致
for ($i = 0; $i < $pad; $i++) {
if (ord($text[$textLength - 1 - $i]) !== $pad) {
return false;
}
}
return substr($text, 0, -1 * $pad);
}
}