共计 2489 个字符,预计需要花费 7 分钟才能阅读完成。
[TOC]
openssl 证书生成
问题
golang 1.15+ 版本上,用 gRPC 通过 TLS 实现数据传输加密时,会报错证书的问题
rpc error: code = Unavailable desc = connection error: desc = "transport: authentication ha
ndshake failed: x509: certificate is valid for www.eline.com, not xxx"
panic: rpc error: code = Unavailable desc = connection error: desc = "transport: authentication handshake failed: x509: certificate is valid for www.eline.com, not xxx"
造成的起因是因为咱们用的证书,并没有开启 SAN 扩大(默认是没有开启 SAN 扩大)所生成的,
导致客户端和服务端无奈建设连贯
开始解决问题
应用开启扩大 SAN 的证书
什么是 SAN
SAN(Subject Alternative Name) 是 SSL 规范 x509 中定义的一个扩大。应用了 SAN 字段的 SSL 证书,能够扩大此证书反对的域名,使得一个证书能够反对多个不同域名的解析。
生成 CA 根证书
新建 ca.conf
vim ca.conf
写入内容如下:
[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 (full name)
stateOrProvinceName_default = JiangSu
localityName = Locality Name (eg, city)
localityName_default = NanJing
organizationName = Organization Name (eg, company)
organizationName_default = Sheld
commonName = Common Name (e.g. server FQDN or YOUR name)
commonName_max = 64
commonName_default = Ted CA Test
生成 ca 秘钥,失去 ca.key
openssl genrsa -out ca.key 4096
生成 ca 证书签发申请,失去 ca.csr
openssl req \
-new \
-sha256 \
-out ca.csr \
-key ca.key \
-config ca.conf
shell 交互时一路回车就行
生成 ca 根证书,失去 ca.crt
openssl x509 \
-req \
-days 3650 \
-in ca.csr \
-signkey ca.key \
-out ca.crt
生成终端用户证书
筹备配置文件,失去 server.conf
新建 server.conf
vim server.conf
写入内容如下:
[req]
default_bits = 2048
distinguished_name = req_distinguished_name
req_extensions = req_ext
[req_distinguished_name]
countryName = Country Name (2 letter code)
countryName_default = CN
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = JiangSu
localityName = Locality Name (eg, city)
localityName_default = NanJing
organizationName = Organization Name (eg, company)
organizationName_default = Sheld
commonName = Common Name (e.g. server FQDN or YOUR name)
commonName_max = 64
commonName_default = xiamotong # 此处尤为重要,须要用该服务名字填写到客户端的代码中
[req_ext]
subjectAltName = @alt_names
[alt_names]
DNS.1 = www.eline.com
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
shell 交互时一路回车就行
用 CA 证书生成终端用户证书,失去 server.crt
openssl x509 \
-req \
-days 3650 \
-CA ca.crt \
-CAkey ca.key \
-CAcreateserial \
-in server.csr \
-out server.pem\
-extensions req_ext \
-extfile server.conf
当初证书曾经生成结束,server.pem 和 server.key就是咱们须要的证书和密钥
服务端代码:
creds, err := credentials.NewServerTLSFromFile("./keys/server.pem", "./keys/server.key")
客户端代码:
creds, err := credentials.NewClientTLSFromFile("./keys/server.pem", "xiaomotong")
好了,本次就到这里,下一次分享 gRPC 的 interceptor
技术是凋谢的,咱们的心态,更应是凋谢的。拥抱变动,背阴而生,致力向前行。
我是 小魔童哪吒,欢送点赞关注珍藏,下次见~