Today, I discovered mkcert – a tool that generates valid TLS certificate. It works for any hostname or IP, including localhost. In this post, I will show you how to generate a valid PKCS12 format certificate using mkcert. Then, we will use that certificate in a Spring boot application.
We will start by installing mkcert on our local machine. If you are using Mac then we can use brew
package manager. For installation instructions specific to your OS you can refer to the documentation.
brew install mkcert
Once mkcert
is installed, you can use its CLI to create and install a CA. To do that, run the following command.
mkcert -install
Using the local CA at "/Users/shekhargulati/Library/Application Support/mkcert" ✨ The local CA is now installed in the system trust store! ⚡️ The local CA is now installed in Java's trust store! ☕️
As you can see from the above output, it created and installed CA in both my system and Java’s trust store.
For Java, it is required that JAVA_HOME environment variable is set.
Once CA is created and installed, we can create the PKCS12 format certificate. Java supports two certificate formats:
- PKCS12: Public Key Cryptographic Standards is a password protected format that can contain multiple certificates and keys; it’s an industry-wide used format
- JKS: Java KeyStore is similar to PKCS12; it’s a proprietary format and is limited to the Java environment.
mkcert support PKCS12 format only.
To generate the PKCS12 certificate, we will use the following command.
mkcert -pkcs12 localhost
The output of the above command is shown below.
Using the local CA at "/Users/shekhargulati/Library/Application Support/mkcert" ✨ Created a new certificate valid for the following names 📜 - "localhost" The PKCS#12 bundle is at "./localhost.p12" ✅ The legacy PKCS#12 encryption password is the often hardcoded default "changeit"
It will create the certificate in the current directory. The key store password will be changeit
Now, that we have valid certificate, let’s create the Spring Boot application.
curl https://start.spring.io/starter.zip -d dependencies=web \ -d bootVersion=2.1.2.RELEASE -o ssl-boot-app.zip
Next, unzip the app
unzip ssl-boot-app.zip && cd ssl-boot-app.zip
Copy the localhost.p12
certificate to src/main/resources
directory.
Next, we will set SSL properties in the application.properties
file.
server.port=8443 server.ssl.key-store=classpath:localhost.p12 server.ssl.key-store-type=PKCS12 server.ssl.key-store-password=changeit
Create index.html in the src/main/resources/static
directory
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Hello, HTTPS</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <h1>Hello, Https!</h1> </body> </html>
Now, you can start the app using the following Maven command.
mvnw spring-boot:run
The applictation will be running at https://localhost:8443/