92efb0436ef0bec0c196471e129cd43ccb8e35ba
[openssl.git] / providers / implementations / encode_decode / encode_key2text.c
1 /*
2  * Copyright 2020 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 /*
11  * Low level APIs are deprecated for public use, but still ok for internal use.
12  */
13 #include "internal/deprecated.h"
14
15 #include <ctype.h>
16
17 #include <openssl/core.h>
18 #include <openssl/core_dispatch.h>
19 #include <openssl/core_names.h>
20 #include <openssl/bn.h>
21 #include <openssl/err.h>
22 #include <openssl/safestack.h>
23 #include "internal/ffc.h"
24 #include "crypto/bn.h"           /* bn_get_words() */
25 #include "crypto/dh.h"           /* dh_get0_params() */
26 #include "crypto/dsa.h"          /* dsa_get0_params() */
27 #include "crypto/ec.h"           /* ec_key_get_libctx */
28 #include "crypto/ecx.h"          /* ECX_KEY, etc... */
29 #include "crypto/rsa.h"          /* RSA_PSS_PARAMS_30, etc... */
30 #include "prov/bio.h"
31 #include "prov/implementations.h"
32 #include "prov/providercommonerr.h"
33 #include "endecoder_local.h"
34
35 DEFINE_SPECIAL_STACK_OF_CONST(BIGNUM_const, BIGNUM)
36
37 # ifdef SIXTY_FOUR_BIT_LONG
38 #  define BN_FMTu "%lu"
39 #  define BN_FMTx "%lx"
40 # endif
41
42 # ifdef SIXTY_FOUR_BIT
43 #  define BN_FMTu "%llu"
44 #  define BN_FMTx "%llx"
45 # endif
46
47 # ifdef THIRTY_TWO_BIT
48 #  define BN_FMTu "%u"
49 #  define BN_FMTx "%x"
50 # endif
51
52 static int print_labeled_bignum(BIO *out, const char *label, const BIGNUM *bn)
53 {
54     int ret = 0, use_sep = 0;
55     char *hex_str = NULL, *p;
56     const char spaces[] = "    ";
57     const char *post_label_spc = " ";
58
59     const char *neg = "";
60     int bytes;
61
62     if (bn == NULL)
63         return 0;
64     if (label == NULL) {
65         label = "";
66         post_label_spc = "";
67     }
68
69     if (BN_is_zero(bn))
70         return BIO_printf(out, "%s%s0\n", label, post_label_spc);
71
72     if (BN_num_bytes(bn) <= BN_BYTES) {
73         BN_ULONG *words = bn_get_words(bn);
74
75         if (BN_is_negative(bn))
76             neg = "-";
77
78         return BIO_printf(out, "%s%s%s" BN_FMTu " (%s0x" BN_FMTx ")\n",
79                           label, post_label_spc, neg, words[0], neg, words[0]);
80     }
81
82     hex_str = BN_bn2hex(bn);
83     p = hex_str;
84     if (*p == '-') {
85         ++p;
86         neg = " (Negative)";
87     }
88     if (BIO_printf(out, "%s%s\n", label, neg) <= 0)
89         goto err;
90
91     /* Keep track of how many bytes we have printed out so far */
92     bytes = 0;
93
94     if (BIO_printf(out, "%s", spaces) <= 0)
95         goto err;
96
97     /* Add a leading 00 if the top bit is set */
98     if (*p >= '8') {
99         if (BIO_printf(out, "%02x", 0) <= 0)
100             goto err;
101         ++bytes;
102         use_sep = 1;
103     }
104     while (*p != '\0') {
105         /* Do a newline after every 15 hex bytes + add the space indent */
106         if ((bytes % 15) == 0 && bytes > 0) {
107             if (BIO_printf(out, ":\n%s", spaces) <= 0)
108                 goto err;
109             use_sep = 0; /* The first byte on the next line doesnt have a : */
110         }
111         if (BIO_printf(out, "%s%c%c", use_sep ? ":" : "",
112                        tolower(p[0]), tolower(p[1])) <= 0)
113             goto err;
114         ++bytes;
115         p += 2;
116         use_sep = 1;
117     }
118     if (BIO_printf(out, "\n") <= 0)
119         goto err;
120     ret = 1;
121 err:
122     OPENSSL_free(hex_str);
123     return ret;
124 }
125
126 /* Number of octets per line */
127 #define LABELED_BUF_PRINT_WIDTH    15
128
129 static int print_labeled_buf(BIO *out, const char *label,
130                              const unsigned char *buf, size_t buflen)
131 {
132     size_t i;
133
134     if (BIO_printf(out, "%s\n", label) <= 0)
135         return 0;
136
137     for (i = 0; i < buflen; i++) {
138         if ((i % LABELED_BUF_PRINT_WIDTH) == 0) {
139             if (i > 0 && BIO_printf(out, "\n") <= 0)
140                 return 0;
141             if (BIO_printf(out, "    ") <= 0)
142                 return 0;
143         }
144
145         if (BIO_printf(out, "%02x%s", buf[i],
146                                  (i == buflen - 1) ? "" : ":") <= 0)
147             return 0;
148     }
149     if (BIO_printf(out, "\n") <= 0)
150         return 0;
151
152     return 1;
153 }
154
155 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_DSA)
156 static int ffc_params_to_text(BIO *out, const FFC_PARAMS *ffc)
157 {
158     if (ffc->nid != NID_undef) {
159 #ifndef OPENSSL_NO_DH
160         const char *name = ossl_ffc_named_group_from_uid(ffc->nid);
161
162         if (name == NULL)
163             goto err;
164         if (BIO_printf(out, "GROUP: %s\n", name) <= 0)
165             goto err;
166         return 1;
167 #else
168         /* How could this be? We should not have a nid in a no-dh build. */
169         goto err;
170 #endif
171     }
172
173     if (!print_labeled_bignum(out, "P:   ", ffc->p))
174         goto err;
175     if (ffc->q != NULL) {
176         if (!print_labeled_bignum(out, "Q:   ", ffc->q))
177             goto err;
178     }
179     if (!print_labeled_bignum(out, "G:   ", ffc->g))
180         goto err;
181     if (ffc->j != NULL) {
182         if (!print_labeled_bignum(out, "J:   ", ffc->j))
183             goto err;
184     }
185     if (ffc->seed != NULL) {
186         if (!print_labeled_buf(out, "SEED:", ffc->seed, ffc->seedlen))
187             goto err;
188     }
189     if (ffc->gindex != -1) {
190         if (BIO_printf(out, "gindex: %d\n", ffc->gindex) <= 0)
191             goto err;
192     }
193     if (ffc->pcounter != -1) {
194         if (BIO_printf(out, "pcounter: %d\n", ffc->pcounter) <= 0)
195             goto err;
196     }
197     if (ffc->h != 0) {
198         if (BIO_printf(out, "h: %d\n", ffc->h) <= 0)
199             goto err;
200     }
201     return 1;
202 err:
203     return 0;
204 }
205 #endif
206
207 /* ---------------------------------------------------------------------- */
208
209 #ifndef OPENSSL_NO_DH
210 static int dh_to_text(BIO *out, const void *key, int selection)
211 {
212     const DH *dh = key;
213     const char *type_label = NULL;
214     const BIGNUM *priv_key = NULL, *pub_key = NULL;
215     const FFC_PARAMS *params = NULL;
216     const BIGNUM *p = NULL;
217
218     if (out == NULL || dh == NULL) {
219         ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_NULL_PARAMETER);
220         return 0;
221     }
222
223     if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0)
224         type_label = "DH Private-Key";
225     else if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0)
226         type_label = "DH Public-Key";
227     else if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0)
228         type_label = "DH Parameters";
229
230     if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) {
231         priv_key = DH_get0_priv_key(dh);
232         if (priv_key == NULL) {
233             ERR_raise(ERR_LIB_PROV, PROV_R_NOT_A_PRIVATE_KEY);
234             return 0;
235         }
236     }
237     if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) {
238         pub_key = DH_get0_pub_key(dh);
239         if (pub_key == NULL) {
240             ERR_raise(ERR_LIB_PROV, PROV_R_NOT_A_PUBLIC_KEY);
241             return 0;
242         }
243     }
244     if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0) {
245         params = dh_get0_params((DH *)dh);
246         if (params == NULL) {
247             ERR_raise(ERR_LIB_PROV, PROV_R_NOT_PARAMETERS);
248             return 0;
249         }
250     }
251
252     p = DH_get0_p(dh);
253     if (p == NULL) {
254         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY);
255         return 0;
256     }
257
258     if (BIO_printf(out, "%s: (%d bit)\n", type_label, BN_num_bits(p)) <= 0)
259         return 0;
260     if (priv_key != NULL
261         && !print_labeled_bignum(out, "private-key:", priv_key))
262         return 0;
263     if (pub_key != NULL
264         && !print_labeled_bignum(out, "public-key:", pub_key))
265         return 0;
266     if (params != NULL
267         && !ffc_params_to_text(out, params))
268         return 0;
269
270     return 1;
271 }
272
273 # define dh_input_type          "DH"
274 # define dhx_input_type         "DHX"
275 #endif
276
277 /* ---------------------------------------------------------------------- */
278
279 #ifndef OPENSSL_NO_DSA
280 static int dsa_to_text(BIO *out, const void *key, int selection)
281 {
282     const DSA *dsa = key;
283     const char *type_label = NULL;
284     const BIGNUM *priv_key = NULL, *pub_key = NULL;
285     const FFC_PARAMS *params = NULL;
286     const BIGNUM *p = NULL;
287
288     if (out == NULL || dsa == NULL) {
289         ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_NULL_PARAMETER);
290         return 0;
291     }
292
293     if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0)
294         type_label = "Private-Key";
295     else if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0)
296         type_label = "Public-Key";
297     else if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0)
298         type_label = "DSA-Parameters";
299
300     if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) {
301         priv_key = DSA_get0_priv_key(dsa);
302         if (priv_key == NULL) {
303             ERR_raise(ERR_LIB_PROV, PROV_R_NOT_A_PRIVATE_KEY);
304             return 0;
305         }
306     }
307     if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) {
308         pub_key = DSA_get0_pub_key(dsa);
309         if (pub_key == NULL) {
310             ERR_raise(ERR_LIB_PROV, PROV_R_NOT_A_PUBLIC_KEY);
311             return 0;
312         }
313     }
314     if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0) {
315         params = dsa_get0_params((DSA *)dsa);
316         if (params == NULL) {
317             ERR_raise(ERR_LIB_PROV, PROV_R_NOT_PARAMETERS);
318             return 0;
319         }
320     }
321
322     p = DSA_get0_p(dsa);
323     if (p == NULL) {
324         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY);
325         return 0;
326     }
327
328     if (BIO_printf(out, "%s: (%d bit)\n", type_label, BN_num_bits(p)) <= 0)
329         return 0;
330     if (priv_key != NULL
331         && !print_labeled_bignum(out, "priv:", priv_key))
332         return 0;
333     if (pub_key != NULL
334         && !print_labeled_bignum(out, "pub: ", pub_key))
335         return 0;
336     if (params != NULL
337         && !ffc_params_to_text(out, params))
338         return 0;
339
340     return 1;
341 }
342
343 # define dsa_input_type         "DSA"
344 #endif
345
346 /* ---------------------------------------------------------------------- */
347
348 #ifndef OPENSSL_NO_EC
349 static int ec_param_explicit_curve_to_text(BIO *out, const EC_GROUP *group,
350                                            BN_CTX *ctx)
351 {
352     const char *plabel = "Prime:";
353     BIGNUM *p = NULL, *a = NULL, *b = NULL;
354
355     p = BN_CTX_get(ctx);
356     a = BN_CTX_get(ctx);
357     b = BN_CTX_get(ctx);
358     if (b == NULL
359         || !EC_GROUP_get_curve(group, p, a, b, ctx))
360         return 0;
361
362     if (EC_GROUP_get_field_type(group) == NID_X9_62_characteristic_two_field) {
363         int basis_type = EC_GROUP_get_basis_type(group);
364
365         /* print the 'short name' of the base type OID */
366         if (basis_type == NID_undef
367             || BIO_printf(out, "Basis Type: %s\n", OBJ_nid2sn(basis_type)) <= 0)
368             return 0;
369         plabel = "Polynomial:";
370     }
371     return print_labeled_bignum(out, plabel, p)
372         && print_labeled_bignum(out, "A:   ", a)
373         && print_labeled_bignum(out, "B:   ", b);
374 }
375
376 static int ec_param_explicit_gen_to_text(BIO *out, const EC_GROUP *group,
377                                          BN_CTX *ctx)
378 {
379     const EC_POINT *point = NULL;
380     BIGNUM *gen = NULL;
381     const char *glabel = NULL;
382     point_conversion_form_t form;
383
384     form = EC_GROUP_get_point_conversion_form(group);
385     point = EC_GROUP_get0_generator(group);
386     gen = BN_CTX_get(ctx);
387
388     if (gen == NULL
389         || point == NULL
390         || EC_POINT_point2bn(group, point, form, gen, ctx) == NULL)
391         return 0;
392
393     switch (form) {
394     case POINT_CONVERSION_COMPRESSED:
395        glabel = "Generator (compressed):";
396        break;
397     case POINT_CONVERSION_UNCOMPRESSED:
398         glabel = "Generator (uncompressed):";
399         break;
400     case POINT_CONVERSION_HYBRID:
401         glabel = "Generator (hybrid):";
402         break;
403     default:
404         return 0;
405     }
406     return print_labeled_bignum(out, glabel, gen);
407 }
408
409 /* Print explicit parameters */
410 static int ec_param_explicit_to_text(BIO *out, const EC_GROUP *group,
411                                      OSSL_LIB_CTX *libctx)
412 {
413     int ret = 0, tmp_nid;
414     BN_CTX *ctx = NULL;
415     const BIGNUM *order = NULL, *cofactor = NULL;
416     const unsigned char *seed;
417     size_t seed_len = 0;
418
419     ctx = BN_CTX_new_ex(libctx);
420     if (ctx == NULL)
421         return 0;
422     BN_CTX_start(ctx);
423
424     tmp_nid = EC_GROUP_get_field_type(group);
425     order = EC_GROUP_get0_order(group);
426     if (order == NULL)
427         goto err;
428
429     seed = EC_GROUP_get0_seed(group);
430     if (seed != NULL)
431         seed_len = EC_GROUP_get_seed_len(group);
432     cofactor = EC_GROUP_get0_cofactor(group);
433
434     /* print the 'short name' of the field type */
435     if (BIO_printf(out, "Field Type: %s\n", OBJ_nid2sn(tmp_nid)) <= 0
436         || !ec_param_explicit_curve_to_text(out, group, ctx)
437         || !ec_param_explicit_gen_to_text(out, group, ctx)
438         || !print_labeled_bignum(out, "Order: ", order)
439         || (cofactor != NULL
440             && !print_labeled_bignum(out, "Cofactor: ", cofactor))
441         || (seed != NULL
442             && !print_labeled_buf(out, "Seed:", seed, seed_len)))
443         goto err;
444     ret = 1;
445 err:
446     BN_CTX_end(ctx);
447     BN_CTX_free(ctx);
448     return ret;
449 }
450
451 static int ec_param_to_text(BIO *out, const EC_GROUP *group,
452                             OSSL_LIB_CTX *libctx)
453 {
454     if (EC_GROUP_get_asn1_flag(group) & OPENSSL_EC_NAMED_CURVE) {
455         const char *curve_name;
456         int curve_nid = EC_GROUP_get_curve_name(group);
457
458         /* Explicit parameters */
459         if (curve_nid == NID_undef)
460             return 0;
461
462         if (BIO_printf(out, "%s: %s\n", "ASN1 OID", OBJ_nid2sn(curve_nid)) <= 0)
463             return 0;
464
465         curve_name = EC_curve_nid2nist(curve_nid);
466         return (curve_name == NULL
467                 || BIO_printf(out, "%s: %s\n", "NIST CURVE", curve_name) > 0);
468     } else {
469         return ec_param_explicit_to_text(out, group, libctx);
470     }
471 }
472
473 static int ec_to_text(BIO *out, const void *key, int selection)
474 {
475     const EC_KEY *ec = key;
476     const char *type_label = NULL;
477     unsigned char *priv = NULL, *pub = NULL;
478     size_t priv_len = 0, pub_len = 0;
479     const EC_GROUP *group;
480     int ret = 0;
481
482     if (out == NULL || ec == NULL) {
483         ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_NULL_PARAMETER);
484         return 0;
485     }
486
487     if ((group = EC_KEY_get0_group(ec)) == NULL) {
488         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY);
489         return 0;
490     }
491
492     if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0)
493         type_label = "Private-Key";
494     else if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0)
495         type_label = "Public-Key";
496     else if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0)
497         type_label = "EC-Parameters";
498
499     if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) {
500         const BIGNUM *priv_key = EC_KEY_get0_private_key(ec);
501
502         if (priv_key == NULL) {
503             ERR_raise(ERR_LIB_PROV, PROV_R_NOT_A_PRIVATE_KEY);
504             goto err;
505         }
506         priv_len = EC_KEY_priv2buf(ec, &priv);
507         if (priv_len == 0)
508             goto err;
509     }
510     if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) {
511         const EC_POINT *pub_pt = EC_KEY_get0_public_key(ec);
512
513         if (pub_pt == NULL) {
514             ERR_raise(ERR_LIB_PROV, PROV_R_NOT_A_PUBLIC_KEY);
515             goto err;
516         }
517
518         pub_len = EC_KEY_key2buf(ec, EC_KEY_get_conv_form(ec), &pub, NULL);
519         if (pub_len == 0)
520             goto err;
521     }
522
523     if (BIO_printf(out, "%s: (%d bit)\n", type_label,
524                    EC_GROUP_order_bits(group)) <= 0)
525         goto err;
526     if (priv != NULL
527         && !print_labeled_buf(out, "priv:", priv, priv_len))
528         goto err;
529     if (pub != NULL
530         && !print_labeled_buf(out, "pub:", pub, pub_len))
531         goto err;
532     if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0)
533         ret = ec_param_to_text(out, group, ec_key_get_libctx(ec));
534 err:
535     OPENSSL_clear_free(priv, priv_len);
536     OPENSSL_free(pub);
537     return ret;
538 }
539
540 # define ec_input_type          "EC"
541 #endif
542
543 /* ---------------------------------------------------------------------- */
544
545 #ifndef OPENSSL_NO_EC
546 static int ecx_to_text(BIO *out, const void *key, int selection)
547 {
548     const ECX_KEY *ecx = key;
549     const char *type_label = NULL;
550
551     if (out == NULL || ecx == NULL) {
552         ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_NULL_PARAMETER);
553         return 0;
554     }
555
556     if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) {
557         if (ecx->privkey == NULL) {
558             ERR_raise(ERR_LIB_PROV, PROV_R_NOT_A_PRIVATE_KEY);
559             return 0;
560         }
561
562         switch (ecx->type) {
563         case ECX_KEY_TYPE_X25519:
564             type_label = "X25519 Private-Key";
565             break;
566         case ECX_KEY_TYPE_X448:
567             type_label = "X448 Private-Key";
568             break;
569         case ECX_KEY_TYPE_ED25519:
570             type_label = "ED25519 Private-Key";
571             break;
572         case ECX_KEY_TYPE_ED448:
573             type_label = "ED448 Private-Key";
574             break;
575         }
576     } else if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) {
577         /* ecx->pubkey is an array, not a pointer... */
578         if (!ecx->haspubkey) {
579             ERR_raise(ERR_LIB_PROV, PROV_R_NOT_A_PUBLIC_KEY);
580             return 0;
581         }
582
583         switch (ecx->type) {
584         case ECX_KEY_TYPE_X25519:
585             type_label = "X25519 Public-Key";
586             break;
587         case ECX_KEY_TYPE_X448:
588             type_label = "X448 Public-Key";
589             break;
590         case ECX_KEY_TYPE_ED25519:
591             type_label = "ED25519 Public-Key";
592             break;
593         case ECX_KEY_TYPE_ED448:
594             type_label = "ED448 Public-Key";
595             break;
596         }
597     }
598
599     if (BIO_printf(out, "%s:\n", type_label) <= 0)
600         return 0;
601     if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0
602         && !print_labeled_buf(out, "priv:", ecx->privkey, ecx->keylen))
603         return 0;
604     if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0
605         && !print_labeled_buf(out, "pub:", ecx->pubkey, ecx->keylen))
606         return 0;
607
608     return 1;
609 }
610
611 # define ed25519_input_type     "ED25519"
612 # define ed448_input_type       "ED448"
613 # define x25519_input_type      "X25519"
614 # define x448_input_type        "X448"
615 #endif
616
617 /* ---------------------------------------------------------------------- */
618
619 static int rsa_to_text(BIO *out, const void *key, int selection)
620 {
621     const RSA *rsa = key;
622     const char *type_label = "RSA key";
623     const char *modulus_label;
624     const char *exponent_label;
625     const BIGNUM *rsa_d = NULL, *rsa_n = NULL, *rsa_e = NULL;
626     STACK_OF(BIGNUM_const) *factors = NULL;
627     STACK_OF(BIGNUM_const) *exps = NULL;
628     STACK_OF(BIGNUM_const) *coeffs = NULL;
629     int primes;
630     const RSA_PSS_PARAMS_30 *pss_params = ossl_rsa_get0_pss_params_30((RSA *)rsa);
631     int ret = 0;
632
633     if (out == NULL || rsa == NULL) {
634         ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_NULL_PARAMETER);
635         goto err;
636     }
637
638     factors = sk_BIGNUM_const_new_null();
639     exps = sk_BIGNUM_const_new_null();
640     coeffs = sk_BIGNUM_const_new_null();
641
642     if (factors == NULL || exps == NULL || coeffs == NULL) {
643         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
644         goto err;
645     }
646
647     if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) {
648         type_label = "Private-Key";
649         modulus_label = "modulus:";
650         exponent_label = "publicExponent:";
651     } else if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) {
652         type_label = "Public-Key";
653         modulus_label = "Modulus:";
654         exponent_label = "Exponent:";
655     }
656
657     RSA_get0_key(rsa, &rsa_n, &rsa_e, &rsa_d);
658     ossl_rsa_get0_all_params((RSA *)rsa, factors, exps, coeffs);
659     primes = sk_BIGNUM_const_num(factors);
660
661     if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) {
662         if (BIO_printf(out, "%s: (%d bit, %d primes)\n",
663                        type_label, BN_num_bits(rsa_n), primes) <= 0)
664             goto err;
665     } else {
666         if (BIO_printf(out, "%s: (%d bit)\n",
667                        type_label, BN_num_bits(rsa_n)) <= 0)
668             goto err;
669     }
670
671     if (!print_labeled_bignum(out, modulus_label, rsa_n))
672         goto err;
673     if (!print_labeled_bignum(out, exponent_label, rsa_e))
674         goto err;
675     if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) {
676         int i;
677
678         if (!print_labeled_bignum(out, "privateExponent:", rsa_d))
679             goto err;
680         if (!print_labeled_bignum(out, "prime1:",
681                                   sk_BIGNUM_const_value(factors, 0)))
682             goto err;
683         if (!print_labeled_bignum(out, "prime2:",
684                                   sk_BIGNUM_const_value(factors, 1)))
685             goto err;
686         if (!print_labeled_bignum(out, "exponent1:",
687                                   sk_BIGNUM_const_value(exps, 0)))
688             goto err;
689         if (!print_labeled_bignum(out, "exponent2:",
690                                   sk_BIGNUM_const_value(exps, 1)))
691             goto err;
692         if (!print_labeled_bignum(out, "coefficient:",
693                                   sk_BIGNUM_const_value(coeffs, 0)))
694             goto err;
695         for (i = 2; i < sk_BIGNUM_const_num(factors); i++) {
696             if (BIO_printf(out, "prime%d:", i + 1) <= 0)
697                 goto err;
698             if (!print_labeled_bignum(out, NULL,
699                                       sk_BIGNUM_const_value(factors, i)))
700                 goto err;
701             if (BIO_printf(out, "exponent%d:", i + 1) <= 0)
702                 goto err;
703             if (!print_labeled_bignum(out, NULL,
704                                       sk_BIGNUM_const_value(exps, i)))
705                 goto err;
706             if (BIO_printf(out, "coefficient%d:", i + 1) <= 0)
707                 goto err;
708             if (!print_labeled_bignum(out, NULL,
709                                       sk_BIGNUM_const_value(coeffs, i - 1)))
710                 goto err;
711         }
712     }
713
714     if ((selection & OSSL_KEYMGMT_SELECT_OTHER_PARAMETERS) != 0) {
715         switch (RSA_test_flags(rsa, RSA_FLAG_TYPE_MASK)) {
716         case RSA_FLAG_TYPE_RSA:
717             if (!ossl_rsa_pss_params_30_is_unrestricted(pss_params)) {
718                 if (BIO_printf(out, "(INVALID PSS PARAMETERS)\n") <= 0)
719                     goto err;
720             }
721             break;
722         case RSA_FLAG_TYPE_RSASSAPSS:
723             if (ossl_rsa_pss_params_30_is_unrestricted(pss_params)) {
724                 if (BIO_printf(out, "No PSS parameter restrictions\n") <= 0)
725                     goto err;
726             } else {
727                 int hashalg_nid = ossl_rsa_pss_params_30_hashalg(pss_params);
728                 int maskgenalg_nid =
729                     ossl_rsa_pss_params_30_maskgenalg(pss_params);
730                 int maskgenhashalg_nid =
731                     ossl_rsa_pss_params_30_maskgenhashalg(pss_params);
732                 int saltlen = ossl_rsa_pss_params_30_saltlen(pss_params);
733                 int trailerfield =
734                     ossl_rsa_pss_params_30_trailerfield(pss_params);
735
736                 if (BIO_printf(out, "PSS parameter restrictions:\n") <= 0)
737                     goto err;
738                 if (BIO_printf(out, "  Hash Algorithm: %s%s\n",
739                                ossl_rsa_oaeppss_nid2name(hashalg_nid),
740                                (hashalg_nid == NID_sha1
741                                 ? " (default)" : "")) <= 0)
742                     goto err;
743                 if (BIO_printf(out, "  Mask Algorithm: %s with %s%s\n",
744                                ossl_rsa_mgf_nid2name(maskgenalg_nid),
745                                ossl_rsa_oaeppss_nid2name(maskgenhashalg_nid),
746                                (maskgenalg_nid == NID_mgf1
747                                 && maskgenhashalg_nid == NID_sha1
748                                 ? " (default)" : "")) <= 0)
749                     goto err;
750                 if (BIO_printf(out, "  Minimum Salt Length: %d%s\n",
751                                saltlen,
752                                (saltlen == 20 ? " (default)" : "")) <= 0)
753                     goto err;
754                 /*
755                  * TODO(3.0) Should we show the ASN.1 trailerField value, or
756                  * the actual trailerfield byte (i.e. 0xBC for 1)?
757                  * crypto/rsa/rsa_ameth.c isn't very clear on that, as it
758                  * does display 0xBC when the default applies, but the ASN.1
759                  * trailerField value otherwise...
760                  */
761                 if (BIO_printf(out, "  Trailer Field: 0x%x%s\n",
762                                trailerfield,
763                                (trailerfield == 1 ? " (default)" : "")) <= 0)
764                     goto err;
765             }
766             break;
767         }
768     }
769
770     ret = 1;
771  err:
772     sk_BIGNUM_const_free(factors);
773     sk_BIGNUM_const_free(exps);
774     sk_BIGNUM_const_free(coeffs);
775     return ret;
776 }
777
778 #define rsa_input_type          "RSA"
779 #define rsapss_input_type       "RSA-PSS"
780
781 /* ---------------------------------------------------------------------- */
782
783 static void *key2text_newctx(void *provctx)
784 {
785     return provctx;
786 }
787
788 static void key2text_freectx(ossl_unused void *vctx)
789 {
790 }
791
792 static const OSSL_PARAM *key2text_gettable_params(void *provctx)
793 {
794     static const OSSL_PARAM gettables[] = {
795         { OSSL_ENCODER_PARAM_OUTPUT_TYPE, OSSL_PARAM_UTF8_PTR, NULL, 0, 0 },
796         OSSL_PARAM_END,
797     };
798
799     return gettables;
800 }
801
802 static int key2text_get_params(OSSL_PARAM params[], const char *input_type)
803 {
804     OSSL_PARAM *p;
805
806     p = OSSL_PARAM_locate(params, OSSL_ENCODER_PARAM_INPUT_TYPE);
807     if (p != NULL && !OSSL_PARAM_set_utf8_ptr(p, input_type))
808         return 0;
809
810     p = OSSL_PARAM_locate(params, OSSL_ENCODER_PARAM_OUTPUT_TYPE);
811     if (p != NULL && !OSSL_PARAM_set_utf8_ptr(p, "TEXT"))
812         return 0;
813
814     return 1;
815 }
816
817 static int key2text_encode(void *vctx, const void *key, int selection,
818                            OSSL_CORE_BIO *cout,
819                            int (*key2text)(BIO *out, const void *key,
820                                            int selection),
821                            OSSL_PASSPHRASE_CALLBACK *cb, void *cbarg)
822 {
823     BIO *out = bio_new_from_core_bio(vctx, cout);
824     int ret;
825
826     if (out == NULL)
827         return 0;
828
829     ret = key2text(out, key, selection);
830     BIO_free(out);
831
832     return ret;
833 }
834
835 #define MAKE_TEXT_ENCODER(impl, type)                                   \
836     static OSSL_FUNC_encoder_get_params_fn                              \
837     impl##2text_get_params;                                             \
838     static OSSL_FUNC_encoder_import_object_fn                           \
839     impl##2text_import_object;                                          \
840     static OSSL_FUNC_encoder_free_object_fn                             \
841     impl##2text_free_object;                                            \
842     static OSSL_FUNC_encoder_encode_fn impl##2text_encode;              \
843                                                                         \
844     static int impl##2text_get_params(OSSL_PARAM params[])              \
845     {                                                                   \
846         return key2text_get_params(params, impl##_input_type);          \
847     }                                                                   \
848     static void *impl##2text_import_object(void *ctx, int selection,    \
849                                            const OSSL_PARAM params[])   \
850     {                                                                   \
851         return ossl_prov_import_key(ossl_##impl##_keymgmt_functions,    \
852                                     ctx, selection, params);            \
853     }                                                                   \
854     static void impl##2text_free_object(void *key)                      \
855     {                                                                   \
856         ossl_prov_free_key(ossl_##impl##_keymgmt_functions, key);       \
857     }                                                                   \
858     static int impl##2text_encode(void *vctx, OSSL_CORE_BIO *cout,      \
859                                   const void *key,                      \
860                                   const OSSL_PARAM key_abstract[],      \
861                                   int selection,                        \
862                                   OSSL_PASSPHRASE_CALLBACK *cb,         \
863                                   void *cbarg)                          \
864     {                                                                   \
865         /* We don't deal with abstract objects */                       \
866         if (key_abstract != NULL) {                                     \
867             ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_INVALID_ARGUMENT);     \
868             return 0;                                                   \
869         }                                                               \
870         return key2text_encode(vctx, key, selection, cout,              \
871                                type##_to_text, cb, cbarg);              \
872     }                                                                   \
873     const OSSL_DISPATCH ossl_##impl##_to_text_encoder_functions[] = {   \
874         { OSSL_FUNC_ENCODER_NEWCTX,                                     \
875           (void (*)(void))key2text_newctx },                            \
876         { OSSL_FUNC_ENCODER_FREECTX,                                    \
877           (void (*)(void))key2text_freectx },                           \
878         { OSSL_FUNC_ENCODER_GETTABLE_PARAMS,                            \
879           (void (*)(void))key2text_gettable_params },                   \
880         { OSSL_FUNC_ENCODER_GET_PARAMS,                                 \
881           (void (*)(void))impl##2text_get_params },                     \
882         { OSSL_FUNC_ENCODER_IMPORT_OBJECT,                              \
883           (void (*)(void))impl##2text_import_object },                  \
884         { OSSL_FUNC_ENCODER_FREE_OBJECT,                                \
885           (void (*)(void))impl##2text_free_object },                    \
886         { OSSL_FUNC_ENCODER_ENCODE,                                     \
887           (void (*)(void))impl##2text_encode },                         \
888         { 0, NULL }                                                     \
889     }
890
891 #ifndef OPENSSL_NO_DH
892 MAKE_TEXT_ENCODER(dh, dh);
893 MAKE_TEXT_ENCODER(dhx, dh);
894 #endif
895 #ifndef OPENSSL_NO_DSA
896 MAKE_TEXT_ENCODER(dsa, dsa);
897 #endif
898 #ifndef OPENSSL_NO_EC
899 MAKE_TEXT_ENCODER(ec, ec);
900 MAKE_TEXT_ENCODER(ed25519, ecx);
901 MAKE_TEXT_ENCODER(ed448, ecx);
902 MAKE_TEXT_ENCODER(x25519, ecx);
903 MAKE_TEXT_ENCODER(x448, ecx);
904 #endif
905 MAKE_TEXT_ENCODER(rsa, rsa);
906 MAKE_TEXT_ENCODER(rsapss, rsa);