/
SM2.php
110 lines (90 loc) · 2.37 KB
/
SM2.php
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
<?php
declare (strict_types = 1);
namespace Larke\JwtSM2\Admin\Signer;
use Illuminate\Support\Str;
use Illuminate\Support\Collection;
use Rtgm\util\MyAsn1;
use Larke\JWT\Signer\Key\InMemory;
use Larke\JWT\Contracts\Key as KeyContract;
use Larke\JWT\Contracts\Signer as SignerContract;
use Larke\Admin\Jwt\Contracts\Signer;
use Larke\JwtSM2\Jwt\Signer\SM2 as SM2Signer;
/*
* SM2 签名
*
* @create 2023-10-23
* @author deatil
*/
class SM2 implements Signer
{
/**
* 签名方法
*/
protected string $signingMethod = SM2Signer::class;
/**
* 配置
*
* @var Collection
*/
private Collection $config;
/**
* 构造方法
*
* @param Collection $config 配置信息
*/
public function __construct(Collection $config)
{
$this->config = $config;
}
/**
* 签名类
*
* @return \Larke\JWT\Contracts\Signer
*/
public function getSigner(): SignerContract
{
return new $this->signingMethod();
}
/**
* 签名密钥
*
* @return \Larke\JWT\Contracts\Key
*/
public function getSignSecrect(): KeyContract
{
$privateKey = $this->config->get("private_key");
if (file_exists($privateKey)) {
$data = file_get_contents($privateKey);
if ($this->isPKCS8Key($data)) {
$der = MyAsn1::decode_file($privateKey);
$der = MyAsn1::decode($der[2] ?? '', 'hex');
} else {
$der = MyAsn1::decode_file($privateKey);
}
$secrect = InMemory::plainText($der[1] ?: '');
} else {
$secrect = InMemory::plainText($privateKey);
}
return $secrect;
}
/**
* 验证密钥
*
* @return \Larke\JWT\Contracts\Key
*/
public function getVerifySecrect(): KeyContract
{
$publicKey = $this->config->get("public_key");
if (file_exists($publicKey)) {
$der = MyAsn1::decode_file($publicKey);
$secrect = InMemory::plainText($der[1] ?: '');
} else {
$secrect = InMemory::plainText($publicKey);
}
return $secrect;
}
private function isPKCS8Key(string $key): bool
{
return Str::contains($key, '-----BEGIN PRIVATE KEY-----', true);
}
}