• grpc TLS证书验证


    一、下载openssl

    https://oomake.com/download/openssl 这个链接基本有各个平台(我这里是window 直接下载exe安装文件就可以)

    下载完成后 找到安装目录配置一下环境变量 就可以在任何地方使用了

    二、生成证书

    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 测试的时候必须要

    三、配置证书

    go server

    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)
    }

    这里只展示主要代码(代码基于上一篇博文,可以自行下载测试)

    go client

    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# client

    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();
    }
  • 相关阅读:
    Web安全
    前端安全之XSS攻击
    SQL盲注
    Vim使用手册
    VC获取cookies的几种方法
    Wireshark基本介绍和学习TCP三次握手
    细说Cookie
    top100tools
    如何更改Jframe里Jpanel的大小
    HTTP&&Fiddler教程
  • 原文地址:https://www.cnblogs.com/fanxp/p/11415455.html
Copyright © 2020-2023  润新知