Skip to content

ClickHouseDefaultSslContextProvider expect an invalid PKCS8-encoded PEM file #1589

Open

Description

@ekpdt

Describe the bug

clickhouse-java expects mTLS private keys to be provided as a PEM file with PKCS8 data.
See

But clickhouse-java also expects the key algorithm (RSA, DSA, EC, etc.) to be in the PEM header (i.e. -----BEGIN $ALGO PRIVATE KEY-----).
See

This is an unreasonable expectation. PKCS8 encoding should never include the algorithm in the header. The only two allowable headers are BEGIN PRIVATE KEY and BEGIN ENCRYPTED PRIVATE KEY.
See https://datatracker.ietf.org/doc/html/rfc7468#section-10

No compliant tool will produce a PEM/PKCS8 file with the format expected by this library.
This is a problem when the PKCS8 data represents anything but an RSA key (which the library assumes as default). For example, the library is unable to read properly represented EC private keys.

With PEM/PKCS8, the algorithm is encoded in the PKCS8 data itself and can be read from the encoded data. Java/JCA does not give a good way of doing this (though there is a proposal - https://openjdk.org/jeps/8300911) but BouncyCastle does.

PEMParser pemParser = new PEMParser(Files.newBufferedReader(Paths.get("private.key")));
var privateKeyInfo = (PrivateKeyInfo) pemParser.readObject();
PrivateKey privateKey = new JcaPEMKeyConverter().getPrivateKey(privateKeyInfo);
String algorithm = privateKey.getAlgorithm();

Steps to reproduce

  1. Create a PEM/PKCS8 file for an EC private key.
  2. Specify it via ClickHouseClientBuilder.option(ClickHouseClientOption.SSL_KEY, "path/to/private.key")
  3. Execute a ClickHouseRequest from the resulting client.

Expected behaviour

An SSL context is established and the request succeeds.

Error log

java.util.concurrent.CompletionException: javax.net.ssl.SSLException: Failed to get SSL context
	at com.clickhouse.client.ClickHouseClientBuilder$Agent.handle(ClickHouseClientBuilder.java:272)
	at com.clickhouse.client.ClickHouseClientBuilder$Agent.lambda$execute$0(ClickHouseClientBuilder.java:348)
	at java.base/java.util.concurrent.CompletableFuture.uniHandle(CompletableFuture.java:934)
	at java.base/java.util.concurrent.CompletableFuture$UniHandle.tryFire(CompletableFuture.java:911)
	at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:510)
	at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1773)
	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144)
	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642)
	at java.base/java.lang.Thread.run(Thread.java:1583)
Caused by: javax.net.ssl.SSLException: Failed to get SSL context
	at com.clickhouse.client.config.ClickHouseDefaultSslContextProvider.getJavaSslContext(ClickHouseDefaultSslContextProvider.java:176)
	at com.clickhouse.client.config.ClickHouseDefaultSslContextProvider.getSslContext(ClickHouseDefaultSslContextProvider.java:186)
	at com.clickhouse.client.http.HttpUrlConnectionImpl.newConnection(HttpUrlConnectionImpl.java:118)
	at com.clickhouse.client.http.HttpUrlConnectionImpl.<init>(HttpUrlConnectionImpl.java:200)
	at com.clickhouse.client.http.ClickHouseHttpConnectionFactory.createConnection(ClickHouseHttpConnectionFactory.java:30)
	at com.clickhouse.client.http.ClickHouseHttpClient.newConnection(ClickHouseHttpClient.java:56)
	at com.clickhouse.client.http.ClickHouseHttpClient.newConnection(ClickHouseHttpClient.java:26)
	at com.clickhouse.client.AbstractClient.getConnection(AbstractClient.java:198)
	at com.clickhouse.client.http.ClickHouseHttpClient.send(ClickHouseHttpClient.java:90)
	at com.clickhouse.client.AbstractClient.sendAsync(AbstractClient.java:161)
	at com.clickhouse.client.AbstractClient.lambda$execute$0(AbstractClient.java:273)
	at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1768)
	... 3 more
Caused by: java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: Invalid RSA private key
	at java.base/sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:253)
	at java.base/java.security.KeyFactory.generatePrivate(KeyFactory.java:389)
	at com.clickhouse.client.config.ClickHouseDefaultSslContextProvider.getPrivateKey(ClickHouseDefaultSslContextProvider.java:90)
	at com.clickhouse.client.config.ClickHouseDefaultSslContextProvider.getKeyStore(ClickHouseDefaultSslContextProvider.java:114)
	at com.clickhouse.client.config.ClickHouseDefaultSslContextProvider.getJavaSslContext(ClickHouseDefaultSslContextProvider.java:156)
	... 14 more
