使用ThinkPHP6中集成Acmephp实现SSL证书在线生成,并自动续签。
直接上代码
1,安装Acmephp
用Composer来安装Acmephp。在项目根目录下执行以下命令:
SSL在线生成网址:https://ssl.goolibao.com/ssl
composer require acmephp/acmephp
2,创建证书目录
在config目录下创建一个acmephp.php配置文件,用于配置Acmephp。
return [
'storage' => [
'class' => AcmePhpSslStoreFilesystemStore::class,
'directory' => __DIR__.'/../public/certs',
],
'acme' => [
'directory' => 'https://acme-v02.api.letsencrypt.org/directory',
'contact' => ['mailto:admin@example.com'],
],
];
在上面的配置中,我们指定了证书存储的目录为public/certs,以及ACME服务器的地址和联系方式。
4,创建SSL证书
用Acmephp的API来创建SSL证书。控制器:
<?php
namespace appcontroller;
use AcmePhpSslPrivateKey;
use AcmePhpSslCertificate;
use AcmePhpCoreAcmeClient;
use AcmePhpBundleAcmeDomainAuthorizationChallengeSolver;
use AcmePhpBundleAcmeDomainAuthorizationChallenge;
use AcmePhpBundleAcmeDomainDomainValidator;
use SymfonyComponentHttpFoundationRequest;
class CertController
{
public function create(Request $request)
{
$domain = $request->get('domain');
$email = $request->get('email');
$client = new AcmeClient($domain, $email);
$solver = new AuthorizationChallengeSolver();
$challenge = $client->requestAuthorization($domain);
$solver->solve($challenge, $domain);
$validator = new DomainValidator();
$validator->validate($domain);
$privateKey = new PrivateKey();
$certificate = new Certificate($client->getCertificateData());
$privateKey->saveToFile(__DIR__.'/../public/certs/'.$domain.'.key');
$certificate->saveToFile(__DIR__.'/../public/certs/'.$domain.'.crt');
return 'OK';
}
}
我们首先从请求参数中获取域名和电子邮件地址,然后创建一个AcmeClient对象来请求证书。接着,我们通过AuthorizationChallengeSolver来解决验证挑战,然后使用DomainValidator来验证域名。最后,我们将私钥和证书保存到public/certs目录下。
5,自动续签SSL证书
用Acmephp的API来自动续签SSL证书。
<?php
namespace appcontroller;
use AcmePhpSslPrivateKey;
use AcmePhpSslCertificate;
use AcmePhpCoreAcmeClient;
use AcmePhpBundleAcmeDomainAuthorizationChallengeSolver;
use AcmePhpBundleAcmeDomainAuthorizationChallenge;
use AcmePhpBundleAcmeDomainDomainValidator;
use SymfonyComponentHttpFoundationRequest;
class CertController
{
public function renew(Request $request)
{
$domain = $request->get('domain');
$email = $request->get('email');
$client = new AcmeClient($domain, $email);
$certificate = new Certificate(file_get_contents(__DIR__.'/../public/certs/'.$domain.'.crt'));
$privateKey = new PrivateKey(file_get_contents(__DIR__.'/../public/certs/'.$domain.'.key'));
$client->renewCertificate($certificate, $privateKey);
$certificate->saveToFile(__DIR__.'/../public/certs/'.$domain.'.crt');
$privateKey->saveToFile(__DIR__.'/../public/certs/'.$domain.'.key');
return 'OK';
}
}
思路:我们首先从请求参数中获取域名和电子邮件地址,然后创建一个AcmeClient对象来请求证书。接着,我们加载之前生成的证书和私钥文件,然后调用renewCertificate方法来自动续签证书。最后,我们将新的证书和私钥保存到public/certs目录下。
版权说明
文章采用: 《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权。版权声明:未标注转载均为本站原创,转载时请以链接形式注明文章出处。如有侵权、不妥之处,请联系站长删除。敬请谅解!