OpenSSL 精粹：SSL 证书、私钥和 CSR
OpenSSL 证书
![](/data/attachment/album/202006/07/225825y6frhbm2ozvfamoa.jpg)


### 介绍


OpenSSL 是一个多功能的命令行工具，可以用于与<ruby> 公钥基础设施 <rp>  （ </rp> <rt>  Public Key Infrastructure </rt> <rp>  ） </rp></ruby>（PKI）和 HTTPS（HTTP over TLS）相关的大量任务。这本小抄风格的指南提供了 OpenSSL 命令的快速参考，这些命令在常见的日常场景中非常有用。这包括生成私钥、<ruby> 证书签署请求 <rp>  （ </rp> <rt>  certificate signing request </rt> <rp>  ） </rp></ruby>（CSR）和证书格式转换的 OpenSSL 示例，但它并没有涵盖 OpenSSL 的所有用途。


### 如何使用本指南


* 如果你不熟悉证书签署请求（CSR），请阅读第一部分。
* 除了第一部分，本指南采用了简单的小抄格式：自带了命令行代码片段。
* 跳到与你准备完成的任务相关的任何部分。
* 大多数命令都是单行的，为了清晰起见，已经扩展到多行（使用 `\` 符号）。


### 关于证书签署请求（CSR）


如果你想从<ruby> 证书颁发机构 <rp>  （ </rp> <rt>  certificate authority </rt> <rp>  ） </rp></ruby>（CA）那里获得 SSL 证书，你必须生成一个<ruby> 证书签署请求 <rp>  （ </rp> <rt>  certificate signing request </rt> <rp>  ） </rp></ruby>（CSR）。一个 CSR 主要是由一个密钥对的公钥和一些附加信息组成。当证书被签署时，这两部分都会被插入到证书中。


每当你生成一个 CSR 时，你会被提示提供有关证书的信息。这些信息被称为<ruby> 区分名称 <rp>  （ </rp> <rt>  Distinguised Name </rt> <rp>  ） </rp></ruby>（DN）。DN 中的一个重要字段是<ruby> 通用名称 <rp>  （ </rp> <rt>  Common Name </rt> <rp>  ） </rp></ruby>（CN），它应该是你打算使用证书的主机的<ruby> 完全合格域名 <rp>  （ </rp> <rt>  Fully Qualified Domain Name </rt> <rp>  ） </rp></ruby>（FQDN）。当创建 CSR 时，也可以通过命令行或文件传递信息来跳过交互式提示。


DN 中的其他项目提供了有关你的业务或组织的附加信息。如果你是从证书机构购买 SSL 证书，通常要求这些附加字段（如“<ruby> 组织 <rp>  （ </rp> <rt>  Organization </rt> <rp>  ） </rp></ruby>”）准确地反映你的组织的详细信息。


下面是一个 CSR 信息提示的例子：



```
---
Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:New York
Locality Name (eg, city) []:Brooklyn
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Example Brooklyn Company
Organizational Unit Name (eg, section) []:Technology Division
Common Name (e.g. server FQDN or YOUR name) []:examplebrooklyn.com
Email Address []:
```

如果你想非交互式地回答 CSR 信息提示，你可以通过在任何请求 CSR 信息的 OpenSSL 命令中添加 `-subj` 选项来实现。这里是该选项的一个例子，使用上面代码块中显示的相同信息：



```
-subj "/C=US/ST=New York/L=Brooklyn/O=Example Brooklyn Company/CN=examplebrooklyn.com"
```

现在你已经了解了 CSR，可以自由跳转到本指南中涵盖你的 OpenSSL 需求的任何一节。


### 生成 CSR


本节介绍了与生成 CSR（以及私钥，如果它们还不存在的话）有关的 OpenSSL 命令。CSR 可以用来向证书颁发机构请求 SSL 证书。


请记住，你可以通过上一节中提到的 `-subj` 选项非交互式地添加 CSR 信息。


#### 生成一个私钥和一个 CSR


如果你想使用 HTTPS（HTTP over TLS）来保护你的 Apache HTTP 或 Nginx Web 服务器的安全，并且你想使用一个证书颁发机构（CA）来颁发 SSL 证书，那么就使用这个方法。生成的 CSR 可以发送给 CA，请求签发由 CA 签名的 SSL 证书。如果你的 CA 支持 SHA-2，请添加 `-sha256` 选项，用 SHA-2 签署 CSR。


这条命令从头开始创建一个 2048 位的私钥（`domain.key`）和一个 CSR（`domain.csr`）：



```
openssl req \
       -newkey rsa:2048 -nodes -keyout domain.key \
       -out domain.csr
