证书

为什么要证书

防止中间人攻击(MITM:Man-in-the-Middle Attack)

中间人从一开始就介入,客户端与中间人互相通信,中间人与服务端互相通信,客户端和服务端不能发现中间人的存在。

而通过证书,客户端与服务端互相发送自己的证书给对方,通过验证证书就能判断此证书用于哪些域名/ip,如果发现对方不是此证书的使用者或者证书不被信任,那么就说明可能对方是中间人。

证书怎么生成的

  1. 证书数据通过签名哈希算法得到hash证书数据里含有证书使用者的公钥
  2. 再通过证书发行者的私钥根据签名算法加密hash生成一个签名

证书数据+签名+一些元信息,如签名哈希算法、签名算法等就是证书。

验证证书签名

  1. 得到证书后,根据证书中证书数据通过签名哈希算法得到hash
  2. 再通过证书发行者的公钥(证书里有发行者的唯一识别编号),根据签名算法解密签名得到hash2
  3. 如果hash2hash相等,那么说明,证书确实是被这个发行者签名的并且内容没有被修改。
  4. 如果这个发行者是自己信任的那么这个证书就被信任。

如何获得对应CA的公钥

证书颁发机构叫做certificate authority,是作为证书的发行者。

CA也有自己的证书(被其它CA签名,或者自己签名),那么只要获得这个CA的证书(不知道如何获得)就能得到CA的公钥,但是这时还需要验证这个CA的证书是否被自己信任。

如何验证:如果系统内置了此CA的证书,那么这个证书就是被信任的。如果没有,那么需要验证此证书的签名(即继续找给这个证书签名的CA,一层一层找,直到某个CA的证书被自己信任,此时就能判定签名是否正确)。

创建一对非对称密钥

1
2
3
4
# 生成私钥
openssl genrsa -out pri.key 1024
# 生成此私钥对应的公钥,一样的私钥每次生成的公钥都是一样的
openssl rsa -in pri.key -pubout -out pub.key

生成证书请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 通过私钥生成证书请求
openssl req -key pri.key -new -out certificate.req


root@VM_0_17_centos ~/d/https# openssl req -key pri.key -new -out c.req
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) [XX]:CN
State or Province Name (full name) []:JiangXi
Locality Name (eg, city) [Default City]:GanZhou
Organization Name (eg, company) [Default Company Ltd]:iails
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:iails
Email Address []:iailsfe@163.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:xxx
An optional company name []:
root@VM_0_17_centos ~/d/https#
root@VM_0_17_centos ~/d/https# ll
total 12K
-rw-r--r-- 1 root root 696 Oct  7 17:27 certificate.req
-rw-r--r-- 1 root root 887 Oct  7 17:18 pri.key
-rw-r--r-- 1 root root 272 Oct  7 17:23 pub.key

生成证书

X.509是密码学里公钥证书的格式标准。X.509证书里含有公钥、身份信息和签名信息。

1
2
# 需要CA自己的私钥和证书,然后就能通过证书请求生成一个自己签名后的证书
openssl x509 -req -in certificate.req -CA cacertificate.pem -CAkey capri.key -out certificate.pem

还有一种证书,称为Self-Signed Certificate,就是自己给自己签名。

查看证书内容

1
openssl x509 -in certificate.pem -noout -text

https通信

计算对称密钥的算法是:Diffie Hellman 算法

如果用的是ephemeral Diffie Hellman 算法,server hello done前面还有一个server key exchange.https://security.stackexchange.com/questions/79482/whats-the-purpose-of-server-key-exchange-when-using-ephemeral-diffie-hellman#:~:text=In%20Diffie%2DHellman,the%20ServerKeyExchange.

貌似没有 client certificate,需要server发一个certificate request,client才会发client certificate。

为什么需要三个随机数,为了防止重放攻击 https://security.stackexchange.com/a/218492

https流程