grpc ssl/tsl自签名证书

openssl下载网址

http://slproweb.com/products/Win32OpenSSL.html

生成根证书/私钥、服务端证书/私钥、客户端证书/私钥

  1. 创建一个CA私钥(根证书)
    openssl genrsa -out ca.key 4096

  2. 创建一个conf 用来生成csr(请求签名证书文件)---ca.conf

[ req ]
default_bits = 4096
distinguished_name = req_distinguished_name

[ req_distinguished_name ]
countryName = Country Name (2 letter code)
countryName_default = CN
stateOrProvinceName = State or Province Name (2 letter code)
stateOrProvinceName_default = Shanghai
localityName = Locality Name (eg, city)
localityName_default = Shanghai
organizationName = Organization Name (eg, company)
organizationName_default = nsqk.com
commonName = Common Name (e.g. server FQDN or YOUR name)
commonName_max = 64
commonName_default = localhost
  1. 生成csr文件
    openssl req -new -sha256 -out ca.csr -key ca.key -config ca.conf

  2. 生成证书 crt文件
    openssl x509 -req -days 365 -in ca.csr -signkey ca.key -out ca.crt

  3. 生成server证书
    新建server.conf
    commonName_default 客户端要根据这个字段做匹配

[ 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 (2 letter code)
stateOrProvinceName_default = Shanghai
localityName = Locality Name (eg, city)
localityName_default = Shanghai
organizationName = Organization Name (eg, company)
organizationName_default = nsqk.com
commonName = Common Name (e.g. server FQDN or YOUR name)
commonName_max = 64
commonName_default = localhost
[ req_ext ]
subjectAltName = @alt_names
[alt_names]
DNS.1 = localhost
IP  = 127.0.0.1
  1. 生成server.key
    openssl genrsa -out server.key 2048

  2. 生成server.csr
    openssl req -new -sha256 -out server.csr -key server.key -config server.conf

  3. 生成server.crt/pem
    openssl x509 -req -days 365 -CA ca.crt -CAkey ca.key -CAcreateserial -in server.csr -out server.pem -extensions req_ext -extfile server.conf

  4. 生成client.key
    openssl ecparam -genkey -name secp384r1 -out client.key

  5. 生成client.csr
    openssl req -new -key client.key -out client.csr -config server.conf

  6. 生成client.pem
    openssl x509 -req -sha256 -CA ca.pem -CAkey ca.key -CAcreateserial -days 3650 -in client.csr -out client.pem -extensions req_ext -extfile server.conf
    或者
    openssl x509 -req -sha256 -CA ca.crt -CAkey ca.key -CAcreateserial -days 3650 -in client.csr -out client.pem -extensions req_ext -extfile server.conf

grpc使用

方案1:简单,不推荐(因为客户端直接使用的是服务端的证书)

  1. server端
package main

import (
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"grpc_test/services"
	"log"
	"net"
)

func main() {
	// grpc服务端配置证书和私钥
	creds, err := credentials.NewServerTLSFromFile("certs/server.pem", "certs/server.key")
	if err != nil {
		log.Fatalln(err.Error())
	}

	// NewServer 创建一个未注册服务且尚未开始接受请求的 gRPC 服务器。
	rpcServer := grpc.NewServer(grpc.Creds(creds))

	// 将当前产品服务注册到grpc服务当中去
	services.RegisterProdServiceServer(rpcServer, new(services.ProdService))

	// 监听套接字
	listener, _ := net.Listen("tcp", ":8080")

	// grpc服务器接收请求,开始提供服务
	rpcServer.Serve(listener)
}

  1. 客户端
package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"grpc_test_client/services"
	"log"
)

func main() {
	// Dial 创建到给定目标的客户端连接
	creds, err := credentials.NewClientTLSFromFile("certs/server.pem", "localhost")
	if err != nil {
		log.Fatalln(err.Error())
	}
	conn, err := grpc.Dial(":8080", grpc.WithTransportCredentials(creds))
	if err != nil {
		log.Fatalln(err.Error())
	}
	//defer conn.Close()

	prodClient := services.NewProdServiceClient(conn)
	prodRes, err := prodClient.GetProdStock(
		context.Background(),
		&services.ProdRequest{ProdId: 118},
	)
	if err != nil {
		log.Fatalln(err.Error())
	}
	fmt.Println("客户端接收到服务端的响应,ProdStock: ", prodRes.ProdStock)
}