```

回答 CSR 信息提问，完成该过程。


选项 `-newkey rsa:2048` 指定密钥应该是 `2048` 位，使用 `RSA` 算法生成。选项 `-nodes` 指定私钥*没有*用密码加密。这里没有包含 `-new` 选项，而是隐含在其中，表示正在生成一个 CSR。


#### 从现有的私钥中生成一个 CSR


如果你已经有了私钥，并想用它向 CA 申请证书，请使用这个方法。


该命令基于现有的私钥（`domain.key`）创建一个新的 CSR（`domain.csr`）：



```
openssl req \
       -key domain.key \
       -new -out domain.csr
```

回答 CSR 信息提问，完成该过程。


选项 `-key` 指定一个现有的私钥（`domain.key`)，它将被用来生成一个新的 CSR。选项 `-new` 表示正在生成一个 CSR。


#### 从现有的证书和私钥生成 CSR


如果你想更新现有的证书，但由于某些原因，你或你的 CA 没有原始的 CSR，请使用这个方法。基本上可以省去重新输入 CSR 信息的麻烦，因为它是从现有证书中提取信息的。


该命令基于现有的证书（`domain.crt`）和私钥（`domain.key`）创建一个新的 CSR（`domain.csr`）：



```
openssl x509 \
       -in domain.crt \
       -signkey domain.key \
       -x509toreq -out domain.csr
```

选项 `-x509toreq` 指定你使用一个 X509 证书来制作 CSR。


### 生成 SSL 证书


如果你想使用 SSL 证书来确保服务的安全，但你不需要 CA 签名的证书，一个有效的（和免费的）解决方案是签署你自己的证书。


你可以自己签发的一种常见证书是<ruby> 自签证书 <rp>  （ </rp> <rt>  self-signed certificate </rt> <rp>  ） </rp></ruby>。自签证书是用自己的私钥签署的证书。自签证书和 CA 签名证书一样可以用来加密数据，但是你的用户会显示一个警告，说这个证书不被他们的计算机或浏览器信任。因此，只有当你不需要向用户证明你的服务身份时，才可以使用自签名证书（例如非生产或非公开服务器）。


本节介绍与生成自签名证书相关的 OpenSSL 命令。


#### 生成自签证书


如果你想使用 HTTPS（HTTP over TLS）来保护你的 Apache HTTP 或 Nginx Web 服务器，并且你不需要你的证书由 CA 签名，那么就使用这个方法。


这个命令可以从头开始创建一个 2048 位的私钥（`domain.key`）和一个自签证书（`domain.crt`）：



```
openssl req \
       -newkey rsa:2048 -nodes -keyout domain.key \
       -x509 -days 365 -out domain.crt
```

回答 CSR 信息提问，完成该过程。


选项 `-x509` 告诉 `req` 子命令创建一个自签名的证书。`-days 365` 选项指定证书的有效期为 `365` 天。它会生成一个临时的 CSR，以收集与证书相关的信息。


#### 从现有私钥生成自签名证书


如果你已经有了一个私钥，并且你想用它来生成一个自签证书，请使用这个方法。


这条命令可以从现有的私钥（`domain.key`）中创建一个自签证书（`domain.crt`）：



```
openssl req \
       -key domain.key \
       -new \
       -x509 -days 365 -out domain.crt
