Skip to content

Commit cca5667

Browse files
authored
Merge pull request #87 from AlexQin2017/feature/sm2_ans1
sm2解密支持ans1格式密文
2 parents 2824b53 + 996f3cb commit cca5667

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

src/sm/RtSm2.php

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,56 @@ public function doDecrypt($encryptData, $privateKey, $trim = true, $model = C1C3
187187
return '';
188188
}
189189
}
190+
191+
/**
192+
* 解密ASN1(c1xc1yc3c2)格式的密文
193+
* @param $encryptData
194+
* @param $privateKey
195+
* @param $trim
196+
* @param $model
197+
* @return string
198+
* @throws \Exception
199+
*/
200+
public function doDecryptASN1($encryptData, $privateKey, $trim = true, $model = C1C3C2): string
201+
{
202+
$newEncryptData = $this->transformANS1($encryptData);
203+
return $this->doDecrypt($newEncryptData, $privateKey, $trim, $model);
204+
}
205+
206+
/**
207+
* 密文格式转换 ANS1(c1xc1yc3c2) -> c1c3c2
208+
*
209+
* @param string $encryptData
210+
* @return string
211+
* @throws \Exception
212+
*/
213+
private function transformANS1(string $encryptData): string
214+
{
215+
$asn1Object = \FG\ASN1\ASNObject::fromBinary($encryptData);
216+
217+
if (! $asn1Object instanceof \FG\ASN1\Universal\Sequence) {
218+
throw new \Exception('Invalid ASN.1 format');
219+
}
220+
221+
// 提取 x 和 y 坐标
222+
$c1X = $asn1Object->getChildren()[0]->getContent();
223+
$c1Y = $asn1Object->getChildren()[1]->getContent();
224+
225+
// 使用 GMP 处理大整数
226+
$c1xHex = gmp_strval(gmp_init($c1X, 10), 16);
227+
$c1yHex = gmp_strval(gmp_init($c1Y, 10), 16);
228+
229+
// 确保十六进制字符串长度为 64 个字符(256 位)
230+
$c1xHex = str_pad($c1xHex, 64, '0', STR_PAD_LEFT);
231+
$c1yHex = str_pad($c1yHex, 64, '0', STR_PAD_LEFT);
232+
233+
// 提取 c3 和 c2
234+
$c3 = $asn1Object->getChildren()[2]->getContent();
235+
$c2 = $asn1Object->getChildren()[3]->getContent();
236+
237+
return $c1xHex . $c1yHex . $c3 . $c2;
238+
}
239+
190240
/**
191241
* SM2 签名明文16进制密码, 如提供的base64的,可使用 bin2hex(base64_decode($privateKey))
192242
*

0 commit comments

Comments
 (0)