vid*_*.s. 5 ssl go x509certificate go-gin
我当前的应用程序使用 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")
}
Run Code Online (Sandbox Code Playgroud)
经过不断调试,问题得以解决。这是它的代码
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("",""))
Run Code Online (Sandbox Code Playgroud)