php配置Let's Encrypt免费ssl证书

之前写过一个文章(CentOS6给网站开通免费https)是通过certbot来配置Let's Encrypt的免费证书的,那个工具好虽好但是需要python版本大于等于2.7,我的服务器又是CentOS6的,默认python版本太低,于是乎就想试试不需要依赖除php以外的方法,以下就是我的操作记录。以下操作的域名example.com为示例,需替换为自己的域名。

准备Acme PHP

这是一个用php写的可以获取ssl证书的工具,需要php开启curlopenssl扩展。文档地址https://acmephp.github.io/documentation/getting-started/1-installation.html

仅需要下载一个phar文件和一个pubkey文件即可完成安装。

cd ~
php -r "copy('https://github.com/acmephp/acmephp/releases/download/1.0.1/acmephp.phar', 'acmephp.phar');"
php -r "copy('https://github.com/acmephp/acmephp/releases/download/1.0.1/acmephp.phar.pubkey', 'acmephp.phar.pubkey');"
php acmephp.phar --version

申请证书

直接按照文档上的步骤来就可以了,最简单的方式就是通过配置yml文件,此处不再赘述。
我这里讲的主要是单独手动申请证书的步骤。

注册邮箱

php acmephp.phar register xxx@example.com

注意:Windows下此处可能会报错
1.OpenSSL key creation failed during generation with error: error:02001003:system library:fopen:No such process
2.cURL error 60: SSL certificate problem: unable to get local issuer certificate (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

解决办法详见AcmePhpSslExceptionKeyPairGenerationException on register #69

授权域名

php acmephp.phar auth example.com

成功后会提示你创建一个文件http://example.com/.well-known/acme-challenge/xxxx,文件内容就是下面打印出来的内容,一串字符。注意:Windows下直接右键无法创建.开头的目录,可以使用dos命令或者使用php脚本创建。

验证域名

php acmephp.phar check -s http example.com

验证成功之后会提示你可以获取证书了。

获取证书

php acmephp.phar request example.com

获取完证书之后默认会存储在当前用户目录~/.acmephp/master/certs/example.com下的public和private文件夹下,这里就是我们需要的证书文件了。

基本非iis用户到这里就可以拿着证书文件去配置nginx啥的了,但是如果要配置iis,则需要使用的是.pfx文件的证书,这怎么办呢?下面直接给出php代码

# 证书文件和私钥文件
$cert = '~/.acmephp/master/certs/example.com/public/cert.pem';
$key = '~/.acmephp/master/certs/example.com/private/key.private.pem';
# 获取证书内容
$x509 = openssl_x509_read(file_get_contents($cert));
# 获取私钥内容
$private_key = openssl_get_privatekey(file_get_contents($key));
# 转为pfx文件,其中$out存储的是pfx的二进制数据,直接将其写入pfx文件即可,123456为证书密码
$res = openssl_pkcs12_export($x509, $out, $private_key, '123456', array(
    # 证书名称,不填显示为空
    'friendly_name' => 'example.com'
));

if ($res) {
    # 保存为pfx文件即可
    file_put_contents('ssl/cert.pfx', $out);
}

查看证书状态

> php acmephp.phar status

+-----------------+----------------------------+---------------------+---------------------+----------------+
| Domain          | Issuer                     | Valid from          | Valid to            | Needs renewal? |
+-----------------+----------------------------+---------------------+---------------------+----------------+
| example.com     | Let's Encrypt Authority X3 | 2019-11-27 07:28:36 | 2020-02-25 07:28:36 | No             |
+-----------------+----------------------------+---------------------+---------------------+----------------+

The End!

原文地址:https://www.cnblogs.com/lantor/p/11944017.html