创建 X509 证书并另存为 Base-64

Create X509 certificate and save as Base-64

我一直在遵循涵盖 Web API 安全签名授权令牌的指南。其中一个方面是将 X509 证书作为 Base-64 字符串存储在 web.config 中。但是,没有解释如何获取 X509 证书并将其转换为 Base-64 字符串的必要步骤。我找到了一些关于如何使用 OpenSSL 生成 X509 证书的指南,但是我仍然对使用哪些部分以及如何转换为 Base-64 感到困惑。这是我想要结束的。

  1. 我可以存储在 web.config
  2. 中的证书的 Base-64 表示形式
  3. 证书附带的密码

我想在我的身份验证服务器中使用的代码是..

SigningCertificate = new X509Certificate2(certificate, password);

其中 certificate 是证书的 Base 64 编码表示,password 是签名证书密码。

所以使用 OpenSSL 工具我能够生成两个文件...

问题 #1 - 转换为 Base-64 时是否只需要使用 MyCert.pem 文件?或者这两个文件是否需要在表示为 Base-64 之前将两个文件合并为一个 PFX 文件?

问题 #2 - 是否有我可以使用的接受文件然后导出 Base-64 字符串的实用程序?

Question #1 - Do I only need to use the MyCert.pem file when converting to Base-64? Or do both files need to combined both files as a single PFX file before representing as Base-64?

PEM 文件格式采用 base64 编码。它可以应用于私钥、证书或证书签名请求。这些文件有一个 header/foot 来区分它们以 ----BEGIN PRIVATE KEY--------BEGIN CERTIFICATE----

开头

A PFX 是私钥和受密码保护的证书的容器。您需要包含这两个 PEM 文件。 PFX 以 pkcs#12 格式(二进制)编码。

将证书与密钥文件连接起来,然后让 OpenSSL 将其转换为 PKCS#12 (PFX)

cat MyKey.pem MyCert.pem > cert.pem
openssl pkcs12 -export -in cert.pem -out mykeystore.p12 -name myalias
#Enter Export Password:

如果您正在使用此 service(我在 google 中搜索过),您将需要 pkcs12 文件和分配的密码

Question #2 - Is there a utility that I can use that accepts a file and then exports a Base-64 string?

我通常使用带有 MIME 插件的文本编辑器,如 Notepad++。或者,如果您需要以编程方式进行操作,所有编程语言都有一种将字节数组转换为 Base64 的方法。

考虑到您有本地 IIS,这是在 .NET 中获取有效证书的方法:

  1. Open your IIS
  2. Click on Server Certificates
  3. Click on Create Self-Signed Certificate
  4. Specify a name and select Web Hosting, then click Ok
  5. Select the certificate you just created and click on Export
  6. When exporting it, select a location and choose a password(1)

要获取Base64字符串,可以在C#上使用这段代码:

var certificate = Convert.ToBase64String(File.ReadAllBytes(@"C:\Temp\DemoCert.pfx"));

我将 base64 字符串和密码存储在我的网络配置中:

<appSettings>
 <add key="SigningCertificate" value="MIIKLwIBAzCCCesGCSqGSIb3DQEHAaCCCdwk...." />
 <add key="SigningCertificatePassword" value="password"/>         
</appSettings>

(1) 您在 key="SigningCertificatePassword" 属性中使用的密码与您在创建证书时使用的密码相同。

然后在我的 Startup.cs class:

中使用它
var certificate = Convert.FromBase64String(ConfigurationManager.AppSettings["SigningCertificate"]);

var options = new IdentityServerOptions
        {
            SigningCertificate = new X509Certificate2(certificate, ConfigurationManager.AppSettings["SigningCertificatePassword"]),
            RequireSsl = false,
            Factory = factory
        };