Preface

https than http It's safer , So you can configure Nginx The server uses certificates , The client will go to the third party platform to verify the certificate .

But our own servers and clients just want to encrypt , There is no need to run to a third-party platform to verify the certificate , Saving money and convenience .

So I studied the notes of generating and using certificates .

Generate Certificate

A lot of it is used on the Internet openssl Command line to generate , A little bit of a problem , The main reason is that I don't want to memorize a lot of commands , So find a very simple project .

Project address :https://github.com/michaelklishin/tls-gen, Need environment to have python3、openssl、make These three tools .

Usage method cd tls-gen/basic & make CN=www.janbar.com, So the client must use the domain name to access , And bring the corresponding certificate .

Finally, the following three documents are produced ,testca/cacert.pem It's client use ,server/cert.pem,server/key.pem It's the server that uses .

testca/
cacert.pem server/
cert.pem
key.pem

Remember in c:\Windows\System32\drivers\etc\hosts increase 127.0.0.1 www.janbar.com, Prepare certificate source file cert.go, The contents are as follows :


var (
certPEMBlock = []byte(`-----BEGIN CERTIFICATE-----
MIIDfjCCAmagAwIBAgIBATANBgkqhkiG9w0BAQsFADAxMSAwHgYDVQQDDBdUTFNH
ZW5TZWxmU2lnbmVkdFJvb3RDQTENMAsGA1UEBwwEJCQkJDAeFw0yMTAxMjExMDEx
MjJaFw0zMTAxMTkxMDExMjJaMCoxFzAVBgNVBAMMDnd3dy5qYW5iYXIuY29tMQ8w
DQYDVQQKDAZzZXJ2ZXIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDj
pGglwTB/B1N07ZhwaP3erxDZDYhtDqir7fiuZQxgmWzQ5UeU7gp5ntu8bLXpFmVS
s7si0WyOKbGoPi8Q/cvkZix3zkClAvS7vM2zW+0qa3Fp4dYRg42cjYAgenfpC0M5
fKHhnBKjzWFOiTOyJIPcNpvhAcV9dvQIdgX64g/+M2J3pMK2+tU5Z49Nc1KqyUS/
/zFo4C+HAk7Wbkc3Kgx8t4OZo0ddTdmLsPfRIU3hxqehRxhk7OccHBBb6JOVSF21
3h6kWwauN9djiOixpsS3jr1SVEGrhZk6zaOtZ+MSOg410pr3u79kdIuCYGNhvdDW
soyNB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hxyglarRNrneZKM96KFm3c
z99HzxBxX71hKBF6kV6GKdKQkl4Ocx6HLiHiIWviTFr0qNVNcafrdDwWa9dRg5da
xKOOE9XoLYHWDmDaKgAIz4x5tDUDhAT4u7hkHQACz4TMlQG6L2uXPI0IiTv5185w
vgNNpx2V3d9rlvq6AOWjhSrZ9rfuSnt3UbRjKmbZAGcaFb3Gqr7MdIZuYOB9CN7H
o0wKNxKk00o7jav298tHinDdKvwYdAf8IgkEaHgBeFsPfNy8VGe4XWNdVT7HkzpO
PHM7SBK+cEpKnylKkEdKb9ubSCe8NA4RpuKbeo36IS6Bcfmr
-----END CERTIFICATE-----`)
)

test https The server

Test code file test_https.go as follows :

package main
import (
"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)
// It's on it http Running the server // Here is http Customer service access
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()
}

perform go run test_https.go cert.go The effect is as follows , Shows the list of files in the running Directory :

<pre>
<a href="test.exe">test.exe</a>
<a href="test.go">test.go</a>
</pre>

use tls encryption tcp Connect

Test code test_tcp.go file , Source code is as follows :

package main
import (
"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
}

perform go run test_tcp.go cert.go The effect is as follows :

server [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]

summary

Used before tcp The connection doesn't have any encryption , Now it's not safe . Use the certificate , At least check access domain name and certificate information , How many times is it safer .

All of the above are for testing and so on , If you need to formally use a certificate , Or go to the major websites to spend money to apply for it . I've been using Wannet's free certificate , But it's only valid for one year .

