Files
pgserver3.0/pgserver/application/lib/DesCrypto.php
annnj-company 130c1026c4 first commit
2026-04-17 18:29:53 +08:00

80 lines
2.0 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 app\lib;
class DesCrypto
{
private $key;
private $iv;
/**
* 构造函数(集成固定密钥和向量)
*/
public function __construct($key, $iv)
{
// 使用您提供的固定密钥
$this->key = $this->padToLength($key, 8);
// 使用您提供的固定向量
$this->iv = $this->padToLength($iv, 8);
}
/**
* DES加密CBC模式 + PKCS5Padding
* @param string $data 待加密数据
* @return string Base64编码的加密结果
*/
public function encrypt($data)
{
// 添加PKCS5填充
$blockSize = 8;
$pad = $blockSize - (strlen($data) % $blockSize);
$data .= str_repeat(chr($pad), $pad);
// 执行加密
$encrypted = openssl_encrypt(
$data,
'DES-CBC',
$this->key,
OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING,
$this->iv
);
return base64_encode($encrypted);
}
/**
* DES解密
* @param string $base64Data Base64编码的加密数据
* @return string 解密后的原始数据
*/
public function decrypt($base64Data)
{
$encrypted = base64_decode($base64Data);
// 执行解密
$decrypted = openssl_decrypt(
$encrypted,
'DES-CBC',
$this->key,
OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING,
$this->iv
);
// 移除PKCS5填充
$pad = ord($decrypted[strlen($decrypted) - 1]);
return substr($decrypted, 0, -$pad);
}
/**
* 辅助方法:填充/截断字符串到指定长度
* @param string $str 输入字符串
* @param int $length 目标长度
* @return string 处理后的字符串
*/
private function padToLength($str, $length)
{
if (strlen($str) > $length) {
return substr($str, 0, $length);
}
return str_pad($str, $length, "\0");
}
}