ios 开发之没事来看看Linux

grpc ssl 自签名证书

2021-10-28  本文已影响0人  等这姑娘老在我心里

起因

问题1

rpc error: code = Unavailable desc = connection error: desc = “transport: authentication handshake failed: x509: certificate is not valid for any names, but wanted to match XXX”

这个是因为grpc 长时间没有链接,重启就可以了

问题2

普通的自签名证书在 golang 1.15 + 版本上,用gRPC tls报错

rpc error: rpc error: code = Unavailable desc = connection error: desc = "transport: authentication handshake failed: x509: certificate is not valid for any names, but wanted to match SANs"

需要开启一个叫SAN扩展的东西,不然没有办法进行链接

1. 创建一个CA私钥(根证书)

openssl genrsa -out ca.key 4096

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

touch ca.conf
vi ca.conf

编写conf文件

commonName_default 这个配置项,如果有域名就写域名,本地就 localhost

[ 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

生成csr文件

openssl req \
-new \
-sha256 \
-out ca.csr \
-key ca.key \
-config ca.conf

3. 生成证书 crt文件

openssl x509 \
-req \
-days 365 \
-in ca.csr \
-signkey ca.key \
-out ca.crt

4. 生成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

生成server.key

openssl genrsa -out server.key 2048

生成server.csr

openssl req \
-new \
-sha256 \
-out server.csr \
-key server.key \
-config server.conf

生成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

生成client.key

openssl ecparam -genkey -name secp384r1 -out client.key

生成client.csr

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

生成client.pem

openssl x509 -req -sha256 -CA ca.pem -CAkey ca.key -CAcreateseria
l -days 3650 -in client.csr -out client.pem -extensions req_ext -extfile server.conf

5. gRPC使用

server 端

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

    // 向证书池中加入证书
    cafileBytes, err := ioutil.ReadFile("cert/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,                       // 客户端证书池

    })

    lis, err := net.Listen("tcp", ":2333")
    if err != nil {
        fmt.Println("监听端口失败 err:", err)
    }
    s := grpc.NewServer(grpc.Creds(creds))
    services.RegisterHelloWorldServer(s, new(services.HelloService))

    reflection.Register(s)

    err = s.Serve(lis)
    fmt.Println("gRPC starting")
    if err != nil {
        fmt.Println("启动grpc失败 err:", err)
    } else {
        fmt.Println("gRPC started")
    }

client 端

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

    certPool := x509.NewCertPool()
    caFile ,err :=  ioutil.ReadFile("cert/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, // 证书池
    })

    conn, err := grpc.Dial(":2333", grpc.WithTransportCredentials(creds))
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()

    client := services.NewHelloWorldClient(conn)
    replay, err := client.HelloRPC(context.Background(), &services.SayHelloRequest{
        Name: "hello world name",
    })
    if err != nil {
        fmt.Println("rpc error:", err)
    } else {
        fmt.Println("result message :", replay.Message)
    }
上一篇 下一篇

猜你喜欢

热点阅读