From 53c0ec0493762bdc605887eaee99a5ec0f1bedca Mon Sep 17 00:00:00 2001 From: egidijus-kuzma Date: Sat, 3 Sep 2022 22:46:38 +0300 Subject: [PATCH] DSSUtils.loadCertificates() fixing openssl backed security provider issue --- .../java/eu/europa/esig/dss/spi/DSSUtils.java | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/dss-spi/src/main/java/eu/europa/esig/dss/spi/DSSUtils.java b/dss-spi/src/main/java/eu/europa/esig/dss/spi/DSSUtils.java index 7d828ef959..28a20f0f1a 100644 --- a/dss-spi/src/main/java/eu/europa/esig/dss/spi/DSSUtils.java +++ b/dss-spi/src/main/java/eu/europa/esig/dss/spi/DSSUtils.java @@ -289,9 +289,57 @@ public static List loadCertificateFromP7c(InputStream is) { return loadCertificates(is); } + /** + * @Important + * Openssl backed security provider can read certificate, if + * some custom metadata before -----BEGIN CERTIFICATE----- is added + * + * Fore example: + * + * Certificate: + * Data: + * Version: 3 (0x2) + * Serial Number: + * 03:9a:a4:cd:b1:9b:14:21:85:bf:8f:76:2a:5f:7f:46 + * -----BEGIN CERTIFICATE----- + * + * Temporary workaround is strip certificate, by + * loading string bouncy castle tools and exporting. + * Full certificate generation with BC provider possible, + * but still much slower solution. + */ + static InputStream normalizePemFormat(InputStream stream) { + PemReader pemReader = new PemReader(new InputStreamReader(stream)); + try { + PemObject pemObject = pemReader.readPemObject(); + + if(pemObject == null) { + throw new IllegalArgumentException("Failed to parse pem certificate"); + } + + byte[] content = pemObject.getContent(); + + return new ByteArrayInputStream(content); + } catch (IOException e) { + throw new DSSException(e); + } + } + private static List loadCertificates(InputStream is) { final List certificates = new ArrayList<>(); try { + + byte[] copyOfInputStream = DSSUtils.toByteArray(is); + + try { + InputStream inputStream = normalizePemFormat(new ByteArrayInputStream(copyOfInputStream)); + copyOfInputStream = DSSUtils.toByteArray(inputStream); + } + catch (IllegalArgumentException e) { + //ignore + } + + byte[] finalCopyOfInputStream = copyOfInputStream; @SuppressWarnings("unchecked") final Collection certificatesCollection = CryptoProvider.bind((provider) -> { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", provider);