Monday, August 31, 2020

keystore javax.net.ssl.keyStore in Spring or Spring boot

TLS 2 connection between Spring boot client and server.  SSL configuration class inside your client application to setup keystore (.jks ). .jks file needs to be inside  your classpath (resource folder) of spring application.

import java.io.FileNotFoundException;

import javax.annotation.PostConstruct;

import org.springframework.context.annotation.Configuration;

import org.springframework.util.ResourceUtils;


@Configuration

public class TLSConfig {


@PostConstruct

private void configureTLS() throws FileNotFoundException {


String filePath = ResourceUtils.getFile("classpath:filejks.jks").getPath();

System.setProperty("https.protocols", "TLSv1.2");

System.setProperty("javax.net.ssl.keyStore", filePath);

System.setProperty("javax.net.ssl.keyStorePassword", "password");

}


Read .jks file from spring boot jar file

InputStream inputStream = null;
File jksFile = null;
try {
ClassPathResource classPathResource = new ClassPathResource("jksfilename.jks");
inputStream = classPathResource.getInputStream();
jksFile = File.createTempFile("anyfilename", ".jks");
java.nio.file.Files.copy(inputStream, jksFile.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
inputStream.close();
}

System.setProperty("javax.net.ssl.keyStore", jksFile.getPath());

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home