如何在Go的gin框架中使用证书存储中的证书并运行TLS?

huangapple go评论104阅读模式
英文:

How to use a certificate from a certificate store and run TLS in gin framework in go?

问题

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

package main

import (
	"crypto/tls"
	"crypto/x509"
	"io/ioutil"
	"log"

	"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"))
	})

	// 从证书文件加载证书和密钥
	cert, err := tls.LoadX509KeyPair("./certs/server.crt", "./certs/server.key")
	if err != nil {
		log.Fatal(err)
	}

	// 创建一个空的证书池
	caCertPool := x509.NewCertPool()

	// 从证书文件加载根证书
	caCert, err := ioutil.ReadFile("./certs/ca.crt")
	if err != nil {
		log.Fatal(err)
	}

	// 将根证书添加到证书池
	caCertPool.AppendCertsFromPEM(caCert)

	// 创建一个自定义的TLS配置
	tlsConfig := &tls.Config{
		Certificates: []tls.Certificate{cert},
		RootCAs:      caCertPool,
	}

	// 将自定义的TLS配置应用到服务器
	server := &http.Server{
		Addr:      ":3000",
		TLSConfig: tlsConfig,
	}

	// 启动服务器
	err = server.ListenAndServeTLS("", "")
	if err != nil {
		log.Fatal(err)
	}
}

请注意,上述代码假设您的证书和密钥文件位于"./certs"目录下,并且您还有一个名为"ca.crt"的根证书文件。您需要根据实际情况修改文件路径和文件名。

英文:

My current application starts a Go Gin web server using TLS and loads the cert and key from a local file system. I want to load these files from a cert store or I want to pass the certificate and private key as byte array instead of file path.

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")
}

答案1

得分: 7

我可以在持续调试后解决这个问题。
以下是代码的翻译:

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

// 签署证书
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)})

// 从 pem 编码的证书和密钥 ([]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("", ""))

希望对你有帮助!

英文:

I could solve the problem after continuous debug.
Here is the code for it


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("",""))


huangapple
  • 本文由 发表于 2021年5月21日 02:03:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/67625752.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定