Use Certificate in JAVA SDK

Here are some code samples to illustrate @mreiche 's suggestion.

There are a few ways to trust a custom CA certificate.

Option A: Programmatic environment configuration

This syntax requires Java SDK 3.4.1 or later, but the same idea works with earlier versions.

String connectionString = "couchbases://example.com";

Cluster cluster = Cluster.connect(
    connectionString,
    ClusterOptions.clusterOptions(username, password)
        .environment(env -> env
            .securityConfig(security -> security
                .trustCertificate(Paths.get("/path/to/ca-cert.pem"))
            )
        )
);

TIP: The ca-cert.pem file (or whatever you choose to name it) may contain multiple trusted CA certificates.

Option B: Configure via connection string

Most client settings (including security.trustCertificate) can be specified as connection string query parameters.

String connectionString = "couchbases://example.com" +
    "?security.trustCertificate=/path/to/ca-cert.pem";

Cluster cluster = Cluster.connect(connectionString, username, password);

Option C: Add certificate to JVM trust store

If you don’t tell the SDK to trust specific certificates, SDK 3.4.0 and later defaults to trusting all certificates in the JVM’s cacerts trust store. You can add your certificate to cacerts (the internet can show you how to do that) and just enable TLS.

String connectionString = "couchbases://example.com";
Cluster cluster = Cluster.connect(connectionString, username, password);

It’s also possible to put the certificate in a separate Java Keystore and tell the SDK to use that keystore, but it’s much simpler to use a plain old PEM file as in Options A & B.

NOTE: The above examples enable TLS by using the couchbases:// (note the final “s”) scheme in the connection string. An alternate way to enable TLS is to set the security.enableTls client setting to true.

2 Likes