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