-
Notifications
You must be signed in to change notification settings - Fork 6
/
CryptoHelper.php
245 lines (206 loc) · 5.89 KB
/
CryptoHelper.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
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
<?php
/**
* Wrapper for CPCertficate object
*/
class CryptoCertificate {
private $original;
private $pin;
public $Subject;
public $Issuer;
public $Version;
public $SerialNumber;
public $Thumbprint;
public $ValidFrom;
public $ValidTo;
public $HasPrivate;
public $IsValid;
function __construct($certificate) {
$this->original = $certificate;
$this->Subject = $this->parseDN($certificate->get_SubjectName());
$this->Issuer = $this->parseDN($certificate->get_IssuerName());
$this->Version = $certificate->get_Version();
$this->SerialNumber = $certificate->get_SerialNumber();
$this->Thumbprint = $certificate->get_Thumbprint();
$this->ValidFrom = $certificate->get_ValidFromDate();
$this->ValidTo = $certificate->get_ValidToDate();
$this->HasPrivate = $certificate->HasPrivateKey();
$this->IsValid = $certificate->IsValid()->get_Result();
}
function GetCertificate() {
return $this->original;
}
function SetPin($pin) {
$this->pin = $pin;
}
function GetPin() {
return $this->pin;
}
private function parseDN($dn) {
$tags = [
'CN' => 'Name',
'S' => 'Region',
'ST' => 'Region',
'STREET' => 'Address',
'O' => 'Company',
'OU' => 'PostType',
'T' => 'Post',
'TITLE' => 'Post',
'ОГРН' => 'Ogrn',
'OGRN' => 'Ogrn',
'СНИЛС' => 'Snils',
'SNILS' => 'Snils',
'ИНН' => 'Inn',
'INN' => 'Inn',
'E' => 'Email',
'G' => 'GivenName',
'GN' => 'GivenName',
'SN' => 'SurName',
'L' => 'City'
];
preg_match_all('/\s\w+=/u', $dn, $matches);
$buf = $dn;
$i = 0;
$fields = array_reduce(array_reverse($matches[0]), function($acc, $cur) use (&$buf, &$i, $tags) {
$pos = mb_strpos($buf, $cur);
//$pos = strpos($buf, $cur);
$v = substr($buf, $pos);
$v = str_replace($cur, '', $v);
$v = preg_replace('/\s*"?(.*?)"?,?\s?$/', '$1', $v);
$v = preg_replace('/""/', '"', $v);
$tag = trim(str_replace('=', '', $cur));
if (array_key_exists($tag, $tags)) {
$acc[$tags[$tag]] = $v;
}
$buf = substr($buf, 0, $pos);
$i++;
return $acc;
}, []);
return (object)$fields;
}
}
/**
* Crypto Helper class
*/
class CryptoHelper {
const SIGN_DETACHED = true;
/**
* Get valid certificates from store
* @param search - filter by subject name
* @param integer $location - https://docs.microsoft.com/ru-ru/windows/win32/seccrypto/capicom-store-location
* @param string $store
* @return CryptoCertificate[]
*/
public function GetCertificates($search = null, $location = null, $store = null) {
$store = $this->getStore($location, $store);
$certs = $store->get_Certificates();
if ($search) {
$certs = $certs->Find(CERTIFICATE_FIND_SUBJECT_NAME, $search, 0);
} else {
$certs = $certs->Find(CERTIFICATE_FIND_TIME_VALID, date('YmdHis'), 0);
}
$certsArr = [];
for ($i = 1; $i <= $certs->Count(); $i++) {
$cert = new CryptoCertificate($certs->Item($i));
$certsArr []= $cert;
}
return $certsArr;
}
/**
* Sign string data type by chosen certificate
*
* @param CryptoCertificate $certificate
* @param string $data
* @param boolean $toBase64
* @return string|boolean
*/
public function Sign($certificate, $data, $toBase64 = true) {
$signer = new CPSigner();
$signer->set_Certificate($certificate->GetCertificate());
$signer->set_Options(CERTIFICATE_INCLUDE_WHOLE_CHAIN);
if ($certificate->GetPin()) {
$signer->set_KeyPin($certificate->GetPin());
}
$signedData = new CPSignedData();
$signedData->set_ContentEncoding(BASE64_TO_BINARY);
$signedData->set_Content($toBase64 ? base64_encode($data) : $data);
try {
$signedMessage = $signedData->SignCades($signer, CADES_BES, self::SIGN_DETACHED, ENCODE_BASE64);
return $signedMessage;
} catch (Exception $e) {
return false;
}
}
/**
* Sign file by chosen certificate
*
* @param CryptoCertificate $certificate
* @param string $dataFilePath
* @param string $signFilePath
* @return string|boolean
*/
public function SignFile($certificate, $dataFilePath, $signFilePath = null) {
$data = file_get_contents($dataFilePath);
$sign = $this->Sign($certificate, $data, true);
if ($signFilePath) {
file_put_contents($signFilePath, $sign);
}
return $sign;
}
/**
* Verify data sign
*
* @param string $data
* @param string $sign
* @param boolean $toBase64
* @return array|boolean
*/
public function Verify($data, $sign, $toBase64 = true) {
$signedData = new CPSignedData();
$signedData->set_ContentEncoding(BASE64_TO_BINARY);
$signedData->set_Content($toBase64 ? base64_encode($data) : $data);
try {
$signedData->VerifyCades($sign, CADES_BES, self::SIGN_DETACHED);
$signers = $signedData->get_Signers();
$signs = [];
for ($i = 1; $i <= $signedData->get_Signers(); $i += 1) {
$signer = $signers->get_Item($i);
$cert = $signer->get_Certificate();
$signs []= (object)[
'ts' => $signer->get_SigningTime(),
'cert' => new CryptoCertificate($cert)
];
}
return $signs;
} catch (Exception $e) {
return false;
}
}
/**
* Verify file sign
*
* @param string $dataFilePath
* @param string $signFilePath
* @return array|boolean
*/
public function VerifyFile($dataFilePath, $signFilePath) {
$data = file_get_contents($dataFilePath);
$sign = file_get_contents($signFilePath);
return $this->Verify($data, $sign, true);
}
/**
* Create and open store
*
* @param integer $location
* @param string $name
* @param integer $mode
* @return CPStore
*/
private function getStore($location = null, $name = null, $mode = null) {
$location = $location ?: CURRENT_USER_STORE;
$name = $name ?: 'My';
$mode = $mode ?: STORE_OPEN_READ_ONLY;
$store = new CPStore();
$store->Open($location, $name, $mode);
return $store;
}
}