public class HiveMQClient {
public static void main(String[] args) throws Exception {
final String pathToJKS = "/path/to/keystores/client1-keystore.jks";
final String pathToJKSTrustStore = "/path/to/keystores/client1-truststore.jks";
//Create key store
final KeyStore keyStore = KeyStore.getInstance("JKS");
final InputStream inKey = new FileInputStream(pathToJKS);
keyStore.load(inKey, "secret".toCharArray());
final Certificate certificate = keyStore.getCertificate("mqtt-client");
final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, "secret".toCharArray());
//Create trust store
final KeyStore trustStore = KeyStore.getInstance("JKS");
final InputStream in = new FileInputStream(pathToJKSTrustStore);
trustStore.load(in, "secret".toCharArray());
final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(trustStore);
// Build SSL context
final SSLContext sslCtx = SSLContext.getInstance("TLSv1.2");
sslCtx.init(null, tmf.getTrustManagers(), null);
final List<Mqtt5Publish> message = Collections.synchronizedList(new ArrayList<>());
final Mqtt5AsyncClient client = Mqtt5Client.builder()
.serverHost("localhost")
.sslConfig()
.identifier("client1")
.protocols(Arrays.asList("TLSv1.2"))
.keyManagerFactory(kmf)
.trustManagerFactory(tmf)
.applySslConfig()
.serverPort(8883)
.buildAsync();
client.connect().get();
}
} |