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