应用范围及描述

算法类型 国密算法 应用范围及描述
对称加密 SM1 128位数据加密,算法不公开,仅以IP核的形式存在于芯片中。智能IC卡、智能密码钥匙、加密卡、加密机。
非对称加密 SM2 被用来替换RSA算法。常用于身份认证,数据签名,密码交换,256位椭圆曲线。
完整性运算 SM3 256位数据摘要计算,相当于SHA256,数字签名及验证、消息认证码生成及验证、随机数生成
对称加密 SM4 128位数据加密,相当于AES(128)

相关代码

php sm2 sm3 sm4 完整测试类,可拖入 laravel unit test 模块运行。基于扩展包 [ lpilp/guomi ] , sm2 与兴业银行有部分区别,sm4 已互通,未做招行验证。

sm2 密钥长度一般为 128 或 130 位,部分使用压缩密钥长度为 66,也就是将密钥分成 x、y,y是偶数就是02,y是奇数就是03,通过 x 可以算出 y。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
<?php

namespace Tests\Unit;

use FG\ASN1\ASNObject;
use FG\ASN1\Exception\ParserException;
use Mdanter\Ecc\Crypto\Signature\Signature;
use Mdanter\Ecc\Serializer\Signature\DerSignatureSerializer;
use PHPUnit\Framework\TestCase;
use Rtgm\sm\RtSm2;
use Rtgm\sm\RtSm3;
use Rtgm\sm\RtSm4;

