本文主要介绍了自签CA、服务端和客户端双向认证,主要包括自签CA、GolangGrpc服务端和客户端双向认证的相关内容,需要的朋友可以参考下
参考地址:https://blog.csdn.net/dl962454/article/details/124350199
一、双向认证
1.1 CA根证书生成
在openssl的bin目录下新建一个配置文件ca.conf,文件内容如下:
[ req ]
default_bits = 2048
distinguished_name = req_distinguished_name
[ req_distinguished_name ]
countryName = Country Name (2 letter code)
countryName_default = CN
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = SiChuan
localityName = Locality Name (eg, city)
localityName_default = Chengdu
organizationName = Organization Name (eg, company)
organizationName_default = Step
commonName = CommonName (e.g. server FQDN or YOUR name)
commonName_max = 64
commonName_default = tonghua
依次执行下面的命令,执行过程中遇到的填写国家之类的直接Enter跳过,选择配置文件中默认的,从而生成**CA私钥(ca.key)、*
*签名请求(ca.csr) 和 签名证书(ca.crt):
openssl genrsa -out ca.key 2048
openssl req -new -sha256 -out ca.csr -key ca.key -config ca.conf
openssl x509 -req -days 3650 -in ca.csr signkey ca.key out ca.crt //这地方的输出可以改写成ca.pem,改写后后面命令中也要同步
1.2 签发服务端证书
接下来创建服务端配置文件server.conf,文件内容如下:
[ req ]
default_bits = 2048
distinguished_name = req_distinguished_name
[ req_distinguished_name ]
countryName = Country Name (2 letter code)
countryName_default = CN
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = SiChuan
localityName = Locality Name (eg, city)
localityName_default = Chengdu
organizationName = Organization Name (eg, company)
organizationName_default = Step
commonName = CommonName (e.g. server FQDN or YOUR name)
commonName_max = 64
commonName_default = tonghua
[ req_ext ]
# 添加subjectAltName
subjectAltName = @alt_names
# 文件末尾添加. www.p-pp.cn代表允许的ServerName,自己随便写
[alt_names]
DNS.1 = www.p-pp.cn
IP = 127.0.0.1
同样,使用上面得到的CA根证书(ca.crt)签发服务端证书,依次执行下面命令生成服务端的密钥、签名请求和签名证书:
// 服务端私钥
openssl genrsa -out server.key 2048
//服务端签名请求
openssl req -new -sha256 -out server.csr -key server.key -config server.conf
//用根证书签发服务端证书server.pem
openssl x509 -req -days 3650 -CA ca.crt -CAkey ca.key -CAcreateserial -in server.csr -out server.pem -extensions req_ext -extfile server.conf
1.3 签发客户端证书
建立配置文件client.conf:
[ req ]
default_bits = 2048
distinguished_name = req_distinguished_name
[ req_distinguished_name ]
countryName = Country Name (2 letter code)
countryName_default = CN
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = SiChuan
localityName = Locality Name (eg, city)
localityName_default = Chengdu
organizationName = Organization Name (eg, company)
organizationName_default = Step
commonName = CommonName (e.g. server FQDN or YOUR name)
commonName_max = 64
commonName_default = tonghua
[ req_ext ]
subjectAltName = @alt_names
[alt_names]
DNS.1 = www.p-pp.cn
IP = 127.0.0.1
执行下面命令生成客户端密钥、证书等:
openssl ecparam -genkey -name secp384r1 -out client.key
openssl req -new -sha256 -out client.csr -key client.key -config client.conf
openssl x509 -req -days 3650 -CA ca.crt -CAkey ca.key -CAcreateserial -in client.csr -out client.pem -extensions req_ext -extfile client.conf
1.4 服务端代码改写
服务端改写,首先拷贝ca.pem、server.key和server.pem到服务端项目中,改写代码:
package main
import (
"crypto/tls"
"crypto/x509"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"grpcpro/services"
"io/ioutil"
"log"
"net"
)
const (
// Address gRPC服务地址
Address = "127.0.0.1:8888"
)
func main() {
// TLS认证
//从证书相关文件中读取和解析信息,得到证书公钥、密钥对
cert, _ := tls.LoadX509KeyPair("keys/server.pem", "keys/server.key")
certPool := x509.NewCertPool() //初始化一个CertPool
ca, _ := ioutil.ReadFile("keys/ca.pem")
certPool.AppendCertsFromPEM(ca) //解析传入的证书,解析成功会将其加到池子中
creds := credentials.NewTLS(&tls.Config{ //构建基于TLS的TransportCredentials选项
Certificates: []tls.Certificate{cert}, //服务端证书链,可以有多个
ClientAuth: tls.RequireAndVerifyClientCert, //要求必须验证客户端证书
ClientCAs: certPool, //设置根证书的集合,校验方式使用 ClientAuth 中设定的模式
})
rpcServer := grpc.NewServer(grpc.Creds(creds)) //实例化grpc Server
//创建带ca证书验证的服务端
services.RegisterProdServiceServer(rpcServer, new(services.ProdService))
listen, _ := net.Listen("tcp", Address) //设置传输协议和监听地址
log.Println("Listen on " + Address + " with TLS")
rpcServer.Serve(listen)
}
1.5 客户端代码改写
客户端改写:同样要拷贝ca.pem、client.key和client.pem到客户端项目中,改写代码:
package main
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"grpcClient/services"
"io/ioutil"
"log"
)
const (
// Address gRPC服务地址
Address = "127.0.0.1:8888"
)
func main() {
// TLS连接
//从证书相关文件中读取和解析信息,得到证书公钥、密钥对
cert, _ := tls.LoadX509KeyPair("keys/client.pem", "keys/client.key")
certPool := x509.NewCertPool()
ca, _ := ioutil.ReadFile("keys/ca.pem")
certPool.AppendCertsFromPEM(ca)
creds := credentials.NewTLS(&tls.Config{
Certificates: []tls.Certificate{cert}, //客户端证书
ServerName: "www.p-pp.cn", //注意这里的参数为配置文件中所允许的ServerName,也就是其中配置的DNS...
RootCAs: certPool,
})
conn, err := grpc.Dial(Address, grpc.WithTransportCredentials(creds)) //连接服务端
if err != nil {
log.Fatal(err)
}
defer conn.Close()
prodClient := services.NewProdServiceClient(conn) //初始化客户端
prodRes, err := prodClient.GetProdStock(context.Background(), &services.ProdRequest{ProdId: 12}) //调用方法
if err != nil {
log.Fatal(err)
}
fmt.Printf("grpcClient getProdStock is %d\n", prodRes.ProdStock)
}
1.6 双向认证成功
启动两个服务之后客户端就能使用服务端的服务了。