本文深度剖析現有安全網絡通信基石——SSL,使用上篇生成的自簽名證書 zlex.cer 完成證書導入、域名映射、Tomcat SSL 配置,並編寫 Java 客戶端通過 HttpsURLConnection 實現 HTTPS 訪問,驗證 SSL 雙向認證流程。
keytool -import -alias www.zlex.org -file d:/zlex.cer -keystore d:/zlex-client.keystore
密碼 654321,信任證書。hosts 綁定 127.0.0.1 www.zlex.org。server.xml):
<Connector
SSLEnabled="true"
URIEncoding="UTF-8"
clientAuth="false"
keystoreFile="conf/zlex.keystore"
keystorePass="123456"
maxThreads="150"
port="443"
protocol="HTTP/1.1"
scheme="https"
secure="true"
sslProtocol="TLS" />
clientAuth="false" 測試階段建議關閉,生產環境開啟。啟動 Tomcat,訪問 https://www.zlex.org/,瀏覽器提示證書不受信(自簽名),手動安裝 zlex.cer 為受信根證書後顯示小鎖圖標。抽象類 CertificateCoder 封裝:
getKeyStore、getPrivateKey、getCertificate)encryptByPublicKey/decryptByPrivateKey、encryptByPrivateKey/decryptByPublicKey)verifyCertificate 檢查有效期)sign/verify 基於 Signature)configSSLSocketFactory 初始化 KeyManagerFactory、TrustManagerFactory、SSLContext)關鍵點:未配置 SSLSocketFactory 前,HttpsURLConnection.getContentLength() 永遠返回 -1。
CertificateCoderTest 三測試方法:
test():公鑰加密/私鑰解密 + 證書有效性驗證testSign():私鑰加密/公鑰解密 + 私鑰簽名/公鑰驗證簽名testHttps():配置 SSLSocketFactory 後訪問 https://www.zlex.org/examples/,控制台輸出 Tomcat Examples 頁面 HTML雙方通過 Tomcat 配置有效 SSL 服務,可簡化代碼完全通過證書配置完成 SSL 雙向認證。