使用openssl 工具进行双向认证测试
1,双向认证测试(需要根证书,客户证书,服务器证书以及各自的私钥)(验证通信双方的身份)
openssl s_server -accept 8090 -key certs/server.key -cert certs/server-cert.pem -CAfile certs/root-cacert.pem -Verify 1
openssl s_client -connect localhost:8090 -key certs/client.key -cert certs/client-cert.pem -CAfile certs/root-cacert.pem -showcerts Verify return code: 0 (ok)
2,单项认证测试(验证客户身份)
openssl s_server -accept 8090 -key certs/server.key -cert certs/server-cert.pem openssl s_client -connect localhost:8090 -CAfile certs/root-cacert.pem -showcerts Verify return code: 0 (ok)
3,如何生成上面的证书呢(自签名证书为例)
CA证书
openssl genrsa -out certs/root-ca.key 2048 openssl req -new -x509 -days 365 -config ./openssl.cnf -key certs/root-ca.key -out certs/root-cacert.pem -subj "/C=CN/ST=shenzhen/O=EMQ/CN=RootCA"
服务器证书
openssl genrsa -out certs/server.key 2048 openssl req -new -days 365 -key certs/server.key -out certs/server-cert.csr -subj "/C=CN/ST=shenzhen/O=EMQ/CN=Server" openssl ca -extensions v3_req -days 365 -in certs/server-cert.csr -out certs/server-cert.pem -cert certs/root-cacert.pem -keyfile certs/root-ca.key
客户端证书
openssl genrsa -out certs/client.key 2048 openssl req -new -days 365 -key certs/client.key -out certs/client-cert.csr -subj "/C=CN/ST=shenzhen/O=EMQ/CN=Client" openssl ca -extensions v3_req -days 365 -in certs/client-cert.csr -out certs/client-cert.pem -cert certs/root-cacert.pem -keyfile certs/root-ca.key
使用根证书验证下服务器证书是否可信的
openssl verify -CAfile certs/root-cacert.pem certs/server-cert.pem
注意证书里CN=Server,身份认证过程中应用程序可能会校验这个字段的,一般这个字段为网站的域名。
第一次生成根证书的时候,
mkdir -p demoCA/newcerts touch demoCA/index.txt vi demoCA/serial 加入01,第二行空行
查看证书有效期
openssl x509 -in cacert.pem -noout -dates
使用MQTT消息测试双向认证
echo -en "\x10\x0d\x00\x04MQTT\x04\x00\x00\x00\x00\x01a" | openssl s_client -connect 47.102.137.3:8883 -key client-key.pem -cert client-cert.pem -CAfile cacert.pem -showcerts