参考网址

方案2,有点复杂,推荐(服务端使用服务端的证书和私钥以及ca证书,客户端使用客户端证书和私钥以及ca证书)

  1. 服务端
点击查看代码
package main

import (
	"crypto/tls"
	"crypto/x509"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"grpc_test/services"
	"io/ioutil"
	"log"
	"net"
)

func main() {
	// 使用tls 进行加载  key pair
	cert, err := tls.LoadX509KeyPair("certs/server.pem", "certs/server.key")
	if err != nil {
		log.Println("tls 加载x509 证书失败", err)
	}
	// 创建证书池
	certPool := x509.NewCertPool()

	// 向证书池中加入证书
	cafileBytes, err := ioutil.ReadFile("certs/ca.pem")
	if err != nil {
		log.Println("读取ca.pem证书失败", err)
	}
	// 加载客户端证书
	//certPool.AddCert()

	// 加载证书从pem 文件里面
	certPool.AppendCertsFromPEM(cafileBytes)

	// 创建credentials 对象
	creds := credentials.NewTLS(&tls.Config{
		Certificates: []tls.Certificate{cert},        //服务端证书
		ClientAuth:   tls.RequireAndVerifyClientCert, // 需要并且验证客户端证书
		ClientCAs:    certPool,                       // 客户端证书池

	})

	// grpc服务端配置证书和私钥
	//creds, err := credentials.NewServerTLSFromFile("certs/server.pem", "certs/server.key")
	//if err != nil {
	//	log.Fatalln(err.Error())
	//}

	// NewServer 创建一个未注册服务且尚未开始接受请求的 gRPC 服务器。
	rpcServer := grpc.NewServer(grpc.Creds(creds))

	// 将当前产品服务注册到grpc服务当中去
	services.RegisterProdServiceServer(rpcServer, new(services.ProdService))

	// 监听套接字
	listener, _ := net.Listen("tcp", ":8080")

	// grpc服务器接收请求,开始提供服务
	rpcServer.Serve(listener)
}

  1. 客户端
点击查看代码
package main

import (
	"context"
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"grpc_test_client/services"
	"io/ioutil"
	"log"
)

func main() {
	// 和server端一样,先创建证书池
	cert, err := tls.LoadX509KeyPair("certs/client.pem","certs/client.key")
	if err!= nil{
		log.Println("加载client pem, key 失败",err)
	}

	certPool := x509.NewCertPool()
	caFile ,err :=  ioutil.ReadFile("certs/ca.pem")
	if err!= nil{
		log.Println("加载ca失败",err)
	}
	certPool.AppendCertsFromPEM(caFile)

	creds := credentials.NewTLS(&tls.Config{
		Certificates: []tls.Certificate{cert},// 放入客户端证书
		ServerName: "localhost", //证书里面的 commonName
		RootCAs: certPool, // 证书池
	})

	// Dial 创建到给定目标的客户端连接
	//creds, err := credentials.NewClientTLSFromFile("certs/server.pem", "localhost")
	//if err != nil {
	//	log.Fatalln(err.Error())
	//}

	conn, err := grpc.Dial(":8080", grpc.WithTransportCredentials(creds))
	if err != nil {
		log.Fatalln(err.Error())
	}
	//defer conn.Close()

	prodClient := services.NewProdServiceClient(conn)
	prodRes, err := prodClient.GetProdStock(
		context.Background(),
		&services.ProdRequest{ProdId: 29},
	)
	if err != nil {
		log.Fatalln(err.Error())
	}
	fmt.Println("客户端接收到服务端的响应,ProdStock: ", prodRes.ProdStock)
}

posted @ 2022-05-05 21:58  专职  阅读(479)  评论(0编辑  收藏  举报