首页 > 解决方案 > go - 如何使用证书存储中的证书并在 gin 框架中运行 TLS?

问题描述

我当前的应用程序使用 TLS 启动 Go Gin Web 服务器,并从本地文件系统加载证书和密钥。我想从证书存储加载这些文件,或者我想将证书和私钥作为字节数组而不是文件路径传递。

package main

import (
    "github.com/gin-gonic/gin"
)

func main() {
    g := gin.Default()
    g.GET("/hello/:name", func(c *gin.Context) {
        c.String(200, "Hello %s", c.Param("name"))
    })
    g.RunTLS(":3000", "./certs/server.crt", "./certs/server.key")
}

标签: gosslx509certificatego-gin

解决方案


我可以在不断调试后解决问题。这是它的代码


cert := &x509.Certificate{
        SerialNumber: big.NewInt(1658),
        Subject: pkix.Name{
            Organization:  []string{"ORGANIZATION_NAME"},
            Country:       []string{"COUNTRY_CODE"},
            Province:      []string{"PROVINCE"},
            Locality:      []string{"CITY"},
            StreetAddress: []string{"ADDRESS"},
            PostalCode:    []string{"POSTAL_CODE"},
        },
        NotBefore:    time.Now(),
        NotAfter:     time.Now().AddDate(10, 0, 0),
        SubjectKeyId: []byte{1, 2, 3, 4, 6},
        ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
        KeyUsage:     x509.KeyUsageDigitalSignature,
    }
    priv, _ := rsa.GenerateKey(rand.Reader, 2048)
    pub := &priv.PublicKey

    // Sign the certificate
    certificate, _ := x509.CreateCertificate(rand.Reader, cert, cert, pub, priv)

    certBytes := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certificate})
    keyBytes := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})

    // Generate a key pair from your pem-encoded cert and key ([]byte).
    x509Cert, _ := tls.X509KeyPair(certBytes, keyBytes)

    tlsConfig := &tls.Config{
            Certificates: []tls.Certificate{x509Cert}}
    server := http.Server{Addr: ":3000", Handler: router, TLSConfig: tlsConfig}

    glog.Fatal(server.ListenAndServeTLS("",""))



推荐阅读