OpensslService.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace App\Services;
  3. use App\Traits\CommonTrait;
  4. use Illuminate\Support\Facades\Cache;
  5. use Illuminate\Support\Facades\DB;
  6. class OpensslService
  7. {
  8. use CommonTrait;
  9. public $table = 'sys_openssl_secret';
  10. /**
  11. * 重新缓存数据
  12. */
  13. public function cacheCsr()
  14. {
  15. $query = DB::table($this->table);
  16. $query->select('id')->orderBy('id', 'asc')->chunk(100, function ($listObj) {
  17. foreach ($listObj as $row) {
  18. $keyArr = $this->getOpensslCacheKey($row->id);
  19. Cache::tags($keyArr['tags'])->forever($keyArr['key'], get_object_vars($row));
  20. }
  21. });
  22. }
  23. /**
  24. * 创建新的密钥对
  25. *
  26. * @return array
  27. */
  28. public function getNewCsr()
  29. {
  30. $config = array(
  31. "private_key_bits" => 1024, //指定应该使用多少位来生成私钥 512 1024 2048 4096等
  32. "private_key_type" => OPENSSL_KEYTYPE_RSA, //选择在创建CSR时应该使用哪些扩展。可选值有 OPENSSL_KEYTYPE_DSA, OPENSSL_KEYTYPE_DH, OPENSSL_KEYTYPE_RSA 或 OPENSSL_KEYTYPE_EC. 默认值是 OPENSSL_KEYTYPE_RSA.
  33. );
  34. $res = openssl_pkey_new($config);
  35. openssl_pkey_export($res, $private_key_pem, null, $config);
  36. $details = openssl_pkey_get_details($res);
  37. $public_key_pem = $details['key'];
  38. return ['private_key' => $private_key_pem, 'public_key' => $public_key_pem];
  39. }
  40. /**
  41. * 清空表,清空缓存
  42. */
  43. public function clearTable()
  44. {
  45. DB::table($this->table)->truncate();
  46. $keyArr = $this->getOpensslTotalCacheKey();
  47. Cache::tags($keyArr['tags'])->flush();
  48. }
  49. }