Caused by: java.security.InvalidKeyException: Invalid RSA private key
	at java.base/sun.security.rsa.RSAPrivateCrtKeyImpl.parseKeyBits(RSAPrivateCrtKeyImpl.java:356)
	at java.base/sun.security.rsa.RSAPrivateCrtKeyImpl.<init>(RSAPrivateCrtKeyImpl.java:161)
	at java.base/sun.security.rsa.RSAPrivateCrtKeyImpl.newKey(RSAPrivateCrtKeyImpl.java:90)
	at java.base/sun.security.rsa.RSAKeyFactory.generatePrivate(RSAKeyFactory.java:348)
	at java.base/sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:249)
	... 18 more
Caused by: java.io.IOException: Version must be 0
	at java.base/sun.security.rsa.RSAPrivateCrtKeyImpl.parseASN1(RSAPrivateCrtKeyImpl.java:321)
	at java.base/sun.security.rsa.RSAPrivateCrtKeyImpl.parseKeyBits(RSAPrivateCrtKeyImpl.java:346)
	... 22 more

Configuration

Environment

  • Client version: 0.6.0-patch1
  • Language version: 21
  • OS: Linux

ClickHouse server

  • ClickHouse Server version: N/A
  • ClickHouse Server non-default settings, if any: N/A

