Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parse PEM Key files leniantly #33173

Merged
merged 4 commits into from
Aug 29, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ public class PemUtils {
private static final String OPENSSL_EC_FOOTER = "-----END EC PRIVATE KEY-----";
private static final String OPENSSL_EC_PARAMS_HEADER = "-----BEGIN EC PARAMETERS-----";
private static final String OPENSSL_EC_PARAMS_FOOTER = "-----END EC PARAMETERS-----";
private static final String HEADER = "-----BEGIN";

private PemUtils() {
throw new IllegalStateException("Utility class should not be instantiated");
Expand All @@ -74,6 +75,9 @@ private PemUtils() {
public static PrivateKey readPrivateKey(Path keyPath, Supplier<char[]> passwordSupplier) {
try (BufferedReader bReader = Files.newBufferedReader(keyPath, StandardCharsets.UTF_8)) {
String line = bReader.readLine();
while (null != line && line.startsWith(HEADER) == false){
line = bReader.readLine();
}
if (null == line) {
throw new IllegalStateException("Error parsing Private Key from: " + keyPath.toString() + ". File is empty");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,16 @@ public void testReadPKCS8RsaKey() throws Exception {
assertThat(privateKey, equalTo(key));
}

public void testReadPKCS8RsaKeyWithBagAttrs() throws Exception {
Key key = getKeyFromKeystore("RSA");
assertThat(key, notNullValue());
assertThat(key, instanceOf(PrivateKey.class));
PrivateKey privateKey = PemUtils.readPrivateKey(getDataPath
("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode_with_bagattrs.pem"), ""::toCharArray);
assertThat(privateKey, notNullValue());
assertThat(privateKey, equalTo(key));
}

public void testReadPKCS8DsaKey() throws Exception {
Key key = getKeyFromKeystore("DSA");
assertThat(key, notNullValue());
Expand Down