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