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

Commit

Permalink
Trim PEMs manually before parsing
Browse files Browse the repository at this point in the history
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/
  • Loading branch information
aviraxp committed Jun 22, 2024
1 parent c43f209 commit 322ce4e
Showing 1 changed file with 4 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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();
Expand All @@ -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();
Expand All @@ -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());
Expand Down

0 comments on commit 322ce4e

Please sign in to comment.