/**
* 国密加密测试
* sm4 已与兴业银行调通
*/
class GmTest extends TestCase
{


/**
* 获取 sm2
* @return RtSm2
*/
private function getSm2(): RtSm2
{
return new RtSm2('base64');
}

/**
* 获取 sm3
* @return RtSm3
*/
private function getSm3(): RtSm3
{
return new RtSm3();
}

/**
* 获取 sm4
* @return RtSm4
*/
private function getSm4(): RtSm4
{
$privateKey = $this->getSm4PrivateKey();

return new RtSm4($privateKey);
}

/**
* 获取 16进制 sm2 密钥
* 生成于工具站 https://www.lzltool.com/SM2 base64格式
* @return string
*/
private function getSm2PrivateKey(): string
{
return bin2hex(base64_decode('L8TbMByc+rQmKECWMBjnDQHrXrExqZKdl5S6sBbP07M='));
}

/**
* 获取 16进制 sm2 公钥
* 生成于工具站 https://www.lzltool.com/SM2 base64格式
* @return string
*/
private function getSm2PublicKey(): string
{
return bin2hex(base64_decode('BCxc4cDX1OQEpCD8O7wzPhTOljYg0uzfsMAEanCvYgBIj966+i5pgjwyIOtFSNWLWjoDzLmMJP9nf2cVmiH+aYI='));
}

/**
* sm2 数据格式化
* @param $dec
* @return string
*/
private function sm2FormatHex($dec): string
{
$hex = gmp_strval(gmp_init($dec, 10), 16);
$len = strlen($hex);
if ($len == 64) {
return $hex;
}

return $len < 64 ? str_pad($hex, 64, "0", STR_PAD_LEFT) : substr($hex, $len - 64, 64);
}

/**
* 获取 16位 密钥
* @return bool|string
*/
private function getSm4PrivateKey(): bool|string
{
return base64_decode('NmQzZDQ2YTcxMmRjNGE0NQ==');
}


/**
* 获取待加密字符串
* @return string
*/
private function getDataStr(): string
{
return '{"bankCardNo":"6212028190240439021","certNo":"41052619700925136X","userName":"南瓜"}';
}

/**
* 拼接 sm2 待加密字符串
* @return bool|string
*/
private function getSm2SignStr(): bool|string
{
$params = json_decode($this->getDataStr(), true);
$signStr = '';
if ($params != null) {
ksort($params);
foreach ($params as $k => $v) {
$signStr .= "{$k}={$v}&";
}
}
return substr($signStr, 0, strlen($signStr) - 1);
}

public function test_sm2_sign()
{
$sm2 = $this->getSm2();

$signStr = $this->getSm2SignStr();

// 加密
$sign = $sm2->doSign($signStr, $this->getSm2PrivateKey());
$encryptStr = base64_decode($sign);

try {
$a = ASNObject::fromBinary($encryptStr)->getChildren();
} catch (ParserException $e) {
$this->fail('加密失败: ' . $e->getMessage());
}

$aa = $this->sm2FormatHex($a[0]->getContent());
$bb = $this->sm2FormatHex($a[1]->getContent());
$encryptStr = base64_encode(hex2bin($aa . $bb));
$this->assertNotEmpty($encryptStr);

return $encryptStr;
}

public function test_sm2_verify_sign()
{
$sm2 = $this->getSm2();
$encryptSignStr = bin2hex(base64_decode($this->test_sm2_sign()));
echo 'sm2 sign str: ', $encryptSignStr, PHP_EOL;

$r = substr($encryptSignStr, 0, 64);
$s = substr($encryptSignStr, 64, 64);
$r = gmp_init($r, 16);
$s = gmp_init($s, 16);
$signature = new Signature($r, $s);
$serializer = new DerSignatureSerializer();
$sign = base64_encode($serializer->serialize($signature));

$boolean = $sm2->verifySign($this->getSm2SignStr(), $sign, $this->getSm2PublicKey()) ?? false;
echo $boolean ? 'sm2 验签通过' : 'sm2 验签失败', PHP_EOL;
$this->assertTrue($boolean);
}

public function test_sm2_encrypt()
{

$sm2 = $this->getSm2();

// 压缩公钥
$key = $this->decompressPublicKey('0315edd9126410e9b94b83ee2bcdfeebe9166e84d7aad1b9d16fa923995d28e81f');
$encrypt = $sm2->doEncrypt($this->getDataStr(), $key);
$this->assertNotEmpty($encrypt);
return $encrypt;
}

public function test_sm2_decrypt()
{
$sm2 = $this->getSm2();
$encrypt = $this->test_sm2_encrypt();
$privateKey = 'bf5e3e47e5392a8cdba8e3f854db2d3f5e2c536235303a02898b58d085a8246a';
echo 'sm2 encrypt str: ', $encrypt, PHP_EOL;

$decryptStr = $sm2->doDecrypt($encrypt, $privateKey);
echo 'sm2 decrypt str: ', $decryptStr, PHP_EOL;
$this->assertNotEmpty($decryptStr);
$this->assertTrue($decryptStr === $this->getDataStr());
}

/**
* 获取未压缩公钥
* @param $compressedKey
* @return string|null
*/
function decompressPublicKey($compressedKey): ?string
{
// 获取压缩标志和X坐标
$flag = substr($compressedKey, 0, 2);
$x = substr($compressedKey, 2);

// 将16进制字符串转换为大整数
$p = gmp_init('FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF', 16);
$a = gmp_init('FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC', 16);
$b = gmp_init('28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93', 16);
$gx = gmp_init('32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1711D7AFB1B8B4E16', 16);
$gy = gmp_init('BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0', 16);
$n = gmp_init('FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123', 16);

// 计算Y坐标
$x = gmp_init($x, 16);
$alpha = gmp_powm($x, 3, $p);
$beta = gmp_add(gmp_mod(gmp_mul($a, $x), $p), $b);
$y2 = gmp_mod(gmp_add($alpha, $beta), $p);
$y = gmp_powm($y2, gmp_div_q(gmp_add($p, 1), 4), $p);

if ($flag == "02") {
// 如果压缩标志为 02,则Y坐标为偶数
if (gmp_strval(gmp_mod($y, 2)) != "0") {
$y = gmp_sub($p, $y);
}
return "04" . gmp_strval($x, 16) . str_pad(gmp_strval($y, 16), 64, "0", STR_PAD_LEFT);
}

if ($flag == "03") {
// 如果压缩标志为 03,则Y坐标为奇数
if (gmp_strval(gmp_mod($y, 2)) != "1") {
$y = gmp_sub($p, $y);
}
return "04" . gmp_strval($x, 16) . str_pad(gmp_strval($y, 16), 64, "0", STR_PAD_LEFT);
}

return null;
}


public function test_sm3()
{
$sm3 = $this->getSm3();
$signStr = $sm3->digest($this->getDataStr());
echo 'sm3 sign str: ', $signStr, PHP_EOL;
$this->assertNotEmpty($signStr);
}

/**
* 测试 byteArr to string
* @return string
*/
public function test_sm4_iv()
{
$byteArr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
$iv = call_user_func_array('pack', array_merge(['C*'], $byteArr));

$this->assertTrue(base64_encode($iv) === 'AAAAAAAAAAAAAAAAAAAAAA==');

return base64_encode($iv);
}

public function test_sm4_encrypt()
{
try {
$iv = $this->test_sm4_iv();
$sm4 = $this->getSm4();
$encryptJsonStr = $sm4->encrypt($this->getDataStr(), 'sm4', base64_decode($iv));
} catch (\Exception $e) {
$this->fail('加密异常:' . $e->getMessage());
}

$encryptJsonStr = base64_encode(hex2bin($encryptJsonStr));
$this->assertNotEmpty($encryptJsonStr);

return $encryptJsonStr;
}

public function test_sm4_decrypt()
{
try {
$sm4 = $this->getSm4();
$encryptJsonStr = $this->test_sm4_encrypt();
echo "sm4 encrypt str: " . $encryptJsonStr, PHP_EOL;
$decryptJsonStr = $sm4->decrypt(bin2hex(base64_decode($encryptJsonStr)), 'sm4', base64_decode($this->test_sm4_iv()));
} catch (\Exception $e) {
$this->fail('解密异常:' . $e->getMessage());
}

echo "sm4 decrypt str: " . $decryptJsonStr, PHP_EOL;
echo $decryptJsonStr === $this->getDataStr() ? 'sm4 数据一致' : 'sm4 数据不一致', PHP_EOL;
$this->assertNotEmpty($decryptJsonStr);
}
}