【thinkphp6】国密sm2
一、下载 lpilp/guomi 依赖
composer require lpilp/guomi
二、使用 lpilp/guomi
<?php
namespace app\controller;
use Exception;
use Rtgm\sm\RtSm2;
use Rtgm\sm\RtSm3;
use Rtgm\sm\RtSm4;
class Sm
{
/**
* sm2加密
* @return void
*/
public function sm2(): void
{
// 该密钥对可通过代码生成,亦可通过网站生成
// 生成网站:https://33tool.com/sm2/
$privateKey = 'e1fac6f06ed691da9f74f7a159712e3667d299a7df2e7743404951769188ca90';
$publicKey = '0472100a593eb6d26984123b33a776d4ecf0cd8ea5777aa72835c2797f713cbc13c251d37c403c65424209f9858fedeb509a021e73c9d9d30c6d62a01ebe2baf76';
$sm2 = new RtSm2('base64', false);
$data = 'hello world';
$sm2EncryptData = $sm2->doEncrypt($data, $publicKey);
$sm2DecryptData = $sm2->doDecrypt($sm2EncryptData, $privateKey);
dd([
'encrypt' => $sm2EncryptData,
'decrypt' => $sm2DecryptData,
]);
}
/**
* sm3
* @return void
*/
public function sm3(): void
{
$sm3 = new RtSm3();
$data = 'hello world';
dd($sm3->digest($data));
}
/**
* sm4加密
* @return void
* @throws Exception
*/
public function sm4(): void
{
$key = '0123456789abcdef';
$iv = '1234567887654321';
$sm4 = new RtSm4($key);
$data = 'hello world';
// === sm4-cbc ===
// 加密
$cbcEncryptData = $sm4->encrypt($data, 'sm4', $iv); // sm4默认为cbc模式
// 解密
$cbcDecryptData = $sm4->decrypt($cbcEncryptData, 'sm4', $iv);
// === sm4-ecb ===
// 加密
$ecbEncryptData = $sm4->encrypt($data, 'sm4-ecb', $iv);
// 解密
$ecbDecryptData = $sm4->decrypt($ecbEncryptData, 'sm4-ecb', $iv);
// === sm4-ofb ===
// 加密
$ofbEncryptData = $sm4->encrypt($data, 'sm4-ofb', $iv);
// 解密
$ofbDecryptData = $sm4->decrypt($ofbEncryptData, 'sm4-ofb', $iv);
// === sm4-cfb ===
// 加密
$cfbEncryptData = $sm4->encrypt($data, 'sm4-cfb', $iv);
// 解密
$cfbDecryptData = $sm4->decrypt($cfbEncryptData, 'sm4-cfb', $iv);
// === sm4-ctr ===
// 加密
$ctrEncryptData = $sm4->encrypt($data, 'sm4-ctr', $iv);
// 解密
$ctrDecryptData = $sm4->decrypt($ctrEncryptData, 'sm4-ctr', $iv);
dd([
'sm4-cbc' => [
'encrypt' => $cbcEncryptData,
'decrypt' => $cbcDecryptData,
],
'sm4-ecb' => [
'encrypt' => $ecbEncryptData,
'decrypt' => $ecbDecryptData,
],
'sm4-ofb' => [
'encrypt' => $ofbEncryptData,
'decrypt' => $ofbDecryptData,
],
'sm4-cfb' => [
'encrypt' => $cfbEncryptData,
'decrypt' => $cfbDecryptData,
],
'sm4-ctr' => [
'encrypt' => $ctrEncryptData,
'decrypt' => $ctrDecryptData,
],
]);
}
}

浙公网安备 33010602011771号