1、下載openssljavascript
https://oomake.com/download/openssl 這個連接基本有各個平臺(我這裏是window 直接下載exe安裝文件就能夠)java
下載完成後 找到安裝目錄配置一下環境變量 就能夠在任何地方使用了c#
2、生成證書tcp
openssl genrsa -out server.key 2048 openssl req -new -x509 -sha256 -key server.key -out server.crt -days 36500 -subj /C=CN/ST=CQ/L=fanxp/O=cq/OU=bx/CN=go-grpc-test/emailAddress=myname@gmail.com
會生成 server.key server.crt兩個文件 go-grpc-test 爲servername 測試的時候必需要ide
3、配置證書測試
go serverspa
func main(){ lis, err := net.Listen("tcp", PORT) if err != nil { log.Fatalf("failed to listen: %v", err) } // TLS認證 creds, err := credentials.NewServerTLSFromFile("conf/server.crt", "conf/server.key") if err != nil { grpclog.Fatalf("Failed to generate credentials %v", err) } s := grpc.NewServer(grpc.Creds(creds)) pb.RegisterGreeterServer(s, &server{}) log.Println("rpc服務已經開啓") s.Serve(lis) }
這裏只展現主要代碼(代碼基於上一篇博文,能夠自行下載測試)code
go clientserver
func main() { creds, err := credentials.NewClientTLSFromFile("conf/server.crt", "go-grpc-test") if err != nil { panic(fmt.Errorf("could not load tls cert: %s", err)) } conn, err := grpc.Dial(address, grpc.WithTransportCredentials(creds)) if err != nil { log.Fatalf("did not connect: %v", err) } defer conn.Close() c := pb.NewGreeterClient(conn) name := "lin" if len(os.Args) > 1 { name = os.Args[1] } r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name}) if err != nil { log.Fatalf("could not greet: %v", err) } log.Println(r.Message) }
c# clientblog
static void Main(string[] args) { var cacert = File.ReadAllText("conf/server.crt"); var ssl = new SslCredentials(cacert); var channOptions = new List<ChannelOption> { new ChannelOption(ChannelOptions.SslTargetNameOverride,"go-grpc-test") }; Channel channel = new Channel("127.0.0.1:50001", ssl,channOptions); var client = new Greeter.GreeterClient(channel); var reply = client.SayHello(new HelloRequest{ Name = "lin" }); Console.WriteLine("來自" + reply.Message); channel.ShutdownAsync().Wait(); Console.WriteLine("任意鍵退出..."); Console.ReadKey(); }