Activity

  1. added
    client
    on Jan 9, 2025
  2. github-actions commented on Jan 10, 2026

    @github-actions

    This issue has been automatically marked as stale because it has not had activity in the last year. It will be closed in 30 days if no further activity occurs. Please feel free to leave a comment if you believe the issue is still relevant. Thank you for your contributions!

  3. github-actions commented on Feb 9, 2026

    @github-actions

    This issue has been automatically closed because it has not had any further activity in the last 30 days. Thank you for your contributions!

  4. added this to the 0.11.0 milestone on Jun 17, 2026
  5. modified the milestones: 0.11.0, 0.12.0 on Sep 30, 2026
  6. removed this from the 0.12.0 milestone on Nov 10, 2026
  7. added
    connectivity
    and removed on Nov 26, 2026
  8. polyglotAI-bot commented on Nov 28, 2026

    @polyglotAI-bot
    Collaborator

    Recommendation: Keep open — fix needed
    The defect is also in client-v2 and jdbc-v2, not only in the v1 provider: a PKCS#8 key of any algorithm other than RSA cannot be used for a client certificate. A fix is needed in both PEM key readers.

    • Category: Bug
    • Classification: impact: Security (authentication) · area: Connectivity (TLS client certificate)
    • Status on main: Reproduced on main — an EC key with the RFC 7468 label BEGIN PRIVATE KEY fails in client-v2, jdbc-v2, and v1.
    • Breaking change: No — can be done without a break, if keys that load now still load.
    • Duplicates / related: Related: [client-v2,jdbc-v2] Secure credentials #3248 — its plan (Step 2, item 5) includes this fix.
    • Workaround: Change the label of the key file to EC PRIVATE KEY (-----BEGIN EC PRIVATE KEY-----) and keep the PKCS#8 body: the run shows that client-v2 then loads the key and builds the SSL context.

    Analysis: getAlgorithm (client-v2/.../api/internal/SslContextProvider.java:97) takes the key algorithm from the text between BEGIN and PRIVATE KEY in the first line, with RSA as the default (:49), and getPrivateKey gives that name to KeyFactory (:124). The PKCS#8 label has no algorithm, so each non-RSA PKCS#8 key is decoded as RSA and fails. The v1 ClickHouseDefaultSslContextProvider has the same code (:84, :111), and jdbc-v2 uses the client-v2 code.

    Reproduction: complete program and output

    Changed from the issue's steps: the program makes its own EC key with the JDK keytool, and adds client-v2 and jdbc-v2 cases; the v1 case calls getPrivateKey from the issue's stack trace.

    import com.clickhouse.client.api.Client;
    import com.clickhouse.client.config.ClickHouseDefaultSslContextProvider;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.InputStream;
    import java.nio.charset.StandardCharsets;
    import java.nio.file.Files;
    import java.security.KeyStore;
    import java.security.PrivateKey;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.util.Base64;
    import java.util.Properties;
    
    public class Repro {
        // Only an HTTPS endpoint is needed: the client builds the SSL context before it connects.
        static final String HTTPS_URL = "https://localhost:8443";
    
        static String pem(String label, byte[] der) {
            return "-----BEGIN " + label + "-----\n"
                    + Base64.getMimeEncoder(64, "\n".getBytes(StandardCharsets.US_ASCII)).encodeToString(der)
                    + "\n-----END " + label + "-----\n";
        }
    
        static String write(File dir, String name, String content) throws Exception {
            File f = new File(dir, name);
            Files.write(f.toPath(), content.getBytes(StandardCharsets.US_ASCII));
            return f.getAbsolutePath();
        }
    
        static void print(String name, Throwable e) {
            Throwable root = e;
            while (root.getCause() != null) {
                root = root.getCause();
            }
            System.out.println(name + ": " + e.getClass().getName() + ": " + e.getMessage()
                    + " | root cause: " + root.getClass().getName() + ": " + root.getMessage());
        }
    
        static void clientV2(String name, String cert, String key) {
            try (Client client = new Client.Builder().addEndpoint(HTTPS_URL).setUsername("default")
                    .setClientCertificate(cert).setClientKey(key).build()) {
                System.out.println(name + ": client built, SSL context OK");
            } catch (Exception e) {
                print(name, e);
            }
        }
    
        public static void main(String[] args) throws Exception {
            // An EC key pair and a self-signed certificate, from the JDK keytool.
            File dir = Files.createTempDirectory("issue1589").toFile();
            File p12 = new File(dir, "ec.p12");
            Process p = new ProcessBuilder("keytool", "-genkeypair", "-alias", "k", "-keyalg", "EC", "-keysize", "256",
                    "-dname", "CN=test", "-validity", "1", "-storetype", "PKCS12", "-keystore", p12.getAbsolutePath(),
                    "-storepass", "changeit", "-keypass", "changeit").inheritIO().start();
            if (p.waitFor() != 0) {
                throw new IllegalStateException("keytool failed");
            }
            KeyStore ks = KeyStore.getInstance("PKCS12");
            try (InputStream in = new FileInputStream(p12)) {
                ks.load(in, "changeit".toCharArray());
            }
            PrivateKey key = (PrivateKey) ks.getKey("k", "changeit".toCharArray());
            System.out.println("key: " + key.getAlgorithm() + ", " + key.getFormat());
    
            String cert = write(dir, "cert.pem", pem("CERTIFICATE", ks.getCertificate("k").getEncoded()));
            String keyPkcs8 = write(dir, "key.pem", pem("PRIVATE KEY", key.getEncoded()));           // RFC 7468 label
            String keyEcLabel = write(dir, "key-ec.pem", pem("EC PRIVATE KEY", key.getEncoded()));   // same bytes, other label
    
            clientV2("client-v2, BEGIN PRIVATE KEY", cert, keyPkcs8);
            clientV2("client-v2, BEGIN EC PRIVATE KEY", cert, keyEcLabel);
    
            Properties props = new Properties();
            props.setProperty("user", "default");
            props.setProperty("sslcert", cert);
            props.setProperty("ssl_key", keyPkcs8);
            try (Connection conn = DriverManager.getConnection("jdbc:clickhouse:" + HTTPS_URL + "/default", props)) {
                System.out.println("jdbc-v2, BEGIN PRIVATE KEY: connected");
            } catch (Exception e) {
                print("jdbc-v2, BEGIN PRIVATE KEY", e);
            }
    
            try {
                ClickHouseDefaultSslContextProvider.getPrivateKey(keyPkcs8);
                System.out.println("v1 client, BEGIN PRIVATE KEY: key read");
            } catch (Exception e) {
                print("v1 client, BEGIN PRIVATE KEY", e);
            }
        }
    }

    Output on main (8480ca001), ClickHouse 26.11.4.11 (the client fails before it connects):

    key: EC, PKCS#8
    client-v2, BEGIN PRIVATE KEY: com.clickhouse.client.api.ClientMisconfigurationException: Failed to create SSL context | root cause: java.io.IOException: Version must be 0
    client-v2, BEGIN EC PRIVATE KEY: client built, SSL context OK
    jdbc-v2, BEGIN PRIVATE KEY: java.sql.SQLException: Failed to create connection | root cause: java.io.IOException: Version must be 0
    v1 client, BEGIN PRIVATE KEY: java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: Invalid RSA private key | root cause: java.io.IOException: Version must be 0
    

    Automated triage by Polyglot AI. A maintainer makes the final decision.

  9. added
    jdbc
    on Nov 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

bugclientconnectivityjdbc

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions