KeyStores.kt

  1. package com.hexagonkt.core.security

  2. import java.net.URL
  3. import java.security.KeyStore
  4. import java.security.interfaces.RSAPrivateKey
  5. import java.security.interfaces.RSAPublicKey
  6. import javax.net.ssl.KeyManagerFactory
  7. import javax.net.ssl.TrustManagerFactory

  8. // TODO Create CAs and PKs like `certificates.gradle` Check: https://www.baeldung.com/java-keystore
  9. fun loadKeyStore(resource: URL, password: String): KeyStore =
  10.     KeyStore.getInstance("PKCS12").apply {
  11.         load(resource.openStream(), password.toCharArray())
  12.     }

  13. fun KeyStore.getPrivateKey(alias: String, password: String): RSAPrivateKey =
  14.     this.getKey(alias, password.toCharArray()) as RSAPrivateKey

  15. fun KeyStore.getPublicKey(alias: String): RSAPublicKey =
  16.     this.getCertificate(alias).publicKey as RSAPublicKey

  17. fun createTrustManagerFactory(
  18.     resource: URL,
  19.     password: String,
  20.     algorithm: String = TrustManagerFactory.getDefaultAlgorithm()
  21. ): TrustManagerFactory {
  22.     val trustStore = loadKeyStore(resource, password)
  23.     val trustManager = TrustManagerFactory.getInstance(algorithm)
  24.     trustManager.init(trustStore)
  25.     return trustManager
  26. }

  27. fun createKeyManagerFactory(
  28.     resource: URL,
  29.     password: String,
  30.     algorithm: String = KeyManagerFactory.getDefaultAlgorithm()
  31. ): KeyManagerFactory {
  32.     val keyStore = loadKeyStore(resource, password)
  33.     val keyManager = KeyManagerFactory.getInstance(algorithm)
  34.     keyManager.init(keyStore, password.toCharArray())
  35.     return keyManager
  36. }