- 首先生成证书文件 在github上找到的一段生成脚本:
openssl genrsa -passout pass:1111 -des3 -out ca.key 4096
openssl req -passin pass:1111 -new -x509 -days 3650 -key ca.key -out ca.crt -subj "/C=FR/ST=Paris/L=Paris/O=Test/OU=Test/CN=ca"
openssl genrsa -passout pass:1111 -des3 -out server.key 4096
openssl req -passin pass:1111 -new -key server.key -out server.csr -subj "/C=FR/ST=Paris/L=Paris/O=Test/OU=Server/CN=charmer"
openssl x509 -req -passin pass:1111 -days 3650 -in server.csr -CA ca.crt -CAkey ca.key -set_serial 01 -out server.crt
openssl rsa -passin pass:1111 -in server.key -out server.key
openssl genrsa -passout pass:1111 -des3 -out client.key 4096
openssl req -passin pass:1111 -new -key client.key -out client.csr -subj "/C=FR/ST=Paris/L=Paris/O=Test/OU=Client/CN=charmer"
openssl x509 -passin pass:1111 -req -days 3650 -in client.csr -CA ca.crt -CAkey ca.key -set_serial 01 -out client.crt
openssl rsa -passin pass:1111 -in client.key -out client.key
执行后, 目录下会有8个文件, 2个ca, 3个client和3个server
- golang服务端
creds, err := credentials.NewServerTLSFromFile("./server.crt", "./server.key")
if err != nil {
...
}
server := grpc.NewServer(grpc.Creds(creds))
- golang客户端
creds, err := credentials.NewClientTLSFromFile("./keys/server.crt", "charmer")
if err != nil {
...
}
conn, err := grpc.Dial("xx.xx.xx.xx:xxxx", grpc.WithTransportCredentials(creds))
defer conn.Close()
注意: 这里的charmer是和生成证书时候参数/CN=xxx的xxx一致, 是ssl的common name
- nodejs客户端
const caCrt = fs.readFileSync(__dirname + "/ca.crt");
const clientKey = fs.readFileSync(__dirname + "/client.key");
const clientCrt = fs.readFileSync(__dirname + "/client.crt");
let client = new hello_proto.Greeter("xx.xx.xx.xx:xxxx", grpc.credentials.createSsl(caCrt, clientKey, clientCrt), { "grpc.ssl_target_name_override": "charmer", "grpc.default_authority": "charmer" });
client.sayHello...
注意这里的两个关键参数 grpc.ssl_target_name_override 和 grpc.default_authority, 也是刚刚参数的common name
有疑问加站长微信联系(非本文作者)