Skip to content

Commit e2ac4ec

Browse files
committed
Handle encrypted key pair.
1 parent da97ae4 commit e2ac4ec

File tree

1 file changed

+22
-2
lines changed
  • src/main/java/org/jruby/ext/openssl/impl

1 file changed

+22
-2
lines changed

src/main/java/org/jruby/ext/openssl/impl/PKey.java

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,10 @@
7373
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
7474
import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
7575
import org.bouncycastle.jcajce.provider.asymmetric.util.KeyUtil;
76+
import org.bouncycastle.openssl.PEMEncryptedKeyPair;
7677
import org.bouncycastle.openssl.PEMParser;
78+
import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
79+
import org.bouncycastle.util.io.pem.PemObject;
7780
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
7881

7982
import org.jruby.ext.openssl.SecurityHelper;
@@ -141,8 +144,25 @@ public static KeyPair readPrivateKey(final Type type, final PrivateKeyInfo keyIn
141144
public static PublicKey readPublicKey(final byte[] input) throws IOException {
142145
try (Reader in = new InputStreamReader(new ByteArrayInputStream(input))) {
143146
Object pemObject = new PEMParser(in).readObject();
144-
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(pemObject);
145-
return new JcaPEMKeyConverter().getPublicKey(publicKeyInfo);
147+
try {
148+
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(pemObject);
149+
return new JcaPEMKeyConverter().getPublicKey(publicKeyInfo);
150+
} catch (IllegalArgumentException e) {
151+
if (pemObject instanceof PEMEncryptedKeyPair) {
152+
try {
153+
PEMEncryptedKeyPair encrypted = (PEMEncryptedKeyPair) pemObject;
154+
org.bouncycastle.openssl.PEMKeyPair pemKeyPair = encrypted.decryptKeyPair(new JcePEMDecryptorProviderBuilder().build((char[]) null));
155+
KeyPair keyPair = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
156+
return keyPair.getPublic();
157+
} catch (Exception ex) {
158+
throw new IOException("Encrypted private key requires password for public key reading", ex);
159+
}
160+
} else if (pemObject instanceof KeyPair) {
161+
return ((KeyPair) pemObject).getPublic();
162+
} else {
163+
throw e;
164+
}
165+
}
146166
}
147167
}
148168

0 commit comments

Comments
 (0)