```

回答 CSR 信息提问，完成该过程。


选项 `-x509` 告诉 `req` 子命令创建一个自签证书。`-days 365` 选项指定证书的有效期为 `365` 天。选项 `-new` 启用 CSR 信息提问。


#### 从现有的私钥和 CSR 生成自签证书


如果你已经有了私钥和 CSR，并且你想用它们生成一个自签证书，请使用这个方法。


这条命令将从现有的私钥（`domain.key`）和（`domain.csr`）中创建一个自签证书（`domain.crt`）。



```
openssl x509 \
       -signkey domain.key \
       -in domain.csr \
       -req -days 365 -out domain.crt
```

选项 `-days 365` 指定证书的有效期为 `365` 天。


### 查看证书


证书和 CSR 文件是以 PEM 格式编码的，不适合被人读取。


本节介绍的 OpenSSL 命令将输出 PEM 编码文件的实际条目。


#### 查看 CSR 条目


该命令允许你查看和验证纯文本的 CSR（`domain.csr`）的内容：



```
openssl req \  
       -text -noout -verify \  
       -in domain.csr
```

#### 查看证书条目


该命令允许你查看纯文本证书（`domain.crt`）的内容：



```
openssl x509 \  
       -text -noout \  
       -in domain.crt
```

#### 验证证书由 CA 签署


使用此命令验证证书（`domain.crt`）是否由特定的 CA 证书（`ca.crt`）签署：



```
openssl verify \  
       -verbose -CAFile ca.crt \  
       domain.crt
```

### 私钥


本节介绍了用于创建和验证私钥的 OpenSSL 命令。


#### 创建私钥


使用该命令创建一个受密码保护的 `2048` 位私钥（`domain.key`）：



```
openssl genrsa \  
       -des3 -out domain.key 2048
```

在提示时输入密码以完成该过程。


#### 验证私钥


使用此命令检查私钥（`domain.key`）是否为有效密钥：



```
openssl rsa \  
       -check -in domain.key
```

如果你的私钥已经加密，系统会提示你输入它的密码，成功后，未加密的密钥会在终端上输出。


#### 验证私钥是否与证书和 CSR 匹配


使用这些命令来验证私钥（`domain.key`）是否匹配证书（`domain.crt`）和 CSR（`domain.csr`）：



```
openssl rsa  -noout -modulus -in domain.key | openssl md5
openssl x509 -noout -modulus -in domain.crt | openssl md5
openssl req  -noout -modulus -in domain.csr | openssl md5
```

如果每条命令的输出都是相同的，那么私钥、证书和 CSR 就极有可能是相关的。


#### 加密私钥


这需要一个未加密的私钥（`unencrypted.key`），并输出它的加密版本（`encrypted.key`）：



```
openssl rsa -des3 \
       -in unencrypted.key \
       -out encrypted.key
```

输入你所需的密码，以加密私钥。


#### 解密私钥


这需要一个加密的私钥（`encrypted.key`），并输出一个解密的版本（`decrypted.key`）：



```
openssl rsa \
       -in encrypted.key \
       -out decrypted.key
```

在提示时，输入加密密钥的密码。


### 转换证书格式


我们一直在使用的所有证书都是 ASCII 码 PEM 编码的 X.509 证书。还有很多其他的证书编码和容器类型；一些应用程序喜欢某些格式而不是其他格式。此外，这些格式中的许多格式可以在一个文件中包含多个项目，如私钥、证书和 CA 证书。


OpenSSL 可以用来将证书在则西格式间转换。本节将介绍一些可能的转换。


#### 将 PEM 转换为 DER


如果要将 PEM 编码的证书（`domain.crt`）转换为 DER 编码的证书（`domain.der`），即二进制格式，请使用此命令：



```
openssl x509 \
       -in domain.crt \
       -outform der -out domain.der