Create and use https More about certificates

  1. Windows IIS ASP.NET Core Create and use HTTPS Self signed certificate

    Why use Https Don't say . First step : Create a self signed certificate . stay Windows Lower open PowerShell, Paste the following text in : # setup certificate properties includi ...

  2. establish https certificate

    First milestone : establish https certificate Create file authentication Directory mkdir /application/nginx/key/ -p Create an authentication file in the authentication directory openssl req -new -x509 -node ...

  3. [ Re posting ] use OpenSSL Create a file that can be used for https Certificate

    use OpenSSL Create a file that can be used for https Certificate At the meeting When it comes to safety It's a simple trick I'll use it in the future nginx Forwarding is better . https://blog.csdn.net/joyous/art ...

  4. Centos7 establish CA And apply for a certificate from https://www.cnblogs.com/mingzhang/p/8949541.html

    Centos7.3 establish CA And apply for a certificate openssl Configuration file for :/etc/pki/tls/openssl.cnf Important parameter configuration path dir   = /etc/pki/CA               ...

  5. An empty line causes deployment on alicloud load balancing https The problem with certificates

    Today, I bought... On Alibaba cloud WoSign Of https certificate , After the certificate is issued , Download the certificate file from the console , Altogether 2 File , One is .key file ( Private key file ), One is .pem file ( Certificate file ). And then load balancing in alicloud “ Certificate management ” ...

  6. self-control Https Certificate and Spring Boot and Nginx Use in

    vernacular Https In the article , It introduces Https The purpose and working principle of existence , But most of them are in favor of the introduction of principles , This paper introduces how to make a browser certified one step by step Https certificate , And explain in Spring Boot The environment and Nginx Ring ...

  7. iOS—— About creating a real debugging Certificate ( Issue certificate , test ( debugging ) certificate , Push debugging Certificate )、iOS Developer account application Please use the developer account to iTunes connect Check the status

  8. self-control Https Certificate and Spring Boot and Nginx Use in ( turn )

    vernacular Https In the article , It introduces Https The purpose and working principle of existence , But most of them are in favor of the introduction of principles , This paper introduces how to make a browser certified one step by step Https certificate , And explain in Spring Boot The environment and Nginx Ring ...

  9. HTTPS Certificate configuration

    HTTPS Certificate configuration Now both Alibaba cloud and Tencent cloud support applications HTTPS certificate , No more mention of , You can do it yourself if you need it google Solution . In this paper, we mainly introduce through letsencrypt Apply for free HTTPS certificate , And match it with ...

  10. Free configuration for your website HTTPS certificate

    Now more and more websites or services have been added HTTPS certificate , Apple AppStore. Wechat applets have also forced developers to provide HTTPS The back-end interface of . In Ali cloud / Tencent cloud has a one-year free Symantec SSL Certificates are available ...

Random recommendation

  1. C Language preprocessing

    This is a 2016 The last blog of the year , The plan at the beginning of the year is to write 12 blog , Once a month ,1/3 Reprint ,2/3 original , It seems that it can't be realized ! -- Digression . What I'm going to write today is C Preprocessor in language , We often talk about the usage of macro definition . Why write this ...

  2. python Read and write csv file

    Read csv file : def readCsv(): rows=[] with file(r'E:\py\py01\Data\system.csv','rb') as f: reads=csv.reader ...

  3. Samba After sharing the file in Windows Inaccessible issues on

    /etc/samba/smb.conf The configuration is as follows : #============================ Share Definitions ========================== ...

  4. 2016 ACM/ICPC Asia Regional Qingdao Online HDU5883

    link :http://acm.hdu.edu.cn/showproblem.php?pid=5883 solution : First judge whether it's Euler road or not , Then enumeration #pragma comment(linker, "/S ...

  5. Indexing and optimization like Inquire about

    1. like %keyword     Index failure , Use a full table scan . But you can flip the function +like Before fuzzy query + Index the flipped function = Go flip function index , No full scan . 2. like keyword%     The index has ...

  6. understand SqlServer Query plan

    understand SqlServer Query plan Read the directory Start SQL Server How to find records SQL Server Join The way More specific implementation process Index statistics : Selection basis of query plan Optimize view query Recommended reading -M ...

  7. Visual Studio 2010 Open the crystal report is binary

    The crystal report is 64 Bit machine is not installed successfully resolvent To http://www.cnblogs.com/siyunianhua/p/4806513.html download   Crystal Report VS2010 edition IDE Install the Standard Version SAP ...

  8. Android- How to package with the command line

    Reprint please indicate the source :http://blog.csdn.net/goldenfish1919/article/details/40978859 1. Generate R file aapt package -f -m -J . ...

  9. Binary tree Python Realization

    The definition and basic terms of tree Tree structure is an important class of nonlinear data structures , Among them, trees and binary trees are most commonly used , Is a hierarchy defined by branching relationships . Tree structure exists widely in the objective world , Such as the genealogy of human society and various social organizations : In the field of computer, there are also a wide range of ...

  10. 【 turn 】Android in dip(dp) And px Unit conversion between

    Android in dip(dp) And px Unit conversion between dp This unit may be useful to web The developers are relatively unfamiliar , Because we usually use px( Pixels ) however , Now in the beginning android After applications and games , Basically, it's all converted into dp Action is the unit , because ...