建立並使用https證書

itread01 2021-01-22 01:16:48
Https 使用 技术开发 itread01 建立


[toc]## 前言> https要比http更安全些,因此可以配置Nginx伺服器使用證書,客戶端就會去第三方平臺校驗證書。> 但是我們自己的伺服器和客戶端只是想要加個密而已,也沒必要跑去第三方平臺校驗證書,省錢方便。> 因此研究了一下生成證書和使用證書的筆記。## 產生證書> 網上很多都是用openssl命令列去產生,有點麻煩,主要是不想記一堆命令,因此找到一個非常簡單的專案。> 專案地址: ,需要環境有`python3、openssl、make`這三個工具。> 使用方法`cd tls-gen/basic & make CN=www.janbar.com`,這樣客戶端必須用該域名進行訪問,並且要帶上對應證書。> 最終產生如下三個檔案,`testca/cacert.pem`是客戶端使用,`server/cert.pem,server/key.pem`是伺服器使用。```shtestca/ cacert.pemserver/ cert.pem key.pem```> 記得在`c:\Windows\System32\drivers\etc\hosts`增加`127.0.0.1 www.janbar.com`,準備證書原始碼檔案`cert.go`,內容如下:```govar ( certPEMBlock = []byte(`-----BEGIN CERTIFICATE-----MIIDfjCCAmagAwIBAgIBATANBgkqhkiG9w0BAQsFADAxMSAwHgYDVQQDDBdUTFNHZW5TZWxmU2lnbmVkdFJvb3RDQTENMAsGA1UEBwwEJCQkJDAeFw0yMTAxMjExMDExMjJaFw0zMTAxMTkxMDExMjJaMCoxFzAVBgNVBAMMDnd3dy5qYW5iYXIuY29tMQ8wDQYDVQQKDAZzZXJ2ZXIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDjpGglwTB/B1N07ZhwaP3erxDZDYhtDqir7fiuZQxgmWzQ5UeU7gp5ntu8bLXpFmVSs7si0WyOKbGoPi8Q/cvkZix3zkClAvS7vM2zW+0qa3Fp4dYRg42cjYAgenfpC0M5fKHhnBKjzWFOiTOyJIPcNpvhAcV9dvQIdgX64g/+M2J3pMK2+tU5Z49Nc1KqyUS//zFo4C+HAk7Wbkc3Kgx8t4OZo0ddTdmLsPfRIU3hxqehRxhk7OccHBBb6JOVSF213h6kWwauN9djiO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M96KFm3cz99HzxBxX71hKBF6kV6GKdKQkl4Ocx6HLiHiIWviTFr0qNVNcafrdDwWa9dRg5daxKOOE9XoLYHWDmDaKgAIz4x5tDUDhAT4u7hkHQACz4TMlQG6L2uXPI0IiTv5185wvgNNpx2V3d9rlvq6AOWjhSrZ9rfuSnt3UbRjKmbZAGcaFb3Gqr7MdIZuYOB9CN7Ho0wKNxKk00o7jav298tHinDdKvwYdAf8IgkEaHgBeFsPfNy8VGe4XWNdVT7HkzpOPHM7SBK+cEpKnylKkEdKb9ubSCe8NA4RpuKbeo36IS6Bcfmr-----END CERTIFICATE-----`))```## 測試https伺服器> 測試程式碼檔案`test_https.go`如下:```gopackage mainimport ( "crypto/tls" "crypto/x509" "io" "net/http" "os" "time")func main() { http.Handle("/", http.FileServer(http.Dir("."))) go func() { cf, err := tls.X509KeyPair(certPEMBlock, keyPEMBlock) if err != nil { panic(err) } err = (&http.Server{TLSConfig: &tls.Config{ Certificates: []tls.Certificate{cf}, }}).ListenAndServeTLS("", "") if err != nil { panic(err) } }() time.Sleep(time.Second) // 上面是http伺服器的執行 // 下面是http客服端訪問 roots := x509.NewCertPool() ok := roots.AppendCertsFromPEM(rootPEM) if !ok { panic("failed to parse root certificate") } client := &http.Client{Transport: &http.Transport{ TLSClientConfig: &tls.Config{RootCAs: roots}, }} req, err := http.NewRequest(http.MethodGet, "https://www.janbar.com", nil) if err != nil { panic(err) } resp, err := client.Do(req) if err != nil { panic(err) } io.Copy(os.Stdout, resp.Body) resp.Body.Close()}```> 執行`go run test_https.go cert.go`效果如下,顯示了執行目錄下的檔案列表:```go
test.exetest.go
```## 用tls加密tcp連線> 測試程式碼`test_tcp.go`檔案,原始碼如下:```gopackage mainimport ( "crypto/tls" "crypto/x509" "fmt" "net" "time")func main() { addr := "www.janbar.com:8080" go func() { err := tcpServer(addr) if err != nil { panic(err) } }() time.Sleep(time.Second) err := tcpClient(addr) if err != nil { panic(err) }}func tcpServer(addr string) error { cf, err := tls.X509KeyPair(certPEMBlock, keyPEMBlock) if err != nil { return err } s, err := tls.Listen("tcp", addr, &tls.Config{Certificates: []tls.Certificate{cf}}) if err != nil { return err } defer s.Close() client := func(c net.Conn) error { tNow := time.Now().String() buf := make([]byte, len(tNow)) n, err := c.Read(buf) if err != nil { return err } fmt.Printf("server [%s]\n", buf[:n]) _, err = c.Write([]byte(tNow)) return err } for { l, err := s.Accept() if err != nil { return err } go func(c net.Conn) { defer c.Close() if err := client(c); err != nil { fmt.Println(err) } }(l) }}func tcpClient(addr string) error { roots := x509.NewCertPool() ok := roots.AppendCertsFromPEM(rootPEM) if !ok { panic("failed to parse root certificate") } c, err := tls.Dial("tcp", addr, &tls.Config{RootCAs: roots}) if err != nil { return err } defer c.Close() tNow := time.Now().String() c.Write([]byte(tNow)) buf := make([]byte, len(tNow)) n, err := c.Read(buf) if err != nil { return err } fmt.Printf("client [%s]\n", buf[:n]) return nil}```> 執行`go run test_tcp.go cert.go`效果如下:```goserver [2021-01-21 21:09:51.7942154 +0800 CST m=+1.011929701]client [2021-01-21 21:09:51.7852425 +0800 CST m=+1.002956801]```## 總結> 以前使用的tcp連線沒有任何加密,現在想想還是不安全。用上證書,起碼會校驗訪問域名和證書等資訊,多少回安全一些。> 以上都是用來測試等等,如果需要正式使用證書,還是去各大網站花錢申請吧。我一直用萬網的免費證書,但是有效期只有一
版权声明
本文为[itread01]所创,转载请带上原文链接,感谢
https://www.itread01.com/content/1611248582.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云