cert_helper.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. package helper
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "google.golang.org/grpc/credentials"
  6. "os"
  7. )
  8. func GetCredentials(certFile, keyFile, caFile string) credentials.TransportCredentials {
  9. // 证书认证-双向认证
  10. // 从证书相关文件中读取和解析信息,得到证书公钥、密钥对
  11. cert, err := tls.LoadX509KeyPair(certFile,
  12. keyFile)
  13. if err != nil {
  14. panic(err)
  15. }
  16. // 创建一个新的、空的 CertPool
  17. certPool := x509.NewCertPool()
  18. ca, err := os.ReadFile(caFile)
  19. if err != nil {
  20. panic(err)
  21. }
  22. //注意这里只能解析pem类型的根证书,所以需要的是ca.pem
  23. // 尝试解析所传入的 PEM 编码的证书。如果解析成功会将其加到 CertPool 中,便于后面的使用
  24. certPool.AppendCertsFromPEM(ca)
  25. // 构建基于 TLS 的 TransportCredentials 选项
  26. creds := credentials.NewTLS(&tls.Config{
  27. // 设置证书链,允许包含一个或多个
  28. Certificates: []tls.Certificate{cert},
  29. ServerName: "localhost", //注意这里的参数为配置文件中所允许的ServerName,也就是其中配置的DNS...
  30. RootCAs: certPool,
  31. })
  32. return creds
  33. }