安装库:
composer require “lpilp/guomi”: “^1.0”
- <?php
- namespace app\common\service\crypto;
- class CryptoHelper
- {
- private $privateKeyHex;
- private $desKey;
- private $userInfo;
- // 构造函数,初始化私钥、desKey密钥和userInfo用户信息 privateKeyHex="'12b:d5:65:8d:f1:70:6d:bd:53:47:21:db:de:9a:18:bf:0a:2f:62:1b:b8:30:2b:84:5c:07:38:a0:5c:7d:ce:76';//私钥"
- public function __construct($privateKeyHex, $desKey, $userInfo)
- {
- $privateKeyHex = str_replace(":", "", $privateKeyHex);
- $this->privateKeyHex = $privateKeyHex;
- $this->desKey = $desKey;
- $this->userInfo = $userInfo;
- }
- // 解密用户信息
- public function decryptUserInfo()
- {
- // Step 2: 使用 SM2 解密 DES 密钥
- $sm2 = new SM2($this->privateKeyHex);
- $sm4KeyBytes = $sm2->decrypt($this->desKey,$this->userInfo);
- // Step 3: 使用 SM4 解密 UserInfo
- $sm4 = new SM4($sm4KeyBytes);
- return $sm4->decrypt($this->userInfo);
- }
- }
复制代码 SM2
- <?php
- namespace app\common\service\crypto;
- use Rtgm\sm\RtSm2;
- class SM2
- {
- private $privateKey;
- public function __construct($privateKeyHex)
- {
- $this->privateKey = $privateKeyHex;
- }
- public function decrypt($data, $userInfo)
- {
- // 调用 SM2 解密算法
- return $this->sm2_decrypt($this->privateKey, $data);
- }
- // SM2 解密实现(假设使用 openssl 进行解密)
- private function sm2_decrypt($privateKey, $data)
- {
- $sm2 = new RtSm2('base64', false);
- $m2DecryptData = $sm2->doDecrypt(bin2hex(base64_decode($data)), $privateKey);
- return $m2DecryptData;
- }
- }
复制代码 SM4
- <?php
- namespace app\common\service\crypto;
- use Rtgm\sm\RtSm4;
- class SM4
- {
- private $key;
- public function __construct($key)
- {
- $this->key = $key;
- }
- public function decrypt($data)
- {
- // 调用 SM4 解密算法
- return $this->sm4_decrypt($this->key, $data);
- }
- // SM4 解密实现(假设使用 openssl 实现 AES 解密)
- private function sm4_decrypt($key, $data)
- {
- $sm4 = new RtSm4($key);
- $result = $sm4->decrypt($data, 'sm4-ecb', '', 'base64');
- return $result;
- }
- }
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |