Skip to content
This repository has been archived by the owner on Jul 19, 2024. It is now read-only.

Commit

Permalink
Fix regex for parsing PEMs
Browse files Browse the repository at this point in the history
Lesson: never trust stackoverflow.
  • Loading branch information
5ec1cff authored and aviraxp committed Jul 15, 2024
1 parent ff638f9 commit 06d3e71
Showing 1 changed file with 6 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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();
Expand All @@ -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();
Expand All @@ -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());
Expand Down

0 comments on commit 06d3e71

Please sign in to comment.