From 06d3e71ddd09ef9837b88bce0120626387b2fa61 Mon Sep 17 00:00:00 2001 From: 5ec1cff Date: Mon, 15 Jul 2024 11:21:33 +0800 Subject: [PATCH] Fix regex for parsing PEMs Lesson: never trust stackoverflow. --- .../io/github/aviraxp/keystoreinjection/CertUtils.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) 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 d14c43e..98e0869 100644 --- a/app/src/main/java/io/github/aviraxp/keystoreinjection/CertUtils.java +++ b/app/src/main/java/io/github/aviraxp/keystoreinjection/CertUtils.java @@ -14,11 +14,13 @@ import java.security.KeyPair; import java.security.PrivateKey; import java.security.cert.Certificate; +import java.util.regex.Pattern; public class CertUtils { + private static final Pattern lineTrimmer = Pattern.compile("^\\s+|\\s+$", Pattern.MULTILINE); public static Certificate parseCert(String cert) throws Throwable { - cert = cert.trim().replaceAll("(?m)^[\s&&[^\n]]+|[\s+&&[^\n]]+$", ""); + cert = lineTrimmer.matcher(cert).replaceAll(""); PemObject pemObject; try (PemReader reader = new PemReader(new StringReader(cert))) { pemObject = reader.readPemObject(); @@ -30,7 +32,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]]+$", ""); + cert = lineTrimmer.matcher(cert).replaceAll(""); PemObject pemObject; try (PemReader reader = new PemReader(new StringReader(cert))) { pemObject = reader.readPemObject(); @@ -42,7 +44,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]]+$", ""); + key = lineTrimmer.matcher(key).replaceAll(""); Object object; try (PEMParser parser = new PEMParser(new StringReader(key))) { object = parser.readObject(); @@ -54,7 +56,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]]+$", ""); + keyPair = lineTrimmer.matcher(keyPair).replaceAll(""); try (PEMParser parser = new PEMParser(new StringReader(keyPair))) { PEMKeyPair pemKeyPair = (PEMKeyPair) parser.readObject(); return new JcaPEMKeyConverter().getPrivateKey(pemKeyPair.getPrivateKeyInfo());