這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
- 首先產生認證檔案在github上找到的一段產生指令碼:
openssl genrsa -passout pass:1111 -des3 -out ca.key 4096openssl 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 4096openssl 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.crtopenssl rsa -passin pass:1111 -in server.key -out server.keyopenssl genrsa -passout pass:1111 -des3 -out client.key 4096openssl 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.crtopenssl 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