Foreword
在建立 tls 相关安全连接时,会用到各种各样的加密证书文件。golang 中会需要配置一个tls.Config{}
结构体,但是 golang 常见的是需要提供rootCA
文件,certCA
和privateey
文件。当遇到了一种.pfx
加密码的加密证书文件,处理方式见下。
Code
package main
import (
"crypto/tls"
"crypto/x509"
"github.com/labstack/gommon/log"
"golang.org/x/crypto/pkcs12"
"os"
)
func main() {
certPath := "/certFile.pfx"
certPassword := "xxxxxx"
certData, err := os.ReadFile(certPath)
if err != nil {
log.Error("Failed to read certificate file:", err)
return
}
privateKey, certificate, err := pkcs12.Decode(certData, certPassword)
if err != nil {
log.Fatal("Failed to decode PKCS12 certificate:", err)
}
certPool := x509.NewCertPool()
certPool.AddCert(certificate)
tlsCert := tls.Certificate{
Certificate: [][]byte{certificate.Raw},
PrivateKey: privateKey,
Leaf: certificate,
}
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{tlsCert},
RootCAs: certPool,
InsecureSkipVerify: true,
}
_ = tlsConfig
//...
//供加密通信使用 mqtt、http、tcp...
}
Conclusion
供各位 gopher 碰到相似问题时参考~