|
73 | 73 | import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; |
74 | 74 | import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; |
75 | 75 | import org.bouncycastle.jcajce.provider.asymmetric.util.KeyUtil; |
| 76 | +import org.bouncycastle.openssl.PEMEncryptedKeyPair; |
76 | 77 | import org.bouncycastle.openssl.PEMParser; |
| 78 | +import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder; |
| 79 | +import org.bouncycastle.util.io.pem.PemObject; |
77 | 80 | import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; |
78 | 81 |
|
79 | 82 | import org.jruby.ext.openssl.SecurityHelper; |
@@ -141,8 +144,25 @@ public static KeyPair readPrivateKey(final Type type, final PrivateKeyInfo keyIn |
141 | 144 | public static PublicKey readPublicKey(final byte[] input) throws IOException { |
142 | 145 | try (Reader in = new InputStreamReader(new ByteArrayInputStream(input))) { |
143 | 146 | 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 | + } |
146 | 166 | } |
147 | 167 | } |
148 | 168 |
|
|
0 commit comments