Let‘s encrypt提供免费的SSL证书,他的SSL证书的有效性有三个月之久,并且可以以编程的方式实现续期,今天我就给大家讲讲C#实现Let‘s encrypt申请免费的SSL证书吧。

首先我们要使用NUGET获取Certes的类库,获取之后我们便可以使用C#轻松的实现申请Let‘s encrypt的SSL证书

第一步我们需要创建用户并同意Let‘s encrypt的使用协议,我们这里使用了数据库存储用户如果没有则创建新的用户,新用户的密钥会存放到数据库以待下次使用。

AcmeContext acmeContext = null;
IAccountContext accountContext = null;
var wellKnownServers = Unity.Debug ? WellKnownServers.LetsEncryptStagingV2 : WellKnownServers.LetsEncryptV2;
if (!baseUser.LetsEncryptPem.IsNullOrEmpty())
{
    try
    {
        acmeContext = new AcmeContext(wellKnownServers, KeyFactory.FromPem(baseUser.LetsEncryptPem));
        accountContext = await acmeContext.Account();
    }
    catch (Exception err)
    {
        acmeContext = null;
        err.Log();
    }
}

if (acmeContext == null)
{
    acmeContext = new AcmeContext(wellKnownServers);
    accountContext = await acmeContext.NewAccount(baseUser.Email, true);
}

if (acmeContext != null && !(acmeContext.AccountKey?.ToPem()).IsNullOrEmpty())
{
    baseUser.LetsEncryptPem = acmeContext.AccountKey?.ToPem();
    ContainerService._BaseUserService.SaveOrUpdate(baseUser);
}
第二步申请订单并获取认证信息,www.yourdomain.com代表的是你要申请的主机名。
IOrderContext orderContext = null;
IAuthorizationContext authz = null;
Certes.Acme.Resource.Authorization resource = null;
orderContext = await acmeContext.NewOrder(new[] { "www.yourdomain.com" });
authz = await orderContext.Authorization(currentDomain);
resource = await authz.Resource();

在第二步获取授权之后,第三步我们就要下载验证文件

var httpChallenge = await authz.Http();
var keyAuthz = httpChallenge.KeyAuthz;
var webPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
var dir = webPath + @"domain\" + currentDomain + @"\.well-known\acme-challenge\";
if (!System.IO.Directory.Exists(dir)) System.IO.Directory.CreateDirectory(dir);
System.IO.File.WriteAllText(dir + httpChallenge.Token, keyAuthz);

第四步通知Let‘s encrypt验证域名的归属权。

if (resource.Status == AuthorizationStatus.Pending)
{
    ("正在验证:" + currentDomain).Log("SSL申请");
    await httpChallenge.Validate();
    var times = 0;
    while (times++ < 10 && resource.Status == AuthorizationStatus.Pending)
    {
        ("第[" + times + "]次等待授权状态:" + currentDomain).Log("SSL申请");
        Thread.Sleep(10000);
        resource = await authz.Resource();
    }
}
一旦Let's encrypt验证通过,在第五步我们便可以下载证书文件

if (resource.Status == AuthorizationStatus.Valid)
{
    webArchive.LetsEncryptChallengeTime = DateTime.Now;
    ("获取证书订单:" + currentDomain).Log("SSL申请");
    var privateKey = KeyFactory.NewKey(KeyAlgorithm.ES256);
    CertificateChain certificateChain = await orderContext.Generate(new CsrInfo { CommonName = currentDomain }, privateKey);
    ("下载证书:" + currentDomain).Log("SSL申请");
    var pfxBuilder = certificateChain.ToPfx(privateKey);
    var certificationPwd = "123456";
    var pfxName = currentDomain.Replace(".", "_");
    var pfx = pfxBuilder.Build(pfxName, certificationPwd);
    System.IO.File.WriteAllBytes(webArchive.LetsEncryptPfxPath, pfx);
}
通过以上五步轻松的获取了Let's encrypt的 免费SSL证书 ,有不懂的小伙伴欢迎留言哦!