```

DER 格式通常与 Java 一起使用。


#### 将 DER 转换为 PEM


如果要将 DER 编码的证书（`domain.der`）转换为 PEM 编码的证书（`domain.crt`），请使用此命令：



```
openssl x509 \
       -inform der -in domain.der \
       -out domain.crt
```

#### 将 PEM 转换为 PKCS7


如果你想把 PEM 证书（`domain.crt` 和 `ca-chain.crt`）添加到 PKCS7 文件（`domain.p7b`）中，请使用该命令：



```
openssl crl2pkcs7 -nocrl \
       -certfile domain.crt \
       -certfile ca-chain.crt \
       -out domain.p7b
```

请注意，你可以使用一个或多个 `-certfile` 选项来指定要添加到 PKCS7 文件中的证书。


PKCS7 文件，也被称为 P7B，通常用于 Java Keystores 和 Microsoft IIS（Windows）。它们是 ASCII 文件，可以包含证书和 CA 证书。


#### 将 PKCS7 转换为 PEM


如果你想将 PKCS7 文件（`domain.p7b`）转换为 PEM 文件，请使用该命令：



```
openssl pkcs7 \
       -in domain.p7b \
       -print_certs -out domain.crt
```

请注意，如果你的 PKCS7 文件中有多个项目（如证书和 CA 中间证书)，创建的 PEM 文件将包含其中的所有项目。


#### 将 PEM 转换为 PKCS12


如果你想使用私钥（`domain.key`）和证书（`domain.crt`），并将它们组合成一个 PKCS12 文件（`domain.pfx`），请使用这个命令：



```
openssl pkcs12 \
       -inkey domain.key \
       -in domain.crt \
       -export -out domain.pfx
```

系统会提示你输入导出密码，你可以留空。请注意，在这种情况下，你可以通过将多个证书连接到一个 PEM 文件（`domain.crt`）中来添加一个证书链到 PKCS12 文件中。


PKCS12 文件，也被称为 PFX 文件，通常用于在 Micrsoft IIS（Windows）中导入和导出证书链。


#### 将 PKCS12 转换为 PEM


如果你想转换 PKCS12 文件（`domain.pfx`）并将其转换为 PEM 格式（`domain.combined.crt`），请使用此命令：



```
openssl pkcs12 \
       -in domain.pfx \
       -nodes -out domain.combined.crt
