AopCertification.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. <?php
  2. namespace addons\AvoidTax\common\jdk\alipay;
  3. /**
  4. * 验证支付宝公钥证书是否可信
  5. * @param $alipayCert 支付宝公钥证书
  6. * @param $rootCert 支付宝根证书
  7. */
  8. function isTrusted($alipayCert, $rootCert)
  9. {
  10. $alipayCerts = readPemCertChain($alipayCert);
  11. $rootCerts = readPemCertChain($rootCert);
  12. if (verifyCertChain($alipayCerts, $rootCerts)) {
  13. return verifySignature($alipayCert, $rootCert);
  14. } else {
  15. return false;
  16. }
  17. }
  18. function verifySignature($alipayCert, $rootCert)
  19. {
  20. $alipayCertArray = explode("-----END CERTIFICATE-----", $alipayCert);
  21. $rootCertArray = explode("-----END CERTIFICATE-----", $rootCert);
  22. $length = count($rootCertArray) - 1;
  23. $checkSign = isCertSigner($alipayCertArray[0] . "-----END CERTIFICATE-----", $alipayCertArray[1] . "-----END CERTIFICATE-----");
  24. if (!$checkSign) {
  25. $checkSign = isCertSigner($alipayCertArray[1] . "-----END CERTIFICATE-----", $alipayCertArray[0] . "-----END CERTIFICATE-----");
  26. if ($checkSign) {
  27. $issuer = openssl_x509_parse($alipayCertArray[0] . "-----END CERTIFICATE-----")['issuer'];
  28. for ($i = 0; $i < $length; $i++) {
  29. $subject = openssl_x509_parse($rootCertArray[$i] . "-----END CERTIFICATE-----")['subject'];
  30. if ($issuer == $subject) {
  31. isCertSigner($alipayCertArray[0] . "-----END CERTIFICATE-----", $rootCertArray[$i] . $rootCertArray);
  32. return $checkSign;
  33. }
  34. }
  35. } else {
  36. return $checkSign;
  37. }
  38. } else {
  39. $issuer = openssl_x509_parse($alipayCertArray[1] . "-----END CERTIFICATE-----")['issuer'];
  40. for ($i = 0; $i < $length; $i++) {
  41. $subject = openssl_x509_parse($rootCertArray[$i] . "-----END CERTIFICATE-----")['subject'];
  42. if ($issuer == $subject) {
  43. $checkSign = isCertSigner($alipayCertArray[1] . "-----END CERTIFICATE-----", $rootCertArray[$i] . "-----END CERTIFICATE-----");
  44. return $checkSign;
  45. }
  46. }
  47. return $checkSign;
  48. }
  49. }
  50. function readPemCertChain($cert)
  51. {
  52. $array = explode("-----END CERTIFICATE-----", $cert);
  53. $certs[] = null;
  54. for ($i = 0; $i < count($array) - 1; $i++) {
  55. $certs[$i] = openssl_x509_parse($array[$i] . "-----END CERTIFICATE-----");
  56. }
  57. return $certs;
  58. }
  59. function verifyCert($prev, $rootCerts)
  60. {
  61. $nowTime = time();
  62. if ($nowTime < $prev['validFrom_time_t']) {
  63. echo "证书未激活";
  64. return false;
  65. }
  66. if ($nowTime > $prev['validTo_time_t']) {
  67. echo "证书已经过期";
  68. return false;
  69. }
  70. $subjectMap = null;
  71. for ($i = 0; $i < count($rootCerts); $i++) {
  72. $subjectDN = array2string($rootCerts[$i]['subject']);
  73. $subjectMap[$subjectDN] = $rootCerts[$i];
  74. }
  75. $issuerDN = array2string(($prev['issuer']));
  76. if (!array_key_exists($issuerDN, $subjectMap)) {
  77. echo "证书链验证失败";
  78. return false;
  79. }
  80. return true;
  81. }
  82. /**
  83. * 验证证书链是否是信任证书库中证书签发的
  84. * @param $alipayCerts 目标验证证书列表
  85. * @param $rootCerts 可信根证书列表
  86. */
  87. function verifyCertChain($alipayCerts, $rootCerts)
  88. {
  89. $sorted = sortByDn($alipayCerts);
  90. if (!$sorted) {
  91. echo "证书链验证失败:不是完整的证书链";
  92. return false;
  93. }
  94. //先验证第一个证书是不是信任库中证书签发的
  95. $prev = $alipayCerts[0];
  96. $firstOK = verifyCert($prev, $rootCerts);
  97. $length = count($alipayCerts);
  98. if (!$firstOK || $length == 1) {
  99. return $firstOK;
  100. }
  101. $nowTime = time();
  102. //验证证书链
  103. for ($i = 1; $i < $length; $i++) {
  104. $cert = $alipayCerts[$i];
  105. if ($nowTime < $cert['validFrom_time_t']) {
  106. echo "证书未激活";
  107. return false;
  108. }
  109. if ($nowTime > $cert['validTo_time_t']) {
  110. echo "证书已经过期";
  111. return false;
  112. }
  113. }
  114. return true;
  115. }
  116. /**
  117. * 将证书链按照完整的签发顺序进行排序,排序后证书链为:[issuerA, subjectA]-[issuerA, subjectB]-[issuerB, subjectC]-[issuerC, subjectD]...
  118. * @param $certs 证书链
  119. */
  120. function sortByDn(&$certs)
  121. {
  122. //是否包含自签名证书
  123. $hasSelfSignedCert = false;
  124. $subjectMap = null;
  125. $issuerMap = null;
  126. for ($i = 0; $i < count($certs); $i++) {
  127. if (isSelfSigned($certs[$i])) {
  128. if ($hasSelfSignedCert) {
  129. return false;
  130. }
  131. $hasSelfSignedCert = true;
  132. }
  133. $subjectDN = array2string($certs[$i]['subject']);
  134. $issuerDN = array2string(($certs[$i]['issuer']));
  135. $subjectMap[$subjectDN] = $certs[$i];
  136. $issuerMap[$issuerDN] = $certs[$i];
  137. }
  138. $certChain = null;
  139. addressingUp($subjectMap, $certChain, $certs[0]);
  140. addressingDown($issuerMap, $certChain, $certs[0]);
  141. //说明证书链不完整
  142. if (count($certs) != count($certChain)) {
  143. return false;
  144. }
  145. //将证书链复制到原先的数据
  146. for ($i = 0; $i < count($certs); $i++) {
  147. $certs[$i] = $certChain[count($certs) - $i - 1];
  148. }
  149. return true;
  150. }
  151. /**
  152. * 验证证书是否是自签发的
  153. * @param $cert 目标证书
  154. */
  155. function isSelfSigned($cert)
  156. {
  157. $subjectDN = array2string($cert['subject']);
  158. $issuerDN = array2string($cert['issuer']);
  159. return ($subjectDN == $issuerDN);
  160. }
  161. function array2string($array)
  162. {
  163. $string = [];
  164. if ($array && is_array($array)) {
  165. foreach ($array as $key => $value) {
  166. $string[] = $key . '=' . $value;
  167. }
  168. }
  169. return implode(',', $string);
  170. }
  171. /**
  172. * 向上构造证书链
  173. * @param $subjectMap 主题和证书的映射
  174. * @param $certChain 证书链
  175. * @param $current 当前需要插入证书链的证书,include
  176. */
  177. function addressingUp($subjectMap, &$certChain, $current)
  178. {
  179. $certChain[] = $current;
  180. if (isSelfSigned($current)) {
  181. return;
  182. }
  183. $issuerDN = array2string($current['issuer']);
  184. if (!array_key_exists($issuerDN, $subjectMap)) {
  185. return;
  186. }
  187. addressingUp($subjectMap, $certChain, $subjectMap[$issuerDN]);
  188. }
  189. /**
  190. * 向下构造证书链
  191. * @param $issuerMap 签发者和证书的映射
  192. * @param $certChain 证书链
  193. * @param $current 当前需要插入证书链的证书,exclude
  194. */
  195. function addressingDown($issuerMap, &$certChain, $current)
  196. {
  197. $subjectDN = array2string($current['subject']);
  198. if (!array_key_exists($subjectDN, $issuerMap)) {
  199. return $certChain;
  200. }
  201. $certChain[] = $issuerMap[$subjectDN];
  202. addressingDown($issuerMap, $certChain, $issuerMap[$subjectDN]);
  203. }
  204. /**
  205. * Extract signature from der encoded cert.
  206. * Expects x509 der encoded certificate consisting of a section container
  207. * containing 2 sections and a bitstream. The bitstream contains the
  208. * original encrypted signature, encrypted by the public key of the issuing
  209. * signer.
  210. * @param string $der
  211. * @return string on success
  212. * @return bool false on failures
  213. */
  214. function extractSignature($der = false)
  215. {
  216. if (strlen($der) < 5) {
  217. return false;
  218. }
  219. // skip container sequence
  220. $der = substr($der, 4);
  221. // now burn through two sequences and the return the final bitstream
  222. while (strlen($der) > 1) {
  223. $class = ord($der[0]);
  224. $classHex = dechex($class);
  225. switch ($class) {
  226. // BITSTREAM
  227. case 0x03:
  228. $len = ord($der[1]);
  229. $bytes = 0;
  230. if ($len & 0x80) {
  231. $bytes = $len & 0x0f;
  232. $len = 0;
  233. for ($i = 0; $i < $bytes; $i++) {
  234. $len = ($len << 8) | ord($der[$i + 2]);
  235. }
  236. }
  237. return substr($der, 3 + $bytes, $len);
  238. break;
  239. // SEQUENCE
  240. case 0x30:
  241. $len = ord($der[1]);
  242. $bytes = 0;
  243. if ($len & 0x80) {
  244. $bytes = $len & 0x0f;
  245. $len = 0;
  246. for ($i = 0; $i < $bytes; $i++) {
  247. $len = ($len << 8) | ord($der[$i + 2]);
  248. }
  249. }
  250. $contents = substr($der, 2 + $bytes, $len);
  251. $der = substr($der, 2 + $bytes + $len);
  252. break;
  253. default:
  254. return false;
  255. break;
  256. }
  257. }
  258. return false;
  259. }
  260. /**
  261. * Get signature algorithm oid from der encoded signature data.
  262. * Expects decrypted signature data from a certificate in der format.
  263. * This ASN1 data should contain the following structure:
  264. * SEQUENCE
  265. * SEQUENCE
  266. * OID (signature algorithm)
  267. * NULL
  268. * OCTET STRING (signature hash)
  269. * @return bool false on failures
  270. * @return string oid
  271. */
  272. function getSignatureAlgorithmOid($der = null)
  273. {
  274. // Validate this is the der we need...
  275. if (!is_string($der) or strlen($der) < 5) {
  276. return false;
  277. }
  278. $bit_seq1 = 0;
  279. $bit_seq2 = 2;
  280. $bit_oid = 4;
  281. if (ord($der[$bit_seq1]) !== 0x30) {
  282. die('Invalid DER passed to getSignatureAlgorithmOid()');
  283. }
  284. if (ord($der[$bit_seq2]) !== 0x30) {
  285. die('Invalid DER passed to getSignatureAlgorithmOid()');
  286. }
  287. if (ord($der[$bit_oid]) !== 0x06) {
  288. die('Invalid DER passed to getSignatureAlgorithmOid');
  289. }
  290. // strip out what we don't need and get the oid
  291. $der = substr($der, $bit_oid);
  292. // Get the oid
  293. $len = ord($der[1]);
  294. $bytes = 0;
  295. if ($len & 0x80) {
  296. $bytes = $len & 0x0f;
  297. $len = 0;
  298. for ($i = 0; $i < $bytes; $i++) {
  299. $len = ($len << 8) | ord($der[$i + 2]);
  300. }
  301. }
  302. $oid_data = substr($der, 2 + $bytes, $len);
  303. // Unpack the OID
  304. $oid = floor(ord($oid_data[0]) / 40);
  305. $oid .= '.' . ord($oid_data[0]) % 40;
  306. $value = 0;
  307. $i = 1;
  308. while ($i < strlen($oid_data)) {
  309. $value = $value << 7;
  310. $value = $value | (ord($oid_data[$i]) & 0x7f);
  311. if (!(ord($oid_data[$i]) & 0x80)) {
  312. $oid .= '.' . $value;
  313. $value = 0;
  314. }
  315. $i++;
  316. }
  317. return $oid;
  318. }
  319. /**
  320. * Get signature hash from der encoded signature data.
  321. * Expects decrypted signature data from a certificate in der format.
  322. * This ASN1 data should contain the following structure:
  323. * SEQUENCE
  324. * SEQUENCE
  325. * OID (signature algorithm)
  326. * NULL
  327. * OCTET STRING (signature hash)
  328. * @return bool false on failures
  329. * @return string hash
  330. */
  331. function getSignatureHash($der = null)
  332. {
  333. // Validate this is the der we need...
  334. if (!is_string($der) or strlen($der) < 5) {
  335. return false;
  336. }
  337. if (ord($der[0]) !== 0x30) {
  338. die('Invalid DER passed to getSignatureHash()');
  339. }
  340. // strip out the container sequence
  341. $der = substr($der, 2);
  342. if (ord($der[0]) !== 0x30) {
  343. die('Invalid DER passed to getSignatureHash()');
  344. }
  345. // Get the length of the first sequence so we can strip it out.
  346. $len = ord($der[1]);
  347. $bytes = 0;
  348. if ($len & 0x80) {
  349. $bytes = $len & 0x0f;
  350. $len = 0;
  351. for ($i = 0; $i < $bytes; $i++) {
  352. $len = ($len << 8) | ord($der[$i + 2]);
  353. }
  354. }
  355. $der = substr($der, 2 + $bytes + $len);
  356. // Now we should have an octet string
  357. if (ord($der[0]) !== 0x04) {
  358. die('Invalid DER passed to getSignatureHash()');
  359. }
  360. $len = ord($der[1]);
  361. $bytes = 0;
  362. if ($len & 0x80) {
  363. $bytes = $len & 0x0f;
  364. $len = 0;
  365. for ($i = 0; $i < $bytes; $i++) {
  366. $len = ($len << 8) | ord($der[$i + 2]);
  367. }
  368. }
  369. return bin2hex(substr($der, 2 + $bytes, $len));
  370. }
  371. /**
  372. * Determine if one cert was used to sign another
  373. * Note that more than one CA cert can give a positive result, some certs
  374. * re-issue signing certs after having only changed the expiration dates.
  375. * @param string $cert - PEM encoded cert
  376. * @param string $caCert - PEM encoded cert that possibly signed $cert
  377. * @return bool
  378. */
  379. function isCertSigner($certPem = null, $caCertPem = null)
  380. {
  381. if (!function_exists('openssl_pkey_get_public')) {
  382. die('Need the openssl_pkey_get_public() function.');
  383. }
  384. if (!function_exists('openssl_public_decrypt')) {
  385. die('Need the openssl_public_decrypt() function.');
  386. }
  387. if (!function_exists('hash')) {
  388. die('Need the php hash() function.');
  389. }
  390. if (empty($certPem) or empty($caCertPem)) {
  391. return false;
  392. }
  393. // Convert the cert to der for feeding to extractSignature.
  394. $certDer = pemToDer($certPem);
  395. if (!is_string($certDer)) {
  396. die('invalid certPem');
  397. }
  398. // Grab the encrypted signature from the der encoded cert.
  399. $encryptedSig = extractSignature($certDer);
  400. if (!is_string($encryptedSig)) {
  401. die('Failed to extract encrypted signature from certPem.');
  402. }
  403. // Extract the public key from the ca cert, which is what has
  404. // been used to encrypt the signature in the cert.
  405. $pubKey = openssl_pkey_get_public($caCertPem);
  406. if ($pubKey === false) {
  407. die('Failed to extract the public key from the ca cert.');
  408. }
  409. // Attempt to decrypt the encrypted signature using the CA's public
  410. // key, returning the decrypted signature in $decryptedSig. If
  411. // it can't be decrypted, this ca was not used to sign it for sure...
  412. $rc = openssl_public_decrypt($encryptedSig, $decryptedSig, $pubKey);
  413. if ($rc === false) {
  414. return false;
  415. }
  416. // We now have the decrypted signature, which is der encoded
  417. // asn1 data containing the signature algorithm and signature hash.
  418. // Now we need what was originally hashed by the issuer, which is
  419. // the original DER encoded certificate without the issuer and
  420. // signature information.
  421. $origCert = stripSignerAsn($certDer);
  422. if ($origCert === false) {
  423. die('Failed to extract unsigned cert.');
  424. }
  425. // Get the oid of the signature hash algorithm, which is required
  426. // to generate our own hash of the original cert. This hash is
  427. // what will be compared to the issuers hash.
  428. $oid = getSignatureAlgorithmOid($decryptedSig);
  429. if ($oid === false) {
  430. die('Failed to determine the signature algorithm.');
  431. }
  432. switch ($oid) {
  433. case '1.2.840.113549.2.2':
  434. $algo = 'md2';
  435. break;
  436. case '1.2.840.113549.2.4':
  437. $algo = 'md4';
  438. break;
  439. case '1.2.840.113549.2.5':
  440. $algo = 'md5';
  441. break;
  442. case '1.3.14.3.2.18':
  443. $algo = 'sha';
  444. break;
  445. case '1.3.14.3.2.26':
  446. $algo = 'sha1';
  447. break;
  448. case '2.16.840.1.101.3.4.2.1':
  449. $algo = 'sha256';
  450. break;
  451. case '2.16.840.1.101.3.4.2.2':
  452. $algo = 'sha384';
  453. break;
  454. case '2.16.840.1.101.3.4.2.3':
  455. $algo = 'sha512';
  456. break;
  457. default:
  458. die('Unknown signature hash algorithm oid: ' . $oid);
  459. break;
  460. }
  461. // Get the issuer generated hash from the decrypted signature.
  462. $decryptedHash = getSignatureHash($decryptedSig);
  463. // Ok, hash the original unsigned cert with the same algorithm
  464. // and if it matches $decryptedHash we have a winner.
  465. $certHash = hash($algo, $origCert);
  466. return ($decryptedHash === $certHash);
  467. }
  468. /**
  469. * Convert pem encoded certificate to DER encoding
  470. * @return string $derEncoded on success
  471. * @return bool false on failures
  472. */
  473. function pemToDer($pem = null)
  474. {
  475. if (!is_string($pem)) {
  476. return false;
  477. }
  478. $cert_split = preg_split('/(-----((BEGIN)|(END)) CERTIFICATE-----)/', $pem);
  479. if (!isset($cert_split[1])) {
  480. return false;
  481. }
  482. return base64_decode($cert_split[1]);
  483. }
  484. /**
  485. * Obtain der cert with issuer and signature sections stripped.
  486. * @param string $der - der encoded certificate
  487. * @return string $der on success
  488. * @return bool false on failures.
  489. */
  490. function stripSignerAsn($der = null)
  491. {
  492. if (!is_string($der) or strlen($der) < 8) {
  493. return false;
  494. }
  495. $bit = 4;
  496. $len = ord($der[($bit + 1)]);
  497. $bytes = 0;
  498. if ($len & 0x80) {
  499. $bytes = $len & 0x0f;
  500. $len = 0;
  501. for ($i = 0; $i < $bytes; $i++) {
  502. $len = ($len << 8) | ord($der[$bit + $i + 2]);
  503. }
  504. }
  505. return substr($der, 4, $len + 4);
  506. }