From e0b4c56956ef4ef3ab47cf5d2eed55fbcc5152e8 Mon Sep 17 00:00:00 2001 From: Kazuki Yamaguchi Date: Sun, 17 May 2020 18:25:38 +0900 Subject: pkey: implement #to_text using EVP API Use EVP_PKEY_print_private() instead of the low-level API *_print() functions, such as RSA_print(). EVP_PKEY_print_*() family was added in OpenSSL 1.0.0. Note that it falls back to EVP_PKEY_print_public() and EVP_PKEY_print_params() as necessary. This is required for EVP_PKEY_DH type for which _private() fails if the private component is not set in the pkey object. Since the new API works in the same way for all key types, we now implement #to_text in the base class OpenSSL::PKey::PKey rather than in each subclass. --- ext/openssl/ossl_pkey.c | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) (limited to 'ext/openssl/ossl_pkey.c') diff --git a/ext/openssl/ossl_pkey.c b/ext/openssl/ossl_pkey.c index 593788e1..b92c8a66 100644 --- a/ext/openssl/ossl_pkey.c +++ b/ext/openssl/ossl_pkey.c @@ -539,6 +539,43 @@ ossl_pkey_inspect(VALUE self) OBJ_nid2sn(nid)); } +/* + * call-seq: + * pkey.to_text -> string + * + * Dumps key parameters, public key, and private key components contained in + * the key into a human-readable text. + * + * This is intended for debugging purpose. + * + * See also the man page EVP_PKEY_print_private(3). + */ +static VALUE +ossl_pkey_to_text(VALUE self) +{ + EVP_PKEY *pkey; + BIO *bio; + + GetPKey(self, pkey); + if (!(bio = BIO_new(BIO_s_mem()))) + ossl_raise(ePKeyError, "BIO_new"); + + if (EVP_PKEY_print_private(bio, pkey, 0, NULL) == 1) + goto out; + OSSL_BIO_reset(bio); + if (EVP_PKEY_print_public(bio, pkey, 0, NULL) == 1) + goto out; + OSSL_BIO_reset(bio); + if (EVP_PKEY_print_params(bio, pkey, 0, NULL) == 1) + goto out; + + BIO_free(bio); + ossl_raise(ePKeyError, "EVP_PKEY_print_params"); + + out: + return ossl_membio2str(bio); +} + VALUE ossl_pkey_export_traditional(int argc, VALUE *argv, VALUE self, int to_der) { @@ -1077,6 +1114,7 @@ Init_ossl_pkey(void) rb_define_method(cPKey, "initialize", ossl_pkey_initialize, 0); rb_define_method(cPKey, "oid", ossl_pkey_oid, 0); rb_define_method(cPKey, "inspect", ossl_pkey_inspect, 0); + rb_define_method(cPKey, "to_text", ossl_pkey_to_text, 0); rb_define_method(cPKey, "private_to_der", ossl_pkey_private_to_der, -1); rb_define_method(cPKey, "private_to_pem", ossl_pkey_private_to_pem, -1); rb_define_method(cPKey, "public_to_der", ossl_pkey_public_to_der, 0); -- cgit v1.2.3