# 简述下 TLS 握手过程

Issue

欢迎在 Issue 中交流与讨论: Issue 393

Author

回答者: shfshanyue

TLS 握手的详细过程可参考下图:

TLS handshake

以上图片来自 high-performance-browser

wireshark 抓包,也可以看到握手的详细流程,建议抓包加强理解,以下是抓包 https://q.shanyue.tech 时的握手流程

通过 curl -vvv --head 来查看握手信息:

$ curl -vvv --head  https://q.shanyue.tech
*   Trying 111.6.180.235...
* TCP_NODELAY set
* Connected to q.shanyue.tech (111.6.180.235) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/cert.pem
  CApath: none
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Server hello (2):
* TLSv1.2 (IN), TLS handshake, Certificate (11):
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
* TLSv1.2 (IN), TLS handshake, Server finished (14):
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
* TLSv1.2 (OUT), TLS change cipher, Change cipher spec (1):
* TLSv1.2 (OUT), TLS handshake, Finished (20):
* TLSv1.2 (IN), TLS change cipher, Change cipher spec (1):
* TLSv1.2 (IN), TLS handshake, Finished (20):
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* ALPN, server accepted to use h2
* Server certificate:
*  subject: CN=q.shanyue.tech
*  start date: Dec  2 00:00:00 2019 GMT
*  expire date: Dec  1 12:00:00 2020 GMT
*  subjectAltName: host "q.shanyue.tech" matched cert's "q.shanyue.tech"
*  issuer: C=US; O=DigiCert Inc; OU=www.digicert.com; CN=Encryption Everywhere DV TLS CA - G1
*  SSL certificate verify ok.
* Using HTTP2, server supports multi-use
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* Using Stream ID: 1 (easy handle 0x7f95ba80dc00)

# 握手过程

在 TLS 1.2 中,握手协议过程需要耗费两个 RTT,过程如下

  1. [OUT] Client Hello,客户端选出自身支持的 TLS 版本号、cipher suites、一个随机数、SessionId 传送给服务器端 (有可能可服用 Session)
  2. [IN] Server Hello,服务器端选出双方都支持的 TLS 版本,cipher suite 、一个随机数、SeesionId 给客户端
  3. [IN] Certificate,服务器端给客户端发送证书,用以身份验证及提供公钥
  4. [IN] Server Key Exchange,服务器端给客户端发送秘钥交换算法的一些参数
  5. [IN] Server Finished
  6. [OUT] Client Key Exchange,客户端给服务器端发送秘钥交换算法的一些参数,计算出预备主密钥 (pre master key),作为随机数传递给服务器端 (这个随机数是安全的)。双方根据三个随机数生成对称加密中的秘钥
  7. [OUT] Change Cipher Spec,告知对方以后的消息将要使用TLS记录层协议进行加密
  8. [OUT] Finished,发送第一条加密的消息并完整性验证
  9. [IN] Change Cipher Spec,告知以后的消息将要使用TLS记录层协议进行加密
  10. [IN] Finished,发送第一条加密的消息并完整性验证

# 相关链接

扫码关注公众号全栈成长之路,并发送

即可在关注期间无限制浏览本站全部文章内容

你也可以在文章关于回复公众号扫码解锁全站的技术实现中获得解锁代码,永久解锁本站全部文章