cert_util.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. <?php
  2. namespace com\unionpay\acp\sdk;
  3. include_once 'acp_service.php';
  4. const COMPANY = "中国银联股份有限公司";
  5. class Cert
  6. {
  7. public $cert;
  8. public $certId;
  9. public $key;
  10. }
  11. // 内存泄漏问题说明:
  12. // openssl_x509_parse疑似有内存泄漏,暂不清楚原因,可能和php、openssl版本有关,估计有bug。
  13. // windows下试过php5.4+openssl0.9.8,php7.0+openssl1.0.2都有这问题。mac下试过也有问题。
  14. // 不过至今没人来反馈过这个问题,所以不一定真有泄漏?或者因为增长量不大所以一般都不会遇到问题?
  15. // 也有别人汇报过bug:https://bugs.php.net/bug.php?id=71519
  16. //
  17. // 替代解决方案:
  18. // 方案1. 所有调用openssl_x509_parse的地方都是为了获取证书序列号,可以尝试把证书序列号+证书/key以别的方式保存,
  19. // 从其他地方(比如数据库)读序列号,而不直接从证书文件里读序列号。
  20. // 方案2. 代码改成执行脚本的方式执行,这样执行完一次保证能释放掉所有内存。
  21. // 方案3. 改用下面的CertSerialUtil取序列号,
  22. // 此方法仅用了几个测试和生产的证书做过测试,不保证没bug,所以默认注释掉了。如发现有bug或者可优化的地方可自行修改代码。
  23. // 注意用了bcmath的方法,*nix下编译时需要 --enable-bcmath。http://php.net/manual/zh/bc.installation.php
  24. class CertUtil{
  25. private static $signCerts = array();
  26. private static $encryptCerts = array();
  27. private static $verifyCerts = array();
  28. private static $verifyCerts510 = array();
  29. private static function initSignCert($certPath, $certPwd){
  30. $logger = LogUtil::getLogger();
  31. $logger->LogInfo("读取签名证书……");
  32. $pkcs12certdata = file_get_contents ( $certPath );
  33. if($pkcs12certdata === false ){
  34. $logger->LogInfo($certPath . "file_get_contents fail。");
  35. return;
  36. }
  37. if(openssl_pkcs12_read ( $pkcs12certdata, $certs, $certPwd ) == FALSE ){
  38. $logger->LogInfo($certPath . ", pwd[" . $certPwd . "] openssl_pkcs12_read fail。");
  39. return;
  40. }
  41. $cert = new Cert();
  42. $x509data = $certs ['cert'];
  43. if(!openssl_x509_read ( $x509data )){
  44. $logger->LogInfo($certPath . " openssl_x509_read fail。");
  45. }
  46. $certdata = openssl_x509_parse ( $x509data );
  47. $cert->certId = $certdata ['serialNumber'];
  48. // $certId = CertSerialUtil::getSerial($x509data, $errMsg);
  49. // if($certId === false){
  50. // $logger->LogInfo("签名证书读取序列号失败:" . $errMsg);
  51. // return;
  52. // }
  53. // $cert->certId = $certId;
  54. $cert->key = $certs ['pkey'];
  55. $cert->cert = $x509data;
  56. $logger->LogInfo("签名证书读取成功,序列号:" . $cert->certId);
  57. CertUtil::$signCerts[$certPath] = $cert;
  58. }
  59. public static function getSignKeyFromPfx($certPath=null, $certPwd=null)
  60. {
  61. if( $certPath == null ) {
  62. $certPath = SDKConfig::getSDKConfig()->signCertPath;
  63. $certPwd = SDKConfig::getSDKConfig()->signCertPwd;
  64. }
  65. if (!array_key_exists($certPath, CertUtil::$signCerts)) {
  66. self::initSignCert($certPath, $certPwd);
  67. }
  68. return CertUtil::$signCerts[$certPath] -> key;
  69. }
  70. public static function getSignCertIdFromPfx($certPath=null, $certPwd=null)
  71. {
  72. if( $certPath == null ) {
  73. $certPath = SDKConfig::getSDKConfig()->signCertPath;
  74. $certPwd = SDKConfig::getSDKConfig()->signCertPwd;
  75. }
  76. if (!array_key_exists($certPath, CertUtil::$signCerts)) {
  77. self::initSignCert($certPath, $certPwd);
  78. }
  79. return CertUtil::$signCerts[$certPath] -> certId;
  80. }
  81. private static function initEncryptCert($cert_path)
  82. {
  83. $logger = LogUtil::getLogger();
  84. $logger->LogInfo("读取加密证书……");
  85. $x509data = file_get_contents ( $cert_path );
  86. if($x509data === false ){
  87. $logger->LogInfo($cert_path . " file_get_contents fail。");
  88. return;
  89. }
  90. if(!openssl_x509_read ( $x509data )){
  91. $logger->LogInfo($cert_path . " openssl_x509_read fail。");
  92. return;
  93. }
  94. $cert = new Cert();
  95. $certdata = openssl_x509_parse ( $x509data );
  96. $cert->certId = $certdata ['serialNumber'];
  97. // $certId = CertSerialUtil::getSerial($x509data, $errMsg);
  98. // if($certId === false){
  99. // $logger->LogInfo("签名证书读取序列号失败:" . $errMsg);
  100. // return;
  101. // }
  102. // $cert->certId = $certId;
  103. $cert->key = $x509data;
  104. CertUtil::$encryptCerts[$cert_path] = $cert;
  105. $logger->LogInfo("加密证书读取成功,序列号:" . $cert->certId);
  106. }
  107. public static function verifyAndGetVerifyCert($certBase64String){
  108. $logger = LogUtil::getLogger();
  109. if (array_key_exists($certBase64String, CertUtil::$verifyCerts510)){
  110. return CertUtil::$verifyCerts510[$certBase64String];
  111. }
  112. if (SDKConfig::getSDKConfig()->middleCertPath === null || SDKConfig::getSDKConfig()->rootCertPath === null){
  113. $logger->LogError("rootCertPath or middleCertPath is none, exit initRootCert");
  114. return null;
  115. }
  116. openssl_x509_read($certBase64String);
  117. $certInfo = openssl_x509_parse($certBase64String);
  118. $cn = CertUtil::getIdentitiesFromCertficate($certInfo);
  119. if(strtolower(SDKConfig::getSDKConfig()->ifValidateCNName) == "true"){
  120. if (COMPANY != $cn){
  121. $logger->LogInfo("cer owner is not CUP:" . $cn);
  122. return null;
  123. }
  124. } else if (COMPANY != $cn && "00040000:SIGN" != $cn){
  125. $logger->LogInfo("cer owner is not CUP:" . $cn);
  126. return null;
  127. }
  128. $from = date_create ( '@' . $certInfo ['validFrom_time_t'] );
  129. $to = date_create ( '@' . $certInfo ['validTo_time_t'] );
  130. $now = date_create ( date ( 'Ymd' ) );
  131. $interval1 = $from->diff ( $now );
  132. $interval2 = $now->diff ( $to );
  133. if ($interval1->invert || $interval2->invert) {
  134. $logger->LogInfo("signPubKeyCert has expired");
  135. return null;
  136. }
  137. $result = openssl_x509_checkpurpose($certBase64String, X509_PURPOSE_ANY, array(SDKConfig::getSDKConfig()->rootCertPath, SDKConfig::getSDKConfig()->middleCertPath));
  138. if($result === FALSE){
  139. $logger->LogInfo("validate signPubKeyCert by rootCert failed");
  140. return null;
  141. } else if($result === TRUE){
  142. CertUtil::$verifyCerts510[$certBase64String] = $certBase64String;
  143. return CertUtil::$verifyCerts510[$certBase64String];
  144. } else {
  145. $logger->LogInfo("validate signPubKeyCert by rootCert failed with error");
  146. return null;
  147. }
  148. }
  149. public static function getIdentitiesFromCertficate($certInfo){
  150. $cn = $certInfo['subject'];
  151. $cn = $cn['CN'];
  152. $company = explode('@',$cn);
  153. if(count($company) < 3) {
  154. return null;
  155. }
  156. return $company[2];
  157. }
  158. public static function getEncryptCertId($cert_path=null){
  159. if( $cert_path == null ) {
  160. $cert_path = SDKConfig::getSDKConfig()->encryptCertPath;
  161. }
  162. if(!array_key_exists($cert_path, CertUtil::$encryptCerts)){
  163. self::initEncryptCert($cert_path);
  164. }
  165. if(array_key_exists($cert_path, CertUtil::$encryptCerts)){
  166. return CertUtil::$encryptCerts[$cert_path] -> certId;
  167. }
  168. return false;
  169. }
  170. public static function getEncryptKey($cert_path=null){
  171. if( $cert_path == null ) {
  172. $cert_path = SDKConfig::getSDKConfig()->encryptCertPath;
  173. }
  174. if(!array_key_exists($cert_path, CertUtil::$encryptCerts)){
  175. self::initEncryptCert($cert_path);
  176. }
  177. if(array_key_exists($cert_path, CertUtil::$encryptCerts)){
  178. return CertUtil::$encryptCerts[$cert_path] -> key;
  179. }
  180. return false;
  181. }
  182. private static function initVerifyCerts($cert_dir=null) {
  183. if( $cert_dir == null ) {
  184. $cert_dir = SDKConfig::getSDKConfig()->validateCertDir;
  185. }
  186. $logger = LogUtil::getLogger();
  187. $logger->LogInfo ( '验证签名证书目录 :>' . $cert_dir );
  188. $handle = opendir ( $cert_dir );
  189. if (!$handle) {
  190. $logger->LogInfo ( '证书目录 ' . $cert_dir . '不正确' );
  191. return;
  192. }
  193. while ($file = readdir($handle)) {
  194. clearstatcache();
  195. $filePath = $cert_dir . '/' . $file;
  196. if (is_file($filePath)) {
  197. if (pathinfo($file, PATHINFO_EXTENSION) == 'cer') {
  198. $x509data = file_get_contents($filePath);
  199. if($x509data === false ){
  200. $logger->LogInfo($filePath . " file_get_contents fail。");
  201. continue;
  202. }
  203. if(!openssl_x509_read($x509data)){
  204. $logger->LogInfo($certPath . " openssl_x509_read fail。");
  205. continue;
  206. }
  207. $cert = new Cert();
  208. $certdata = openssl_x509_parse($x509data);
  209. $cert->certId = $certdata ['serialNumber'];
  210. // $certId = CertSerialUtil::getSerial($x509data, $errMsg);
  211. // if($certId === false){
  212. // $logger->LogInfo("签名证书读取序列号失败:" . $errMsg);
  213. // return;
  214. // }
  215. // $cert->certId = $certId;
  216. $cert->key = $x509data;
  217. CertUtil::$verifyCerts[$cert->certId] = $cert;
  218. $logger->LogInfo($filePath . "读取成功,序列号:" . $cert->certId);
  219. }
  220. }
  221. }
  222. closedir ( $handle );
  223. }
  224. public static function getVerifyCertByCertId($certId){
  225. $logger = LogUtil::getLogger();
  226. if(count(CertUtil::$verifyCerts) == 0){
  227. self::initVerifyCerts();
  228. }
  229. if(count(CertUtil::$verifyCerts) == 0){
  230. $logger->LogInfo("未读取到任何证书……");
  231. return null;
  232. }
  233. if(array_key_exists($certId, CertUtil::$verifyCerts)){
  234. return CertUtil::$verifyCerts[$certId]->key;
  235. } else {
  236. $logger->LogInfo("未匹配到序列号为[" . certId . "]的证书");
  237. return null;
  238. }
  239. }
  240. public static function test() {
  241. $x509data = file_get_contents ( "d:/certs/acp_test_enc.cer" );
  242. // $resource = openssl_x509_read ( $x509data );
  243. // $certdata = openssl_x509_parse ( $resource ); //<=这句尼玛内存泄漏啊根本释放不掉啊啊啊啊啊啊啊
  244. // echo $certdata ['serialNumber']; //<=就是需要这个数据啦
  245. // echo $x509data;
  246. // unset($certdata); //<=没有什么用
  247. // openssl_x509_free($resource); //<=没有什么用x2
  248. echo CertSerialUtil::getSerial ( $x509data, $errMsg ) . "\n";
  249. }
  250. }
  251. // class CertSerialUtil {
  252. // private static function bytesToInteger($bytes) {
  253. // $val = 0;
  254. // for($i = 0; $i < count ( $bytes ); $i ++) {
  255. // // $val += (($bytes [$i] & 0xff) << (8 * (count ( $bytes ) - 1 - $i)));
  256. // $val += $bytes [$i] * pow(256, count ( $bytes ) - 1 - $i);
  257. // // echo $val . "<br>\n";
  258. // }
  259. // return $val;
  260. // }
  261. // private static function bytesToBigInteger($bytes) {
  262. // $val = 0;
  263. // for($i = 0; $i < count ( $bytes ); $i ++) {
  264. // $val = bcadd($val, bcmul($bytes [$i], bcpow(256, count ( $bytes ) - 1 - $i)));
  265. // // echo $val . "<br>\n";
  266. // }
  267. // return $val;
  268. // }
  269. // private static function toStr($bytes) {
  270. // $str = '';
  271. // foreach($bytes as $ch) {
  272. // $str .= chr($ch);
  273. // }
  274. // return $str;
  275. // }
  276. // public static function getSerial($fileData, &$errMsg) {
  277. // // $fileData = str_replace('\n','',$fileData);
  278. // // $fileData = str_replace('\r','',$fileData);
  279. // $start = "-----BEGIN CERTIFICATE-----";
  280. // $end = "-----END CERTIFICATE-----";
  281. // $data = trim ( $fileData );
  282. // if (substr ( $data, 0, strlen ( $start ) ) != $start ||
  283. // substr ( $data, strlen ( $data ) - strlen ( $end ) ) != $end) {
  284. // // echo $fileData;
  285. // $errMsg = "error pem data";
  286. // return false;
  287. // }
  288. // $data = substr ( $data, strlen ( $start ), strlen ( $data ) - strlen ( $end ) - strlen ( $start ) );
  289. // $bindata = base64_decode ( $data );
  290. // $bindata = unpack ( 'C*', $bindata );
  291. // $byte = array_shift ( $bindata );
  292. // if ($byte != 0x30) {
  293. // $errMsg = "1st tag " . $byte . " is not 30";
  294. // return false;
  295. // }
  296. // $length = CertSerialUtil::readLength ( $bindata );
  297. // $byte = array_shift ( $bindata );
  298. // if ($byte != 0x30) {
  299. // $errMsg = "2nd tag " . $byte . " is not 30";
  300. // return false;
  301. // }
  302. // $length = CertSerialUtil::readLength ( $bindata );
  303. // $byte = array_shift ( $bindata );
  304. // // echo $byte . "<br>\n";
  305. // if ($byte == 0xa0) { //version tag.
  306. // $length = CertSerialUtil::readLength ( $bindata );
  307. // CertSerialUtil::readData ( $bindata, $length );
  308. // $byte = array_shift ( $bindata );
  309. // }
  310. // // echo $byte . "<br>\n";
  311. // if ($byte != 0x02) { //x509v1 has no version tag, x509v3 has.
  312. // $errMsg = "4th/3rd tag " . $byte . " is not 02";
  313. // return false;
  314. // }
  315. // $length = CertSerialUtil::readLength ( $bindata );
  316. // $serial = CertSerialUtil::readData ( $bindata, $length );
  317. // // echo bin2hex(CertSerialUtil::toStr( $serial ));
  318. // return CertSerialUtil::bytesToBigInteger($serial);
  319. // }
  320. // private static function readLength(&$bindata) {
  321. // $byte = array_shift ( $bindata );
  322. // if ($byte < 0x80) {
  323. // $length = $byte;
  324. // } else {
  325. // $lenOfLength = $byte - 0x80;
  326. // for($i = 0; $i < $lenOfLength; $i ++) {
  327. // $lenBytes [] = array_shift ( $bindata );
  328. // }
  329. // $length = CertSerialUtil::bytesToInteger ( $lenBytes );
  330. // }
  331. // return $length;
  332. // }
  333. // private static function readData(&$bindata, $length) {
  334. // $data = array ();
  335. // for($i = 0; $i < $length; $i ++) {
  336. // $data [] = array_shift ( $bindata );
  337. // }
  338. // return $data;
  339. // }
  340. // }