From f6184c75c61dc1f2f24d4de5bb3e90b420c6a273 Mon Sep 17 00:00:00 2001 From: rmartinc Date: Wed, 7 Oct 2026 18:40:50 +0200 Subject: [PATCH] Use generateCertifiactes and BC Provider in TruststoreBuilder.mergePemFile Closes #53704 Signed-off-by: rmartinc --- .../truststore/TruststoreBuilder.java | 39 +++++++------------ 1 file changed, 14 insertions(+), 25 deletions(-) diff --git a/services/src/main/java/org/keycloak/truststore/TruststoreBuilder.java b/services/src/main/java/org/keycloak/truststore/TruststoreBuilder.java index 031843062f08..f8795930ebb6 100644 --- a/services/src/main/java/org/keycloak/truststore/TruststoreBuilder.java +++ b/services/src/main/java/org/keycloak/truststore/TruststoreBuilder.java @@ -27,6 +27,7 @@ import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.stream.Stream; @@ -268,33 +269,21 @@ static KeyStore loadStore(String path, String type, String password) { static boolean mergePemFile(KeyStore truststore, String file, boolean isPem) { try (FileInputStream pemInputStream = new FileInputStream(file)) { - CertificateFactory certFactory = CertificateFactory.getInstance("X509"); - boolean loadedAny = false; - while (pemInputStream.available() > 0) { - X509Certificate cert; - try { - cert = (X509Certificate) certFactory.generateCertificate(pemInputStream); - loadedAny = true; - } catch (CertificateException e) { - if (pemInputStream.available() > 0 || !loadedAny) { - // any remaining input means there is an actual problem with the key contents or - // file format - if (isPem || loadedAny) { - throw e; - } - LOGGER.debugf(e, - "The file %s may not be in PEM format, it will not be used to create the merged truststore", - new File(file).getAbsolutePath()); - continue; - } - LOGGER.debugf(e, - "The trailing entry for %s generated a certificate exception, assuming instead that the file ends with comments", - new File(file).getAbsolutePath()); - continue; - } + CertificateFactory certFactory = CertificateFactory.getInstance("X509", CryptoIntegration.getProvider().getBouncyCastleProvider()); + Collection certs = (Collection) certFactory.generateCertificates(pemInputStream); + for (X509Certificate cert : certs) { setCertificateEntry(truststore, cert); } - return loadedAny; + return !certs.isEmpty(); + } catch (CertificateException e) { + if (isPem) { + throw new RuntimeException( + "Failed to initialize truststore, could not merge: " + new File(file).getAbsolutePath(), e); + } + LOGGER.debugf(e, + "The file %s may not be in PEM format, it will not be used to create the merged truststore", + new File(file).getAbsolutePath()); + return false; } catch (Exception e) { throw new RuntimeException( "Failed to initialize truststore, could not merge: " + new File(file).getAbsolutePath(), e);