Skip to content

Commit adc5665

Browse files
committed
[fix] PKey.read to parse subject PKI
1 parent 5651d85 commit adc5665

File tree

2 files changed

+17
-5
lines changed

2 files changed

+17
-5
lines changed

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

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -139,11 +139,24 @@ public static KeyPair readPrivateKey(final Type type, final PrivateKeyInfo keyIn
139139

140140
// d2i_PUBKEY_bio
141141
public static PublicKey readPublicKey(final byte[] input) throws IOException {
142+
// Try PEM first
142143
try (Reader in = new InputStreamReader(new ByteArrayInputStream(input))) {
143144
Object pemObject = new PEMParser(in).readObject();
144-
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(pemObject);
145-
return new JcaPEMKeyConverter().getPublicKey(publicKeyInfo);
145+
if (pemObject != null) {
146+
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(pemObject);
147+
return new JcaPEMKeyConverter().getPublicKey(publicKeyInfo);
148+
}
146149
}
150+
// Fall back to DER-encoded SubjectPublicKeyInfo
151+
try {
152+
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(ASN1Primitive.fromByteArray(input));
153+
if (publicKeyInfo != null) {
154+
return new JcaPEMKeyConverter().getPublicKey(publicKeyInfo);
155+
}
156+
} catch (Exception e) {
157+
throw new IOException("Could not parse public key: " + e.getMessage(), e);
158+
}
159+
return null;
147160
}
148161

149162
// d2i_RSAPrivateKey_bio

src/test/ruby/rsa/test_rsa.rb

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -412,8 +412,7 @@ def test_private_encoding_encrypted
412412
def test_export
413413
rsa1024 = Fixtures.pkey("rsa1024")
414414

415-
#pub = OpenSSL::PKey.read(rsa1024.public_to_der) # TODO not supported
416-
pub = OpenSSL::PKey::RSA.new(rsa1024.public_to_der)
415+
pub = OpenSSL::PKey.read(rsa1024.public_to_der)
417416
assert_not_equal rsa1024.export, pub.export
418417
assert_equal rsa1024.public_to_pem, pub.export
419418

@@ -438,7 +437,7 @@ def test_export
438437
def test_to_der
439438
rsa1024 = Fixtures.pkey("rsa1024")
440439

441-
pub = OpenSSL::PKey::RSA.new(rsa1024.public_to_der)
440+
pub = OpenSSL::PKey.read(rsa1024.public_to_der)
442441
assert_not_equal rsa1024.to_der, pub.to_der
443442
assert_equal rsa1024.public_to_der, pub.to_der
444443

0 commit comments

Comments
 (0)