From d53e39e58aeca1d3cf98ee00394d8f1d73d1a92e Mon Sep 17 00:00:00 2001 From: "Zboncakova, Tatiana" Date: Thu, 8 Aug 2024 17:00:57 +0200 Subject: [PATCH] Introduce system property for lax PEM parsing. --- .../bouncycastle/util/io/pem/PemReader.java | 14 +++++++++ .../util/io/pem/test/AllTests.java | 30 +++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/core/src/main/java/org/bouncycastle/util/io/pem/PemReader.java b/core/src/main/java/org/bouncycastle/util/io/pem/PemReader.java index 2d681b9bee..8c3a89f24d 100644 --- a/core/src/main/java/org/bouncycastle/util/io/pem/PemReader.java +++ b/core/src/main/java/org/bouncycastle/util/io/pem/PemReader.java @@ -5,6 +5,8 @@ import java.io.Reader; import java.util.ArrayList; import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; import org.bouncycastle.util.encoders.Base64; @@ -16,6 +18,8 @@ public class PemReader { private static final String BEGIN = "-----BEGIN "; private static final String END = "-----END "; + public static final String LAX_PARSING_SYSTEM_PROPERTY_NAME = "org.bouncycastle.pemreader.lax"; + private static final Logger LOG = Logger.getLogger(PemReader.class.getName()); public PemReader(Reader reader) { @@ -75,6 +79,16 @@ private PemObject loadObject(String type) continue; } + if (System.getProperty(LAX_PARSING_SYSTEM_PROPERTY_NAME, "false").equalsIgnoreCase("true")) + { + String trimmedLine = line.trim(); + if (!trimmedLine.equals(line) && LOG.isLoggable(Level.WARNING)) + { + LOG.log(Level.WARNING, "PEM object contains whitespaces on -----END line", new Exception("trace")); + } + line = trimmedLine; + } + if (line.indexOf(endMarker) == 0) { break; diff --git a/core/src/test/java/org/bouncycastle/util/io/pem/test/AllTests.java b/core/src/test/java/org/bouncycastle/util/io/pem/test/AllTests.java index 189d829b0f..9c43457a83 100644 --- a/core/src/test/java/org/bouncycastle/util/io/pem/test/AllTests.java +++ b/core/src/test/java/org/bouncycastle/util/io/pem/test/AllTests.java @@ -18,6 +18,8 @@ import org.bouncycastle.util.io.pem.PemReader; import org.bouncycastle.util.io.pem.PemWriter; +import static org.bouncycastle.util.io.pem.PemReader.LAX_PARSING_SYSTEM_PROPERTY_NAME; + public class AllTests extends TestCase { @@ -122,6 +124,34 @@ public void testRegularBlobEndFault() } } + public void testRegularBlobEndLaxParsing() + throws IOException + { + String original = System.setProperty(LAX_PARSING_SYSTEM_PROPERTY_NAME, "true"); + PemReader rd = new PemReader(new StringReader(blob4)); + + PemObject obj; + try + { + obj = rd.readPemObject(); + } + finally + { + if (original != null) + { + System.setProperty(LAX_PARSING_SYSTEM_PROPERTY_NAME, original); + } + else + { + System.clearProperty(LAX_PARSING_SYSTEM_PROPERTY_NAME); + } + } + + assertEquals("BLOB", obj.getType()); + assertTrue(Arrays.areEqual(new byte[64], obj.getContent())); + + } + private void lengthTest(String type, List headers, byte[] data) throws IOException {