Skip to content

Commit 1cd0667

Browse files
authored
Merge pull request #479 from rhenium/ky/pkey-ossl-decoder
pkey: use OSSL_DECODER to load encrypted PEM on OpenSSL 3.0
2 parents 8193b73 + a84ea53 commit 1cd0667

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

ext/openssl/ossl_pkey.c

+40
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,45 @@ ossl_pkey_new(EVP_PKEY *pkey)
7979
return obj;
8080
}
8181

82+
#if OSSL_OPENSSL_PREREQ(3, 0, 0)
83+
# include <openssl/decoder.h>
84+
85+
EVP_PKEY *
86+
ossl_pkey_read_generic(BIO *bio, VALUE pass)
87+
{
88+
void *ppass = (void *)pass;
89+
OSSL_DECODER_CTX *dctx;
90+
EVP_PKEY *pkey = NULL;
91+
int pos = 0, pos2;
92+
93+
dctx = OSSL_DECODER_CTX_new_for_pkey(&pkey, "DER", NULL, NULL, 0, NULL, NULL);
94+
if (!dctx)
95+
goto out;
96+
if (OSSL_DECODER_CTX_set_pem_password_cb(dctx, ossl_pem_passwd_cb, ppass) != 1)
97+
goto out;
98+
99+
/* First check DER */
100+
if (OSSL_DECODER_from_bio(dctx, bio) == 1)
101+
goto out;
102+
103+
/* Then check PEM; multiple OSSL_DECODER_from_bio() calls may be needed */
104+
OSSL_BIO_reset(bio);
105+
if (OSSL_DECODER_CTX_set_input_type(dctx, "PEM") != 1)
106+
goto out;
107+
while (OSSL_DECODER_from_bio(dctx, bio) != 1) {
108+
if (BIO_eof(bio))
109+
goto out;
110+
pos2 = BIO_tell(bio);
111+
if (pos2 < 0 || pos2 <= pos)
112+
goto out;
113+
pos = pos2;
114+
}
115+
116+
out:
117+
OSSL_DECODER_CTX_free(dctx);
118+
return pkey;
119+
}
120+
#else
82121
EVP_PKEY *
83122
ossl_pkey_read_generic(BIO *bio, VALUE pass)
84123
{
@@ -107,6 +146,7 @@ ossl_pkey_read_generic(BIO *bio, VALUE pass)
107146
out:
108147
return pkey;
109148
}
149+
#endif
110150

111151
/*
112152
* call-seq:

test/openssl/test_pkey_rsa.rb

+6
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,12 @@ def test_RSAPrivateKey
306306

307307
assert_equal asn1.to_der, rsa1024.to_der
308308
assert_equal pem, rsa1024.export
309+
310+
# Unknown PEM prepended
311+
cert = issue_cert(OpenSSL::X509::Name.new([["CN", "nobody"]]), rsa1024, 1, [], nil, nil)
312+
str = cert.to_text + cert.to_pem + rsa1024.to_pem
313+
key = OpenSSL::PKey::RSA.new(str)
314+
assert_same_rsa rsa1024, key
309315
end
310316

311317
def test_RSAPrivateKey_encrypted

0 commit comments

Comments
 (0)