Golang - 具有自签名证书的TLS

Zap*_*Zap 27 ssl go

我正在尝试使用自签名服务器证书建立TLS连接.

我使用以下示例代码生成证书:http://golang.org/src/pkg/crypto/tls/generate_cert.go

我的相关客户端代码如下所示:

// server cert is self signed -> server_cert == ca_cert
CA_Pool := x509.NewCertPool()
severCert, err := ioutil.ReadFile("./cert.pem")
if err != nil {
    log.Fatal("Could not load server certificate!")
}
CA_Pool.AppendCertsFromPEM(severCert)

config := tls.Config{RootCAs: CA_Pool}

conn, err := tls.Dial("tcp", "127.0.0.1:8000", &config)
if err != nil {
    log.Fatalf("client: dial: %s", err)
}
Run Code Online (Sandbox Code Playgroud)

以及相关的服务器代码:

cert, err := tls.LoadX509KeyPair("./cert.pem", "./key.pem")
config := tls.Config{Certificates: []tls.Certificate{cert}}
listener, err := tls.Listen("tcp", "127.0.0.1:8000", &config)

for {
    conn, err := listener.Accept()
    if err != nil {
        log.Printf("server: accept: %s", err)
        break
    }
    log.Printf("server: accepted from %s", conn.RemoteAddr())
    go handleConnection(conn)
}
Run Code Online (Sandbox Code Playgroud)

因为服务器证书是自签名的,所以使用与服务器和客户端CA_Pool相同的证书,但是这似乎不起作用,因为我总是收到此错误:

client: dial: x509: certificate signed by unknown authority 
(possibly because of "x509: invalid signature: parent certificate
cannot sign this kind of certificate" while trying to verify 
candidate authority certificate "serial:0")
Run Code Online (Sandbox Code Playgroud)

我的错是什么?

Zap*_*Zap 28

它最终与x509.CreateCertificate中构建的go一起工作,问题是我没有设置IsCA:true标志, 我只设置了x509.KeyUsageCertSign,这使得创建自签名证书工作,但在验证证书链时崩溃了.


Kyl*_*ons 10

问题是您需要在服务器端配置中使用CA证书,并且此CA必须已签署服务器的证书.

我已经编写了一些将生成 CA证书的Go代码,但它尚未经过任何人的审核,并且主要是用于玩客户端证书的玩具.最安全的赌注可能是用于openssl ca生成和签署证书.基本步骤将是:

  1. 生成CA证书
  2. 生成服务器密钥
  3. 使用CA证书对服务器密钥进行签名
  4. 将CA证书添加到客户端 tls.Config RootCAs
  5. tls.Config使用服务器密钥和签名证书设置服务器.