Christian-health / scala-learning

学习scala语言
0 stars 0 forks source link

scala双向认证最终的实现 #19

Open Christian-health opened 5 years ago

Christian-health commented 5 years ago

证书转换成为keystore和truststore

keystore的生成

参考了这位大哥的博客:https://sky425509.iteye.com/blog/1994891 image

通过pem格式的证书生成一个 keystore和一个truststore
cd /home/providerData/local/ssl_internal/client

ca.pem  clientkey.pem  client.pem

openssl pkcs12 -export -in client.pem -inkey clientkey.pem -out client.pk12 -name provider

/usr/bin/keytool -importkeystore -deststorepass provider -destkeypass provider -destkeystore client.keystore -srckeystore client.pk12 -srcstoretype PKCS12 -srcstorepass provider -alias provider

生成truststore

参考了这位大哥的博客 : http://www.it1352.com/995030.html image

 keytool -import -keystore client.truststore -file ca.pem
Christian-health commented 5 years ago

代码的实现

代码实际上最重要的就是生成一个SSLCONTENT 双向认证参考了这个大哥写的一个博客:https://blog.csdn.net/fw0124/article/details/41013333

object TwoWaySslContextBuilderEnhanceServer {
  private val logger: Logger = LoggerFactory.getLogger("TwoWaySslContextBuilderServer")

  def build(): SSLContext = {
    logger.error(f"TwoWaySslContextBuilderEnhance build exception catch yangxuefeng begin server")
    val serverKeyStoreFile : String = "/usr/local/zte/cert/client.keystore"
    val serverKeyStorePwd : String  = "provider"
    val catServerKeyPwd : String  = "provider"
    val serverTrustKeyStoreFile : String  = "/usr/local/zte/cert/client.truststore"
    val serverTrustKeyStorePwd : String  = "provider"

    val serverKeyStore : KeyStore = KeyStore.getInstance("JKS")
    serverKeyStore.load(new FileInputStream(serverKeyStoreFile), serverKeyStorePwd.toCharArray())

    val serverTrustKeyStore : KeyStore  = KeyStore.getInstance("JKS")
    serverTrustKeyStore.load(new FileInputStream(serverTrustKeyStoreFile), serverTrustKeyStorePwd.toCharArray())

    val kmf : KeyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
    kmf.init(serverKeyStore, catServerKeyPwd.toCharArray())

    val tmf : TrustManagerFactory  = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
    tmf.init(serverTrustKeyStore)

    val sslContext : SSLContext  = SSLContext.getInstance("TLSv1")
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null)
    logger.error(f"TwoWaySslContextBuilderEnhance build exception catch yangxuefeng sslContext server",sslContext)
    sslContext
  }
}
Christian-health commented 5 years ago

支持单项认证

参考博客:https://blog.csdn.net/fw0124/article/details/41013787