SSL 证书

在当今的数字环境中,网络犯罪日益普遍,保护网站或应用程序变得越来越重要。

实现安全的一种常见方式是使用加密。对称加密和非对称加密在密码学领域经过了广泛研究,也被业界广泛采用,以保护数字系统。SSL 证书建立在非对称加密之上,常用于保护网站:它能够加密客户端与 Web 服务器之间传输的数据,从而保障数据的隐私和安全。

企业、组织和开发者通常会从公共证书颁发机构(CA)获取 SSL 证书。CA 是互联网的信任来源。但在测试、学习、开发或内部用途等场景中,创建自签名 SSL 证书也可能是必要的。

本文将介绍如何使用 OpenSSL 生成自签名 SSL 证书。

分步指南

第 1 步:安装 OpenSSL

网上有很多关于如何安装 OpenSSL 的资料。

  1. 在 Ubuntu 或基于 Debian 的系统上:
1
sudo apt install openssl
  1. 在 CentOS、Fedora 或 RHEL 系统上:
1
sudo yum install openssl
  1. 在 macOS 上:
1
brew install openssl

第 2 步:生成私钥

1
openssl genrsa -out test.key 2048 

运行命令生成一个 2048 位 RSA 私钥(请将 test.key 替换为你选择的文件名):

1
2
3
4
Generating RSA private key, 2048 bit long modulus (2 primes)
..............+++++
.............+++++
e is 65537 (0x010001)

第 3 步:创建证书签名请求

**证书签名请求(CSR)**包含有关你的应用程序和组织的信息。之后可以使用 CSR 生成 SSL 证书。

1
openssl req -new -key test.key -out test.csr
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:CA
State or Province Name (full name) [Some-State]:Ontario 
Locality Name (eg, city) []:Toronto 
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Test 
Organizational Unit Name (eg, section) []:Test 
Common Name (e.g. server FQDN or YOUR name) []:test.com 
Email Address []:[email protected]

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

第 4 步:生成自签名 SSL 证书

1
openssl x509 -req -days 365 -in test.csr -signkey test.key -out test.crt

命令选项和用法可参考:https://www.openssl.org/docs/man1.1.1/man1/x509.html

1
2
3
Signature ok
subject=C = CA, ST = Ontario, L = Toronto, O = Test, OU = Test, CN = test.com, emailAddress = [email protected]
Getting Private key

第 5 步:配置 HTTPS Web 服务器

生成自签名 SSL 证书后,就可以将它用于 Web 服务器。

一个常见的选择是 Nginx。以下是 Nginx HTTPS 配置示例:

1
2
3
4
5
6
7
8
9
server {
    listen              443 ssl;
    server_name         www.example.com;
    ssl_certificate     www.example.com.crt;
    ssl_certificate_key www.example.com.key;
    ssl_protocols       TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;
    ssl_ciphers         HIGH:!aNULL:!MD5;
    ...
}