From 322ce4e5f11cb99c0c2433f71ce62af351a8a282 Mon Sep 17 00:00:00 2001 From: Wang Han <416810799@qq.com> Date: Sun, 23 Jun 2024 01:30:49 +0800 Subject: [PATCH] Trim PEMs manually before parsing BC PemReader (Parser) does not support whitespaces in PEMs so format texts which are read from keybox xml in advance. https://stackoverflow.com/questions/19269043/ --- .../java/io/github/aviraxp/keystoreinjection/CertUtils.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/app/src/main/java/io/github/aviraxp/keystoreinjection/CertUtils.java b/app/src/main/java/io/github/aviraxp/keystoreinjection/CertUtils.java index 5de3f14..d14c43e 100644 --- a/app/src/main/java/io/github/aviraxp/keystoreinjection/CertUtils.java +++ b/app/src/main/java/io/github/aviraxp/keystoreinjection/CertUtils.java @@ -18,6 +18,7 @@ public class CertUtils { public static Certificate parseCert(String cert) throws Throwable { + cert = cert.trim().replaceAll("(?m)^[\s&&[^\n]]+|[\s+&&[^\n]]+$", ""); PemObject pemObject; try (PemReader reader = new PemReader(new StringReader(cert))) { pemObject = reader.readPemObject(); @@ -29,6 +30,7 @@ public static Certificate parseCert(String cert) throws Throwable { } public static X500Name parseCertSubject(String cert) throws Throwable { + cert = cert.trim().replaceAll("(?m)^[\s&&[^\n]]+|[\s+&&[^\n]]+$", ""); PemObject pemObject; try (PemReader reader = new PemReader(new StringReader(cert))) { pemObject = reader.readPemObject(); @@ -40,6 +42,7 @@ public static X500Name parseCertSubject(String cert) throws Throwable { } public static KeyPair parseKeyPair(String key) throws Throwable { + key = key.trim().replaceAll("(?m)^[\s&&[^\n]]+|[\s+&&[^\n]]+$", ""); Object object; try (PEMParser parser = new PEMParser(new StringReader(key))) { object = parser.readObject(); @@ -51,6 +54,7 @@ public static KeyPair parseKeyPair(String key) throws Throwable { } public static PrivateKey parsePrivateKey(String keyPair) throws RuntimeException { + keyPair = keyPair.trim().replaceAll("(?m)^[\s&&[^\n]]+|[\s+&&[^\n]]+$", ""); try (PEMParser parser = new PEMParser(new StringReader(keyPair))) { PEMKeyPair pemKeyPair = (PEMKeyPair) parser.readObject(); return new JcaPEMKeyConverter().getPrivateKey(pemKeyPair.getPrivateKeyInfo());