```

请注意，如果你的 PKCS12 文件中有多个项目（如证书和私钥），创建的 PEM 文件将包含其中的所有项目。


### OpenSSL 版本


`openssl version` 命令可以用来检查你正在运行的版本。你正在运行的 OpenSSL 版本，以及编译时使用的选项会影响到你可以使用的功能（有时也会影响到命令行选项）。


下面的命令显示了你正在运行的 OpenSSL 版本，以及它被编译时的所有选项：



```
openssl version -a
```

本指南是使用具有如下细节的 OpenSSL 二进制文件编写的（参见前面命令的输出）：



```
OpenSSL 1.0.1f 6 Jan 2014
built on: Mon Apr  7 21:22:23 UTC 2014
platform: debian-amd64
options:  bn(64,64) rc4(16x,int) des(idx,cisc,16,int) blowfish(idx)
compiler: cc -fPIC -DOPENSSL_PIC -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -m64 -DL_ENDIAN -DTERMIO -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -Wl,-Bsymbolic-functions -Wl,-z,relro -Wa,--noexecstack -Wall -DMD32_REG_T=int -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DWHIRLPOOL_ASM -DGHASH_ASM
OPENSSLDIR: "/usr/lib/ssl"
```

### 总结


这应该涵盖了大多数人如何使用 OpenSSL 来处理 SSL 证书的情况！它还有很多其他的用途，在这里没有介绍，所以请在评论中随时询问或建议其他用途。


如果你在使用这些命令时遇到了问题，请一定要评论（并附上你的 OpenSSL 版本输出）。




---


via: <https://www.digitalocean.com/community/tutorials/openssl-essentials-working-with-ssl-certificates-private-keys-and-csrs> 


作者：[Mitchell Anicas](https://www.digitalocean.com/community/users/manicas) 选题：[wxy](https://github.com/wxy) 译者：[wxy](https://github.com/wxy) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](/article-12290-1.html) 荣誉推出


OK
OpenSSL is a versatile command line tool that can be used for a large variety of tasks related to Public Key Infrastructure (PKI) and HTTPS (HTTP over TLS). This cheat sheet style guide provides a quick reference to OpenSSL commands that are useful in common, everyday scenarios. This includes OpenSSL examples for generating private keys, certificate signing requests, and certificate format conversion. It does not cover all of the uses of OpenSSL.

**How to Use This Guide:**

`\`

symbol) for clarityIf you would like to obtain an SSL certificate from a commercial certificate authority (CA), you must generate a certificate signing request (CSR). A CSR consists mainly of the public key of a key pair, and some additional information. Both of these components are inserted into the certificate when it is signed.

Whenever you generate a CSR, you will be prompted to provide information regarding the certificate. This information is known as a Distinguished Name (DN). An important field in the DN is the **Common Name** (CN), which should be the exact Fully Qualified Domain Name (FQDN) of the host that you intend to use the certificate with. It is also possible to skip the interactive prompts when creating a CSR by passing the information via command line or from a file.

The other items in a DN provide additional information about your business or organization. If you are purchasing an SSL certificate from a certificate authority, it is often required that these additional fields, such as “Organization”, accurately reflect your organization’s details.

Here is an example of what the CSR information prompt will look like:

```
---
Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:New York
Locality Name (eg, city) []:Brooklyn
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Example Brooklyn Company
Organizational Unit Name (eg, section) []:Technology Division
Common Name (e.g. server FQDN or YOUR name) []:examplebrooklyn.com
Email Address []:
```


If you want to non-interactively answer the CSR information prompt, you can do so by adding the `-subj`

option to any OpenSSL commands that request CSR information. Here is an example of the option, using the same information displayed in the code block above:

```
-subj "/C=US/ST=New York/L=Brooklyn/O=Example Brooklyn Company/CN=examplebrooklyn.com"
```


Now that you understand CSRs, feel free to jump around to whichever section of this guide covers your OpenSSL needs.

This section covers OpenSSL commands that are related to generating CSRs (and private keys, if they do not already exist). CSRs can be used to request SSL certificates from a certificate authority.

Keep in mind that you may add the CSR information non-interactively with the `-subj`

option, mentioned in the previous section.

Use this method if you want to use HTTPS (HTTP over TLS) to secure your Apache HTTP or Nginx web server, and you want to use a Certificate Authority (CA) to issue the SSL certificate. The CSR that is generated can be sent to a CA to request the issuance of a CA-signed SSL certificate. If your CA supports SHA-2, add the `-sha256`

option to sign the CSR with SHA-2.

This command creates a 2048-bit private key (`domain.key`

) and a CSR (`domain.csr`

) from scratch:

- openssl req \
- -newkey rsa:2048 -nodes -keyout domain.key \
- -out domain.csr



Answer the CSR information prompt to complete the process.

The `-newkey rsa:2048`

option specifies that the key should be 2048-bit, generated using the RSA algorithm. The `-nodes`

option specifies that the private key should *not* be encrypted with a pass phrase. The `-new`

option, which is not included here but implied, indicates that a CSR is being generated.

Use this method if you already have a private key that you would like to use to request a certificate from a CA.

This command creates a new CSR (`domain.csr`

) based on an existing private key (`domain.key`

):

- openssl req \
- -key domain.key \
- -new -out domain.csr



Answer the CSR information prompt to complete the process.

The `-key`

option specifies an existing private key (`domain.key`

) that will be used to generate a new CSR. The `-new`

option indicates that a CSR is being generated.

Use this method if you want to renew an existing certificate but you or your CA do not have the original CSR for some reason. It basically saves you the trouble of re-entering the CSR information, as it extracts that information from the existing certificate.

This command creates a new CSR (`domain.csr`

) based on an existing certificate (`domain.crt`

) and private key (`domain.key`

):

- openssl x509 \
- -in domain.crt \
- -signkey domain.key \
- -x509toreq -out domain.csr



The `-x509toreq`

option specifies that you are using an X509 certificate to make a CSR.

If you would like to use an SSL certificate to secure a service but you do not require a CA-signed certificate, a valid (and free) solution is to sign your own certificates.

A common type of certificate that you can issue yourself is a *self-signed certificate*. A self-signed certificate is a certificate that is signed with its own private key. Self-signed certificates can be used to encrypt data just as well as CA-signed certificates, but your users will be displayed a warning that says that the certificate is not trusted by their computer or browser. Therefore, self-signed certificates should only be used if you do not need to prove your service’s identity to its users (e.g. non-production or non-public servers).

This section covers OpenSSL commands that are related to generating self-signed certificates.

Use this method if you want to use HTTPS (HTTP over TLS) to secure your Apache HTTP or Nginx web server, and you do not require that your certificate is signed by a CA.

This command creates a 2048-bit private key (`domain.key`

) and a self-signed certificate (`domain.crt`

) from scratch:

- openssl req \
- -newkey rsa:2048 -nodes -keyout domain.key \
- -x509 -days 365 -out domain.crt



Answer the CSR information prompt to complete the process.

The `-x509`

option tells `req`

to create a self-signed certificate. The `-days 365`

option specifies that the certificate will be valid for 365 days. A temporary CSR is generated to gather information to associate with the certificate.

Use this method if you already have a private key that you would like to generate a self-signed certificate with it.

This command creates a self-signed certificate (`domain.crt`

) from an existing private key (`domain.key`

):

- openssl req \
- -key domain.key \
- -new \
- -x509 -days 365 -out domain.crt



Answer the CSR information prompt to complete the process.

The `-x509`

option tells `req`

to create a self-signed certificate. The `-days 365`

option specifies that the certificate will be valid for 365 days. The `-new`

option enables the CSR information prompt.

Use this method if you already have a private key and CSR, and you want to generate a self-signed certificate with them.

This command creates a self-signed certificate (`domain.crt`

) from an existing private key (`domain.key`

) and (`domain.csr`

):

- openssl x509 \
- -signkey domain.key \
- -in domain.csr \
- -req -days 365 -out domain.crt



The `-days 365`

option specifies that the certificate will be valid for 365 days.

Certificate and CSR files are encoded in PEM format, which is not readily human-readable.

This section covers OpenSSL commands that will output the actual entries of PEM-encoded files.

This command allows you to view and verify the contents of a CSR (`domain.csr`

) in plain text:

- openssl req -text -noout -verify -in domain.csr



This command allows you to view the contents of a certificate (`domain.crt`

) in plain text:

- openssl x509 -text -noout -in domain.crt



Use this command to verify that a certificate (`domain.crt`

) was signed by a specific CA certificate (`ca.crt`

):

- openssl verify -verbose -CAFile ca.crt domain.crt



This section covers OpenSSL commands that are specific to creating and verifying private keys.

Use this command to create a password-protected, 2048-bit private key (`domain.key`

):

- openssl genrsa -des3 -out domain.key 2048



Enter a password when prompted to complete the process.

Use this command to check that a private key (`domain.key`

) is a valid key:

- openssl rsa -check -in domain.key



If your private key is encrypted, you will be prompted for its pass phrase. Upon success, the unencrypted key will be output on the terminal.

Use these commands to verify if a private key (`domain.key`

) matches a certificate (`domain.crt`

) and CSR (`domain.csr`

):

- openssl rsa -noout -modulus -in domain.key | openssl md5
- openssl x509 -noout -modulus -in domain.crt | openssl md5
- openssl req -noout -modulus -in domain.csr | openssl md5



If the output of each command is identical there is an extremely high probability that the private key, certificate, and CSR are related.

This takes an unencrypted private key (`unencrypted.key`

) and outputs an encrypted version of it (`encrypted.key`

):

- openssl rsa -des3 \
- -in unencrypted.key \
- -out encrypted.key



Enter your desired pass phrase, to encrypt the private key with.

This takes an encrypted private key (`encrypted.key`

) and outputs a decrypted version of it (`decrypted.key`

):

- openssl rsa \
- -in encrypted.key \
- -out decrypted.key



Enter the pass phrase for the encrypted key when prompted.

All of the certificates that we have been working with have been X.509 certificates that are ASCII PEM encoded. There are a variety of other certificate encoding and container types; some applications prefer certain formats over others. Also, many of these formats can contain multiple items, such as a private key, certificate, and CA certificate, in a single file.

OpenSSL can be used to convert certificates to and from a large variety of these formats. This section will cover a some of the possible conversions.

Use this command if you want to convert a PEM-encoded certificate (`domain.crt`

) to a DER-encoded certificate (`domain.der`

), a binary format:

- openssl x509 \
- -in domain.crt \
- -outform der -out domain.der



The DER format is typically used with Java.

Use this command if you want to convert a DER-encoded certificate (`domain.der`

) to a PEM-encoded certificate (`domain.crt`

):

- openssl x509 \
- -inform der -in domain.der \
- -out domain.crt



Use this command if you want to add PEM certificates (`domain.crt`

and `ca-chain.crt`

) to a PKCS7 file (`domain.p7b`

):

- openssl crl2pkcs7 -nocrl \
- -certfile domain.crt \
- -certfile ca-chain.crt \
- -out domain.p7b



Note that you can use one or more `-certfile`

options to specify which certificates to add to the PKCS7 file.

PKCS7 files, also known as P7B, are typically used in Java Keystores and Microsoft IIS (Windows). They are ASCII files which can contain certificates and CA certificates.

Use this command if you want to convert a PKCS7 file (`domain.p7b`

) to a PEM file:

- openssl pkcs7 \
- -in domain.p7b \
- -print_certs -out domain.crt



Note that if your PKCS7 file has multiple items in it (e.g. a certificate and a CA intermediate certificate), the PEM file that is created will contain all of the items in it.

Use this command if you want to take a private key (`domain.key`

) and a certificate (`domain.crt`

), and combine them into a PKCS12 file (`domain.pfx`

):

- openssl pkcs12 \
- -inkey domain.key \
- -in domain.crt \
- -export -out domain.pfx



You will be prompted for export passwords, which you may leave blank. Note that you may add a chain of certificates to the PKCS12 file by concatenating the certificates together in a single PEM file (`domain.crt`

) in this case.

PKCS12 files, also known as PFX files, are typically used for importing and exporting certificate chains in Microsoft IIS (Windows).

Use this command if you want to convert a PKCS12 file (`domain.pfx`

) and convert it to PEM format (`domain.combined.crt`

):

```
openssl pkcs12 \
-in domain.pfx \
-nodes -out domain.combined.crt
```


Note that if your PKCS12 file has multiple items in it (e.g. a certificate and private key), the PEM file that is created will contain all of the items in it.

The `openssl version`

command can be used to check which version you are running. The version of OpenSSL that you are running, and the options it was compiled with affect the capabilities (and sometimes the command line options) that are available to you.

The following command displays the OpenSSL version that you are running, and all of the options that it was compiled with:

```
openssl version -a
```


This guide was written using an OpenSSL binary with the following details (the output of the previous command):

```
OpenSSL 1.1.1 11 Sep 2018
built on: Mon Aug 23 17:02:39 2021 UTC
platform: debian-amd64
options: bn(64,64) rc4(16x,int) des(int) blowfish(ptr)
compiler: gcc -fPIC -pthread -m64 -Wa,--noexecstack -Wall -Wa,--noexecstack -g -O2 -fdebug-prefix-map=/build/openssl-Flav1L/openssl-1.1.1=. -fstack-protector-strong -Wformat -Werror=format-security -DOPENSSL_USE_NODELETE -DL_ENDIAN -DOPENSSL_PIC -DOPENSSL_CPUID_OBJ -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DKECCAK1600_ASM -DRC4_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DGHASH_ASM -DECP_NISTZ256_ASM -DX25519_ASM -DPADLOCK_ASM -DPOLY1305_ASM -DNDEBUG -Wdate-time -D_FORTIFY_SOURCE=2
OPENSSLDIR: "/usr/lib/ssl"
ENGINESDIR: "/usr/lib/x86_64-linux-gnu/engines-1.1"
Seeding source: os-specific
```


That should cover how most people use OpenSSL to work with SSL certs. It has many other uses that were not covered here, so feel free to ask or suggest other uses in the comments.

If you are having issues with any of the commands, be sure to comment (and include your OpenSSL version output).

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

This textbox defaults to using **Markdown** to format your answer.

You can type **!ref** in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign up for Infrastructure as a Newsletter.

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Great summary, was recently looking for exactly something like that. Thank you for the write up.

I recently stumbled across https://shaaaaaaaaaaaaa.com/ summarizing the soon to come retirement of SHA-1.

It may be of use also for this tutorial to add the option

to create the CSR.

I did that for a recent request from StartSSL and they offered a certificate accommodating the more secure requirements (passing also A+ on ssllabs.com)

Since you especially describe how to generate CSR for obtaining a certificate, it may be worth adding the option in order to be more future proof.

Best regards Sebastian

Should be

Mitchell - Fantastic post! Just one slight correction:

The option uses a lowercase “f”, as in:

Great article… Thanks for putting it together…

You can also create your own certificate authority and sign your own certificates, then trust your own certificate authority so you don’t get warnings.

https://www.mirthcorp.com/community/forums/showpost.php?p=22124&postcount=4

Hello, great article! I just want to ask you, maybe you know or you can give me a hint or suggestion. How can I create a CSR by passing the information from a json file, not with -subj? Thank you for your time.

How to enter into terminal:

openssl rsa -des3

-in unencrypted.key

-out encrypted.key

Total noob question sorry:

I’ve followed through and been able to create my rsa domain.key, domain.csr and domain.crt THANK YOU SO MUCH! :)

I’m using windows terminal to ssh into my Ubuntu droplet.

Once you started using multi-line commands which are indented I haven’t been able to run these. Can I have your advice please.

I’ve tried copying and pasting, typing, and I read the comment below regarding Ctrl+ins and Shift+ins from community/users/tiangolo with no success. I’ve tried stringing your command lines together into one line but I can’t get a result. I can’t encrypt my private.key for the same reason.

Thank you all in advance, NutAz

I have created a sample project using python to create and manage SSL certificates, if anyone interested can have a look at it. https://github.com/parthibann/shield

Great article. For https ,I had created client private key and certificate key. When i had tried connect the https server below logs were coming. But finally able to connect the server(Taking more time).

Verify requested for (Depth 2):

ceThis certificate has no flags

Verify requested for (Depth 1):

ceThis certificate has no flags

Verify requested for (Depth 0):

ceThis certificate has no flags

connected to server … I had used “openssl verify -verbose -CAFile ca.crt domain.crt” for to create the client certificate and "openssl genrsa -des3 -out domain.key 2048 " for to create privare key.

Could you please tell me if I missed something in my configuration of SSL?

Am i doing wrong?? any suggestions ??please

Great and concise guide. Saved a lot of my time, thanks for sharing!