如若不想使用keytool程序,你也可以通过编程实现上述效果。具体方法如下:
class CustomFeignConfiguration {
private val log = Logger.getLogger(this.javaClass.name)
@Value("\${client_p12_base64_encoded_string}")
private val clientP12: String = ""
@Value("\${client_p12_password}")
private val clientP12Pass: String = ""
@Bean
fun feignClient(): Client {
val sslSocketFactory= getSSLSocketFactory()
log.info("CUSTOM FEIGN CLIENT CALLED")
return Client.Default(sslSocketFactory, DefaultHostnameVerifier())
}
private fun getSSLSocketFactory(): SSLSocketFactory {
val decoder = java.util.Base64.getDecoder()
val p12 = decoder.decode(clientP12)
val p12File = File("clientCer.p12")
p12File.writeBytes(p12)
try {
val sslContext = SSLContexts
.custom()
.loadKeyMaterial(p12File, clientP12Pass.toCharArray(), clientP12Pass.toCharArray())
.build()
return sslContext.socketFactory
} catch (exception: Exception) {
throw RuntimeException(exception)
}
}
}
使用该配置的FeignClient接口必须明确加载它。
@FeignClient(name = "client", configuration = [CustomFeignConfiguration::class], url = "\${url}")
interface Client {
....
....
}
SSLContexts库只能使用p12证书,我们需要将PEM格式的证书和密钥转换为P12格式。
使用以下SSL命令从您的PEM证书和密钥创建p12证书:
openssl pkcs12 -export -inkey domain.key -in domain.crt -out domain.p12
请在运行此命令后记录输入的密码。
使用以下命令将此p12证书转换为base64字符串。
base64 domain.p12 > domain.p12.base64
使用以下命令将此多行字符串转换为单行字符串:
tr -d "\n\r" < domain.p12.base64 > domain.p12.base64.singleline
使用该命令中的单行字符串和您在
application.properties中记录的密码。
@ConfigurationProperties
注释的类的字段keyStorePassword,keyStoreType,keyStore
中。 - mpoznyak