go - 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")
}
解决方案
我可以在不断调试后解决问题。这是它的代码
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("",""))
推荐阅读
- c# - SQL 如何替换一个值
- python - 使用 python 和请求,如何进行正确的 POST 调用以及在哪里找到标头?
- android - FirebaseAppDistribution:appDistributionUpload gradle 命令中缺少应用程序 ID
- mysql - 跨列和行计算值的实例
- javascript - 使用 redux 钩子时使用 redux 操作的最佳选择是什么?
- sql - Impala 2.11:AnalysisException:选择列表中不支持子查询
- swift - 在 SwiftUI 中获取当前的经纬度
- c++ - 是否可以禁止一个类被动态转换为?
- git - Git - 将发布分支合并到主分支
- tensorflow - 任何想法如何解决激活函数的问题?