Java Trust Store
In this post, we install an Nginx server, enable HTTPS and make an HTTP request from Java with the Nginx server’s HTTPS certificate imported into a trust store. This post uses RedHat Enterprise Linux 8.
First, creating the certificates…
mkdir certs; cd certs
openssl genrsa -out locally.key1
openssl pkcs8 -topk8 -in locally.key1 -out locally.key -nocrypt
openssl req -new -key locally.key -out locally.csr -subj "/C=AE/ST=Dubai/O=KNR/OU=IT/CN=localhost.localdomain"
openssl x509 -in locally.csr -out locally.crt -req -signkey locally.key -days 3650
sudo cp locally.crt /etc/pki/tls/certs
sudo cp locally.key /etc/pki/tls/certs
sudo chmod 400 /etc/pki/tls/certs/locally.key
Then, installing Java and getting the certificate into the trust store:
sudo yum search openjdk
sudo yum install -y java-17-openjdk-devel
sudo keytool -import -trustcacerts -keystore /etc/java/java-17-openjdk/java-17-openjdk-17.0.2.0.8-4.el8_5.x86_64/lib/security/cacerts -storepass changeit -noprompt -alias myca -file /home/ec2-user/certs/locally.crt
Next, the Nginx setup
sudo yum install -y nginx
sudo chown nginx. /etc/pki/tls/certs/locally.key
sudo vi /etc/nginx/nginx.conf
#--
listen 443 ssl;
ssl_certificate "/etc/pki/tls/certs/locally.crt";
ssl_certificate_key "/etc/pki/tls/certs/locally.key";
#--
sudo systemctl restart nginx
Then, the Java source code to make a web request:
mkdir ~/myjava; cd ~/myjava
mkdir -p com/pockettheories
vi com/pockettheories/TryHttpClient.java
#--
package com.pockettheories;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class TryHttpClient {
public static void main(String args[]) throws Exception {
HttpRequest req = HttpRequest
.newBuilder(
new URI("https://localhost.localdomain") //change this to hostname
).build();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandlers.ofString());
String responseBody = resp.body();
System.out.println(responseBody);
}
}
#--
javac com/pockettheories/TryHttpClient.java
java -cp . com.pockettheories.TryHttpClient
The web request can be made again after removing the certificate from the trust store:
sudo keytool -delete -trustcacerts -keystore /etc/java/java-17-openjdk/java-17-openjdk-17.0.2.0.8-4.el8_5.x86_64/lib/security/cacerts -storepass changeit -noprompt -alias myca -file /home/ec2-user/certs/locally.crt
java -cp . com.pockettheories.TryHttpClient
The certificate can also be added into a custom trust store:
keytool -import -file /home/ec2-user/certs/locally.crt -alias firstCA -keystore mycert.store
java -cp . -Djavax.net.ssl.trustStore=mycert.store -Djavax.net.ssl.trustStorePassword=changeit com.pockettheories.TryHttpClient