mirror of
https://gitee.com/liuxioabin/fengketrade.git
synced 2026-04-17 21:03:17 +08:00
75 lines
1.9 KiB
PHP
75 lines
1.9 KiB
PHP
|
|
<?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);
|
|||
|
|
}
|
|||
|
|
}
|