Skip to content

Commit

Permalink
Improved extracting public key
Browse files Browse the repository at this point in the history
  • Loading branch information
Hakky54 committed Nov 9, 2023
1 parent 088bc3f commit 9c9e4f6
Showing 1 changed file with 9 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.file.Path;
import java.security.KeyPair;
import java.security.PrivateKey;
Expand Down Expand Up @@ -527,16 +528,18 @@ private static PrivateKey extractPrivateKey(PrivateKeyInfo privateKeyInfo) {
}

public static PublicKey extractPublicKey(PrivateKey privateKey) {
try(StringWriter writer = new StringWriter()) {
try(Writer writer = new StringWriter();
PemWriter pemWriter = new PemWriter(writer)) {

JcaMiscPEMGenerator pemGenerator = new JcaMiscPEMGenerator(privateKey, null);
PemObject pemObject = pemGenerator.generate();

PemWriter pemWriter = new PemWriter(writer);
pemWriter.writeObject(pemObject);
pemWriter.close();
pemWriter.flush();

String pemContent = writer.toString();

try(StringReader stringReader = new StringReader(writer.toString());
PEMParser pemParser = new PEMParser(stringReader)) {
try(Reader reader = new StringReader(pemContent);
PEMParser pemParser = new PEMParser(reader)) {
Object object = pemParser.readObject();
if (object instanceof PEMKeyPair) {
PEMKeyPair pemKeyPair = (PEMKeyPair) object;
Expand Down

0 comments on commit 9c9e4f6

Please sign in to comment.