8f868249ee81194420cc43b41d1c12f725386a75
[openssl.git] / providers / implementations / encode_decode / encode_key2any.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 <openssl/core.h>
16 #include <openssl/core_dispatch.h>
17 #include <openssl/core_names.h>
18 #include <openssl/crypto.h>
19 #include <openssl/params.h>
20 #include <openssl/asn1.h>
21 #include <openssl/err.h>
22 #include <openssl/pem.h>
23 #include <openssl/x509.h>
24 #include <openssl/pkcs12.h>      /* PKCS8_encrypt() */
25 #include <openssl/dh.h>
26 #include <openssl/dsa.h>
27 #include <openssl/ec.h>
28 #include <openssl/proverr.h>
29 #include "internal/passphrase.h"
30 #include "internal/cryptlib.h"
31 #include "crypto/ecx.h"
32 #include "crypto/rsa.h"
33 #include "prov/implementations.h"
34 #include "prov/bio.h"
35 #include "prov/provider_ctx.h"
36 #include "prov/der_rsa.h"
37 #include "endecoder_local.h"
38
39 #if defined(OPENSSL_NO_DH) && defined(OPENSSL_NO_DSA) && defined(OPENSSL_NO_EC)
40 # define OPENSSL_NO_KEYPARAMS
41 #endif
42
43 struct key2any_ctx_st {
44     PROV_CTX *provctx;
45
46     /* Set to 1 if intending to encrypt/decrypt, otherwise 0 */
47     int cipher_intent;
48
49     EVP_CIPHER *cipher;
50
51     struct ossl_passphrase_data_st pwdata;
52 };
53
54 typedef int check_key_type_fn(const void *key, int nid);
55 typedef int key_to_paramstring_fn(const void *key, int nid,
56                                   void **str, int *strtype);
57 typedef int key_to_der_fn(BIO *out, const void *key,
58                           int key_nid, const char *pemname,
59                           key_to_paramstring_fn *p2s, i2d_of_void *k2d,
60                           struct key2any_ctx_st *ctx);
61 typedef int write_bio_of_void_fn(BIO *bp, const void *x);
62
63 static PKCS8_PRIV_KEY_INFO *key_to_p8info(const void *key, int key_nid,
64                                           void *params, int params_type,
65                                           i2d_of_void *k2d)
66 {
67     /* der, derlen store the key DER output and its length */
68     unsigned char *der = NULL;
69     int derlen;
70     /* The final PKCS#8 info */
71     PKCS8_PRIV_KEY_INFO *p8info = NULL;
72
73
74     if ((p8info = PKCS8_PRIV_KEY_INFO_new()) == NULL
75         || (derlen = k2d(key, &der)) <= 0
76         || !PKCS8_pkey_set0(p8info, OBJ_nid2obj(key_nid), 0,
77                             params_type, params, der, derlen)) {
78         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
79         PKCS8_PRIV_KEY_INFO_free(p8info);
80         OPENSSL_free(der);
81         p8info = NULL;
82     }
83
84     return p8info;
85 }
86
87 static X509_SIG *p8info_to_encp8(PKCS8_PRIV_KEY_INFO *p8info,
88                                  struct key2any_ctx_st *ctx)
89 {
90     X509_SIG *p8 = NULL;
91     char kstr[PEM_BUFSIZE];
92     size_t klen = 0;
93
94     if (ctx->cipher == NULL)
95         return NULL;
96
97     if (!ossl_pw_get_passphrase(kstr, sizeof(kstr), &klen, NULL, 1,
98                                 &ctx->pwdata)) {
99         ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_GET_PASSPHRASE);
100         return NULL;
101     }
102     /* First argument == -1 means "standard" */
103     p8 = PKCS8_encrypt(-1, ctx->cipher, kstr, klen, NULL, 0, 0, p8info);
104     OPENSSL_cleanse(kstr, klen);
105     return p8;
106 }
107
108 static X509_SIG *key_to_encp8(const void *key, int key_nid,
109                               void *params, int params_type,
110                               i2d_of_void *k2d, struct key2any_ctx_st *ctx)
111 {
112     PKCS8_PRIV_KEY_INFO *p8info =
113         key_to_p8info(key, key_nid, params, params_type, k2d);
114     X509_SIG *p8 = p8info_to_encp8(p8info, ctx);
115
116     PKCS8_PRIV_KEY_INFO_free(p8info);
117     return p8;
118 }
119
120 static X509_PUBKEY *key_to_pubkey(const void *key, int key_nid,
121                                   void *params, int params_type,
122                                   i2d_of_void k2d)
123 {
124     /* der, derlen store the key DER output and its length */
125     unsigned char *der = NULL;
126     int derlen;
127     /* The final X509_PUBKEY */
128     X509_PUBKEY *xpk = NULL;
129
130
131     if ((xpk = X509_PUBKEY_new()) == NULL
132         || (derlen = k2d(key, &der)) <= 0
133         || !X509_PUBKEY_set0_param(xpk, OBJ_nid2obj(key_nid),
134                                    params_type, params, der, derlen)) {
135         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
136         X509_PUBKEY_free(xpk);
137         OPENSSL_free(der);
138         xpk = NULL;
139     }
140
141     return xpk;
142 }
143
144 /*
145  * key_to_pkcs8_* produce encoded output with the key data pkcs8
146  * in a structure.  For private keys, that structure is PKCS#8, and for
147  * public keys, it's X.509 SubjectPublicKeyInfo.  Parameters don't have
148  * any defined envelopment of that kind.
149  */
150 static int key_to_pkcs8_der_priv_bio(BIO *out, const void *key,
151                                      int key_nid,
152                                      ossl_unused const char *pemname,
153                                      key_to_paramstring_fn *p2s,
154                                      i2d_of_void *k2d,
155                                      struct key2any_ctx_st *ctx)
156 {
157     int ret = 0;
158     void *str = NULL;
159     int strtype = V_ASN1_UNDEF;
160
161     if (p2s != NULL && !p2s(key, key_nid, &str, &strtype))
162         return 0;
163
164     if (ctx->cipher_intent) {
165         X509_SIG *p8 = key_to_encp8(key, key_nid, str, strtype, k2d, ctx);
166
167         if (p8 != NULL)
168             ret = i2d_PKCS8_bio(out, p8);
169
170         X509_SIG_free(p8);
171     } else {
172         PKCS8_PRIV_KEY_INFO *p8info =
173             key_to_p8info(key, key_nid, str, strtype, k2d);
174
175         if (p8info != NULL)
176             ret = i2d_PKCS8_PRIV_KEY_INFO_bio(out, p8info);
177
178         PKCS8_PRIV_KEY_INFO_free(p8info);
179     }
180
181     return ret;
182 }
183
184 static int key_to_pkcs8_pem_priv_bio(BIO *out, const void *key,
185                                      int key_nid,
186                                      ossl_unused const char *pemname,
187                                      key_to_paramstring_fn *p2s,
188                                      i2d_of_void *k2d,
189                                      struct key2any_ctx_st *ctx)
190 {
191     int ret = 0;
192     void *str = NULL;
193     int strtype = V_ASN1_UNDEF;
194
195     if (p2s != NULL && !p2s(key, key_nid, &str, &strtype))
196         return 0;
197
198     if (ctx->cipher_intent) {
199         X509_SIG *p8 = key_to_encp8(key, key_nid, str, strtype, k2d, ctx);
200
201         if (p8 != NULL)
202             ret = PEM_write_bio_PKCS8(out, p8);
203
204         X509_SIG_free(p8);
205     } else {
206         PKCS8_PRIV_KEY_INFO *p8info =
207             key_to_p8info(key, key_nid, str, strtype, k2d);
208
209         if (p8info != NULL)
210             ret = PEM_write_bio_PKCS8_PRIV_KEY_INFO(out, p8info);
211
212         PKCS8_PRIV_KEY_INFO_free(p8info);
213     }
214
215     return ret;
216 }
217
218 static int key_to_spki_der_pub_bio(BIO *out, const void *key,
219                                    int key_nid,
220                                    ossl_unused const char *pemname,
221                                    key_to_paramstring_fn *p2s,
222                                    i2d_of_void *k2d,
223                                    struct key2any_ctx_st *ctx)
224 {
225     int ret = 0;
226     void *str = NULL;
227     int strtype = V_ASN1_UNDEF;
228     X509_PUBKEY *xpk = NULL;
229
230     if (p2s != NULL && !p2s(key, key_nid, &str, &strtype))
231         return 0;
232
233     xpk = key_to_pubkey(key, key_nid, str, strtype, k2d);
234
235     if (xpk != NULL)
236         ret = i2d_X509_PUBKEY_bio(out, xpk);
237
238     /* Also frees |str| */
239     X509_PUBKEY_free(xpk);
240     return ret;
241 }
242
243 static int key_to_spki_pem_pub_bio(BIO *out, const void *key,
244                                    int key_nid,
245                                    ossl_unused const char *pemname,
246                                    key_to_paramstring_fn *p2s,
247                                    i2d_of_void *k2d,
248                                    struct key2any_ctx_st *ctx)
249 {
250     int ret = 0;
251     void *str = NULL;
252     int strtype = V_ASN1_UNDEF;
253     X509_PUBKEY *xpk = NULL;
254
255     if (p2s != NULL && !p2s(key, key_nid, &str, &strtype))
256         return 0;
257
258     xpk = key_to_pubkey(key, key_nid, str, strtype, k2d);
259
260     if (xpk != NULL)
261         ret = PEM_write_bio_X509_PUBKEY(out, xpk);
262
263     /* Also frees |str| */
264     X509_PUBKEY_free(xpk);
265     return ret;
266 }
267
268 /*
269  * key_to_type_specific_* produce encoded output with type specific key data,
270  * no envelopment; the same kind of output as the type specific i2d_ and
271  * PEM_write_ functions, which is often a simple SEQUENCE of INTEGER.
272  *
273  * OpenSSL tries to discourage production of new keys in this form, because
274  * of the ambiguity when trying to recognise them, but can't deny that PKCS#1
275  * et al still are live standards.
276  *
277  * Note that these functions completely ignore p2s, and rather rely entirely
278  * on k2d to do the complete work.
279  */
280 static int key_to_type_specific_der_bio(BIO *out, const void *key,
281                                         int key_nid,
282                                         ossl_unused const char *pemname,
283                                         key_to_paramstring_fn *p2s,
284                                         i2d_of_void *k2d,
285                                         struct key2any_ctx_st *ctx)
286 {
287     unsigned char *der = NULL;
288     int derlen;
289     int ret;
290
291     if ((derlen = k2d(key, &der)) <= 0) {
292         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
293         return 0;
294     }
295
296     ret = BIO_write(out, der, derlen);
297     OPENSSL_free(der);
298     return ret > 0;
299 }
300 #define key_to_type_specific_der_priv_bio key_to_type_specific_der_bio
301 #define key_to_type_specific_der_pub_bio key_to_type_specific_der_bio
302 #define key_to_type_specific_der_param_bio key_to_type_specific_der_bio
303
304 static int key_to_type_specific_pem_bio_cb(BIO *out, const void *key,
305                                            int key_nid, const char *pemname,
306                                            key_to_paramstring_fn *p2s,
307                                            i2d_of_void *k2d,
308                                            struct key2any_ctx_st *ctx,
309                                            pem_password_cb *cb, void *cbarg)
310 {
311     return
312         PEM_ASN1_write_bio(k2d, pemname, out, key, ctx->cipher,
313                            NULL, 0, ossl_pw_pem_password, &ctx->pwdata) > 0;
314 }
315
316 static int key_to_type_specific_pem_priv_bio(BIO *out, const void *key,
317                                              int key_nid, const char *pemname,
318                                              key_to_paramstring_fn *p2s,
319                                              i2d_of_void *k2d,
320                                              struct key2any_ctx_st *ctx)
321 {
322     return key_to_type_specific_pem_bio_cb(out, key, key_nid, pemname,
323                                            p2s, k2d, ctx,
324                                            ossl_pw_pem_password, &ctx->pwdata);
325 }
326
327 static int key_to_type_specific_pem_pub_bio(BIO *out, const void *key,
328                                             int key_nid, const char *pemname,
329                                             key_to_paramstring_fn *p2s,
330                                             i2d_of_void *k2d,
331                                             struct key2any_ctx_st *ctx)
332 {
333     return key_to_type_specific_pem_bio_cb(out, key, key_nid, pemname,
334                                            p2s, k2d, ctx, NULL, NULL);
335 }
336
337 #ifndef OPENSSL_NO_KEYPARAMS
338 static int key_to_type_specific_pem_param_bio(BIO *out, const void *key,
339                                               int key_nid, const char *pemname,
340                                               key_to_paramstring_fn *p2s,
341                                               i2d_of_void *k2d,
342                                               struct key2any_ctx_st *ctx)
343 {
344     return key_to_type_specific_pem_bio_cb(out, key, key_nid, pemname,
345                                            p2s, k2d, ctx, NULL, NULL);
346 }
347 #endif
348
349 #define der_output_type         "DER"
350 #define pem_output_type         "PEM"
351
352 /* ---------------------------------------------------------------------- */
353
354 #ifndef OPENSSL_NO_DH
355 static int prepare_dh_params(const void *dh, int nid,
356                              void **pstr, int *pstrtype)
357 {
358     ASN1_STRING *params = ASN1_STRING_new();
359
360     if (params == NULL) {
361         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
362         return 0;
363     }
364
365     if (nid == EVP_PKEY_DHX)
366         params->length = i2d_DHxparams(dh, &params->data);
367     else
368         params->length = i2d_DHparams(dh, &params->data);
369
370     if (params->length <= 0) {
371         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
372         ASN1_STRING_free(params);
373         return 0;
374     }
375     params->type = V_ASN1_SEQUENCE;
376
377     *pstr = params;
378     *pstrtype = V_ASN1_SEQUENCE;
379     return 1;
380 }
381
382 static int dh_spki_pub_to_der(const void *dh, unsigned char **pder)
383 {
384     const BIGNUM *bn = NULL;
385     ASN1_INTEGER *pub_key = NULL;
386     int ret;
387
388     if ((bn = DH_get0_pub_key(dh)) == NULL) {
389         ERR_raise(ERR_LIB_PROV, PROV_R_NOT_A_PUBLIC_KEY);
390         return 0;
391     }
392     if ((pub_key = BN_to_ASN1_INTEGER(bn, NULL)) == NULL) {
393         ERR_raise(ERR_LIB_PROV, PROV_R_BN_ERROR);
394         return 0;
395     }
396
397     ret = i2d_ASN1_INTEGER(pub_key, pder);
398
399     ASN1_STRING_clear_free(pub_key);
400     return ret;
401 }
402
403 static int dh_pkcs8_priv_to_der(const void *dh, unsigned char **pder)
404 {
405     const BIGNUM *bn = NULL;
406     ASN1_INTEGER *priv_key = NULL;
407     int ret;
408
409     if ((bn = DH_get0_priv_key(dh)) == NULL) {
410         ERR_raise(ERR_LIB_PROV, PROV_R_NOT_A_PRIVATE_KEY);
411         return 0;
412     }
413     if ((priv_key = BN_to_ASN1_INTEGER(bn, NULL)) == NULL) {
414         ERR_raise(ERR_LIB_PROV, PROV_R_BN_ERROR);
415         return 0;
416     }
417
418     ret = i2d_ASN1_INTEGER(priv_key, pder);
419
420     ASN1_STRING_clear_free(priv_key);
421     return ret;
422 }
423
424 static int dh_type_specific_params_to_der(const void *dh, unsigned char **pder)
425 {
426     if (DH_test_flags(dh, DH_FLAG_TYPE_DHX))
427         return i2d_DHxparams(dh, pder);
428     return i2d_DHparams(dh, pder);
429 }
430
431 /*
432  * DH doesn't have i2d_DHPrivateKey or i2d_DHPublicKey, so we can't make
433  * corresponding functions here.
434  */
435 # define dh_type_specific_priv_to_der   NULL
436 # define dh_type_specific_pub_to_der    NULL
437
438 static int dh_check_key_type(const void *dh, int expected_type)
439 {
440     int type =
441         DH_test_flags(dh, DH_FLAG_TYPE_DHX) ? EVP_PKEY_DHX : EVP_PKEY_DH;
442
443     return type == expected_type;
444 }
445
446 # define dh_evp_type            EVP_PKEY_DH
447 # define dhx_evp_type           EVP_PKEY_DHX
448 # define dh_input_type          "DH"
449 # define dhx_input_type         "DHX"
450 # define dh_pem_type            "DH"
451 # define dhx_pem_type           "X9.42 DH"
452 #endif
453
454 /* ---------------------------------------------------------------------- */
455
456 #ifndef OPENSSL_NO_DSA
457 static int prepare_some_dsa_params(const void *dsa, int nid,
458                                    void **pstr, int *pstrtype)
459 {
460     ASN1_STRING *params = ASN1_STRING_new();
461
462     if (params == NULL) {
463         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
464         return 0;
465     }
466
467     params->length = i2d_DSAparams(dsa, &params->data);
468
469     if (params->length <= 0) {
470         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
471         ASN1_STRING_free(params);
472         return 0;
473     }
474
475     *pstrtype = V_ASN1_SEQUENCE;
476     *pstr = params;
477     return 1;
478 }
479
480 static int prepare_all_dsa_params(const void *dsa, int nid,
481                                   void **pstr, int *pstrtype)
482 {
483     const BIGNUM *p = DSA_get0_p(dsa);
484     const BIGNUM *q = DSA_get0_q(dsa);
485     const BIGNUM *g = DSA_get0_g(dsa);
486
487     if (p != NULL && q != NULL && g != NULL)
488         return prepare_some_dsa_params(dsa, nid, pstr, pstrtype);
489
490     *pstr = NULL;
491     *pstrtype = V_ASN1_UNDEF;
492     return 1;
493 }
494
495 static int prepare_dsa_params(const void *dsa, int nid,
496                               void **pstr, int *pstrtype)
497 {
498     /*
499      * TODO(v3.0) implement setting save_parameters, see dsa_pub_encode()
500      * in crypto/dsa/dsa_ameth.c
501      */
502     int save_parameters = 1;
503
504     return save_parameters
505         ?  prepare_all_dsa_params(dsa, nid, pstr, pstrtype)
506         :  prepare_some_dsa_params(dsa, nid, pstr, pstrtype);
507 }
508
509 static int dsa_spki_pub_to_der(const void *dsa, unsigned char **pder)
510 {
511     const BIGNUM *bn = NULL;
512     ASN1_INTEGER *pub_key = NULL;
513     int ret;
514
515     if ((bn = DSA_get0_pub_key(dsa)) == NULL) {
516         ERR_raise(ERR_LIB_PROV, PROV_R_NOT_A_PUBLIC_KEY);
517         return 0;
518     }
519     if ((pub_key = BN_to_ASN1_INTEGER(bn, NULL)) == NULL) {
520         ERR_raise(ERR_LIB_PROV, PROV_R_BN_ERROR);
521         return 0;
522     }
523
524     ret = i2d_ASN1_INTEGER(pub_key, pder);
525
526     ASN1_STRING_clear_free(pub_key);
527     return ret;
528 }
529
530 static int dsa_pkcs8_priv_to_der(const void *dsa, unsigned char **pder)
531 {
532     const BIGNUM *bn = NULL;
533     ASN1_INTEGER *priv_key = NULL;
534     int ret;
535
536     if ((bn = DSA_get0_priv_key(dsa)) == NULL) {
537         ERR_raise(ERR_LIB_PROV, PROV_R_NOT_A_PRIVATE_KEY);
538         return 0;
539     }
540     if ((priv_key = BN_to_ASN1_INTEGER(bn, NULL)) == NULL) {
541         ERR_raise(ERR_LIB_PROV, PROV_R_BN_ERROR);
542         return 0;
543     }
544
545     ret = i2d_ASN1_INTEGER(priv_key, pder);
546
547     ASN1_STRING_clear_free(priv_key);
548     return ret;
549 }
550
551 # define dsa_type_specific_priv_to_der   (i2d_of_void *)i2d_DSAPrivateKey
552 # define dsa_type_specific_pub_to_der    (i2d_of_void *)i2d_DSAPublicKey
553 # define dsa_type_specific_params_to_der (i2d_of_void *)i2d_DSAparams
554
555 # define dsa_check_key_type     NULL
556 # define dsa_evp_type           EVP_PKEY_DSA
557 # define dsa_input_type         "DSA"
558 # define dsa_pem_type           "DSA"
559 #endif
560
561 /* ---------------------------------------------------------------------- */
562
563 #ifndef OPENSSL_NO_EC
564 static int prepare_ec_explicit_params(const void *eckey,
565                                       void **pstr, int *pstrtype)
566 {
567     ASN1_STRING *params = ASN1_STRING_new();
568
569     if (params == NULL) {
570         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
571         return 0;
572     }
573
574     params->length = i2d_ECParameters(eckey, &params->data);
575     if (params->length <= 0) {
576         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
577         ASN1_STRING_free(params);
578         return 0;
579     }
580
581     *pstrtype = V_ASN1_SEQUENCE;
582     *pstr = params;
583     return 1;
584 }
585
586 /*
587  * This implements EcpkParameters, where the CHOICE is based on whether there
588  * is a curve name (curve nid) to be found or not.  See RFC 3279 for details.
589  * TODO: shouldn't we use i2d_ECPKParameters()?
590  */
591 static int prepare_ec_params(const void *eckey, int nid,
592                              void **pstr, int *pstrtype)
593 {
594     int curve_nid;
595     const EC_GROUP *group = EC_KEY_get0_group(eckey);
596     ASN1_OBJECT *params = NULL;
597
598     if (group == NULL)
599         return 0;
600     curve_nid = EC_GROUP_get_curve_name(group);
601     if (curve_nid != NID_undef) {
602         params = OBJ_nid2obj(curve_nid);
603         if (params == NULL)
604             return 0;
605     }
606
607     if (curve_nid != NID_undef
608         && (EC_GROUP_get_asn1_flag(group) & OPENSSL_EC_NAMED_CURVE)) {
609         /* The CHOICE came to namedCurve */
610         if (OBJ_length(params) == 0) {
611             /* Some curves might not have an associated OID */
612             ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_OID);
613             ASN1_OBJECT_free(params);
614             return 0;
615         }
616         *pstr = params;
617         *pstrtype = V_ASN1_OBJECT;
618         return 1;
619     } else {
620         /* The CHOICE came to ecParameters */
621         return prepare_ec_explicit_params(eckey, pstr, pstrtype);
622     }
623 }
624
625 static int ec_spki_pub_to_der(const void *eckey, unsigned char **pder)
626 {
627     return i2o_ECPublicKey(eckey, pder);
628 }
629
630 static int ec_pkcs8_priv_to_der(const void *veckey, unsigned char **pder)
631 {
632     EC_KEY *eckey = (EC_KEY *)veckey;
633     unsigned int old_flags;
634     int ret = 0;
635
636     /*
637      * For PKCS8 the curve name appears in the PKCS8_PRIV_KEY_INFO object
638      * as the pkeyalg->parameter field. (For a named curve this is an OID)
639      * The pkey field is an octet string that holds the encoded
640      * ECPrivateKey SEQUENCE with the optional parameters field omitted.
641      * We omit this by setting the EC_PKEY_NO_PARAMETERS flag.
642      */
643     old_flags = EC_KEY_get_enc_flags(eckey); /* save old flags */
644     EC_KEY_set_enc_flags(eckey, old_flags | EC_PKEY_NO_PARAMETERS);
645     ret = i2d_ECPrivateKey(eckey, pder);
646     EC_KEY_set_enc_flags(eckey, old_flags); /* restore old flags */
647     return ret; /* return the length of the der encoded data */
648 }
649
650 # define ec_type_specific_params_to_der (i2d_of_void *)i2d_ECParameters
651 # define ec_type_specific_pub_to_der    (i2d_of_void *)i2o_ECPublicKey
652 # define ec_type_specific_priv_to_der   (i2d_of_void *)i2d_ECPrivateKey
653
654 # define ec_check_key_type      NULL
655 # define ec_evp_type            EVP_PKEY_EC
656 # define ec_input_type          "EC"
657 # define ec_pem_type            "EC"
658
659 # ifndef OPENSSL_NO_SM2
660 #  define sm2_evp_type          EVP_PKEY_SM2
661 #  define sm2_input_type        "SM2"
662 #  define sm2_pem_type          "SM2"
663 # endif
664 #endif
665
666 /* ---------------------------------------------------------------------- */
667
668 #ifndef OPENSSL_NO_EC
669 # define prepare_ecx_params NULL
670
671 static int ecx_spki_pub_to_der(const void *vecxkey, unsigned char **pder)
672 {
673     const ECX_KEY *ecxkey = vecxkey;
674     unsigned char *keyblob;
675
676     if (ecxkey == NULL) {
677         ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_NULL_PARAMETER);
678         return 0;
679     }
680
681     keyblob = OPENSSL_memdup(ecxkey->pubkey, ecxkey->keylen);
682     if (keyblob == NULL) {
683         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
684         return 0;
685     }
686
687     *pder = keyblob;
688     return ecxkey->keylen;
689 }
690
691 static int ecx_pkcs8_priv_to_der(const void *vecxkey, unsigned char **pder)
692 {
693     const ECX_KEY *ecxkey = vecxkey;
694     ASN1_OCTET_STRING oct;
695     int keybloblen;
696
697     if (ecxkey == NULL || ecxkey->privkey == NULL) {
698         ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_NULL_PARAMETER);
699         return 0;
700     }
701
702     oct.data = ecxkey->privkey;
703     oct.length = ecxkey->keylen;
704     oct.flags = 0;
705
706     keybloblen = i2d_ASN1_OCTET_STRING(&oct, pder);
707     if (keybloblen < 0) {
708         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
709         return 0;
710     }
711
712     return keybloblen;
713 }
714
715 /*
716  * ED25519, ED448, X25519 and X448 only has PKCS#8 / SubjectPublicKeyInfo
717  * representation, so we don't define ecx_type_specific_[priv,pub,params]_to_der.
718  */
719
720 # define ecx_check_key_type     NULL
721
722 # define ed25519_evp_type       EVP_PKEY_ED25519
723 # define ed448_evp_type         EVP_PKEY_ED448
724 # define x25519_evp_type        EVP_PKEY_X25519
725 # define x448_evp_type          EVP_PKEY_X448
726 # define ed25519_input_type     "ED25519"
727 # define ed448_input_type       "ED448"
728 # define x25519_input_type      "X25519"
729 # define x448_input_type        "X448"
730 # define ed25519_pem_type       "ED25519"
731 # define ed448_pem_type         "ED448"
732 # define x25519_pem_type        "X25519"
733 # define x448_pem_type          "X448"
734 #endif
735
736 /* ---------------------------------------------------------------------- */
737
738 /*
739  * Helper functions to prepare RSA-PSS params for encoding.  We would
740  * have simply written the whole AlgorithmIdentifier, but existing libcrypto
741  * functionality doesn't allow that.
742  */
743
744 static int prepare_rsa_params(const void *rsa, int nid,
745                               void **pstr, int *pstrtype)
746 {
747     const RSA_PSS_PARAMS_30 *pss = ossl_rsa_get0_pss_params_30((RSA *)rsa);
748
749     *pstr = NULL;
750
751     switch (RSA_test_flags(rsa, RSA_FLAG_TYPE_MASK)) {
752     case RSA_FLAG_TYPE_RSA:
753         /* If plain RSA, the parameters shall be NULL */
754         *pstrtype = V_ASN1_NULL;
755         return 1;
756     case RSA_FLAG_TYPE_RSASSAPSS:
757         if (ossl_rsa_pss_params_30_is_unrestricted(pss)) {
758             *pstrtype = V_ASN1_UNDEF;
759             return 1;
760         } else {
761             ASN1_STRING *astr = NULL;
762             WPACKET pkt;
763             unsigned char *str = NULL;
764             size_t str_sz = 0;
765             int i;
766
767             for (i = 0; i < 2; i++) {
768                 switch (i) {
769                 case 0:
770                     if (!WPACKET_init_null_der(&pkt))
771                         goto err;
772                     break;
773                 case 1:
774                     if ((str = OPENSSL_malloc(str_sz)) == NULL
775                         || !WPACKET_init_der(&pkt, str, str_sz)) {
776                         goto err;
777                     }
778                     break;
779                 }
780                 if (!ossl_DER_w_RSASSA_PSS_params(&pkt, -1, pss)
781                     || !WPACKET_finish(&pkt)
782                     || !WPACKET_get_total_written(&pkt, &str_sz))
783                     goto err;
784                 WPACKET_cleanup(&pkt);
785
786                 /*
787                  * If no PSS parameters are going to be written, there's no
788                  * point going for another iteration.
789                  * This saves us from getting |str| allocated just to have it
790                  * immediately de-allocated.
791                  */
792                 if (str_sz == 0)
793                     break;
794             }
795
796             if ((astr = ASN1_STRING_new()) == NULL)
797                 goto err;
798             *pstrtype = V_ASN1_SEQUENCE;
799             ASN1_STRING_set0(astr, str, (int)str_sz);
800             *pstr = astr;
801
802             return 1;
803          err:
804             OPENSSL_free(str);
805             return 0;
806         }
807     }
808
809     /* Currently unsupported RSA key type */
810     return 0;
811 }
812
813 /*
814  * RSA is extremely simple, as PKCS#1 is used for the PKCS#8 |privateKey|
815  * field as well as the SubjectPublicKeyInfo |subjectPublicKey| field.
816  */
817 #define rsa_pkcs8_priv_to_der           rsa_type_specific_priv_to_der
818 #define rsa_spki_pub_to_der             rsa_type_specific_pub_to_der
819 #define rsa_type_specific_priv_to_der   (i2d_of_void *)i2d_RSAPrivateKey
820 #define rsa_type_specific_pub_to_der    (i2d_of_void *)i2d_RSAPublicKey
821 #define rsa_type_specific_params_to_der NULL
822
823 static int rsa_check_key_type(const void *rsa, int expected_type)
824 {
825     switch (RSA_test_flags(rsa, RSA_FLAG_TYPE_MASK)) {
826     case RSA_FLAG_TYPE_RSA:
827         return expected_type == EVP_PKEY_RSA;
828     case RSA_FLAG_TYPE_RSASSAPSS:
829         return expected_type == EVP_PKEY_RSA_PSS;
830     }
831
832     /* Currently unsupported RSA key type */
833     return EVP_PKEY_NONE;
834 }
835
836 #define rsa_evp_type            EVP_PKEY_RSA
837 #define rsapss_evp_type         EVP_PKEY_RSA_PSS
838 #define rsa_input_type          "RSA"
839 #define rsapss_input_type       "RSA-PSS"
840 #define rsa_pem_type            "RSA"
841 #define rsapss_pem_type         "RSA-PSS"
842
843 /* ---------------------------------------------------------------------- */
844
845 static OSSL_FUNC_decoder_newctx_fn key2any_newctx;
846 static OSSL_FUNC_decoder_freectx_fn key2any_freectx;
847
848 static void *key2any_newctx(void *provctx)
849 {
850     struct key2any_ctx_st *ctx = OPENSSL_zalloc(sizeof(*ctx));
851
852     if (ctx != NULL)
853         ctx->provctx = provctx;
854
855     return ctx;
856 }
857
858 static void key2any_freectx(void *vctx)
859 {
860     struct key2any_ctx_st *ctx = vctx;
861
862     ossl_pw_clear_passphrase_data(&ctx->pwdata);
863     EVP_CIPHER_free(ctx->cipher);
864     OPENSSL_free(ctx);
865 }
866
867 static const OSSL_PARAM *key2any_gettable_params(void *provctx, int structure)
868 {
869     static const OSSL_PARAM gettables[] = {
870         { OSSL_ENCODER_PARAM_INPUT_TYPE, OSSL_PARAM_UTF8_PTR, NULL, 0, 0 },
871         { OSSL_ENCODER_PARAM_OUTPUT_TYPE, OSSL_PARAM_UTF8_PTR, NULL, 0, 0 },
872         OSSL_PARAM_END,
873     };
874
875     static const OSSL_PARAM gettables_w_structure[] = {
876         { OSSL_ENCODER_PARAM_INPUT_TYPE, OSSL_PARAM_UTF8_PTR, NULL, 0, 0 },
877         { OSSL_ENCODER_PARAM_OUTPUT_TYPE, OSSL_PARAM_UTF8_PTR, NULL, 0, 0 },
878         { OSSL_ENCODER_PARAM_OUTPUT_STRUCTURE, OSSL_PARAM_UTF8_PTR, NULL, 0, 0 },
879         OSSL_PARAM_END,
880     };
881
882     return structure ? gettables_w_structure : gettables;
883 }
884
885 static int key2any_get_params(OSSL_PARAM params[], const char *input_type,
886                               const char *output_type,
887                               const char *output_struct)
888 {
889     OSSL_PARAM *p;
890
891     p = OSSL_PARAM_locate(params, OSSL_ENCODER_PARAM_INPUT_TYPE);
892     if (p != NULL && !OSSL_PARAM_set_utf8_ptr(p, input_type))
893         return 0;
894
895     p = OSSL_PARAM_locate(params, OSSL_ENCODER_PARAM_OUTPUT_TYPE);
896     if (p != NULL && !OSSL_PARAM_set_utf8_ptr(p, output_type))
897         return 0;
898
899     if (output_struct != NULL) {
900         p = OSSL_PARAM_locate(params, OSSL_ENCODER_PARAM_OUTPUT_STRUCTURE);
901         if (p != NULL && !OSSL_PARAM_set_utf8_ptr(p, output_struct))
902             return 0;
903     }
904
905     return 1;
906 }
907
908 static const OSSL_PARAM *key2any_settable_ctx_params(ossl_unused void *provctx)
909 {
910     static const OSSL_PARAM settables[] = {
911         OSSL_PARAM_utf8_string(OSSL_ENCODER_PARAM_CIPHER, NULL, 0),
912         OSSL_PARAM_utf8_string(OSSL_ENCODER_PARAM_PROPERTIES, NULL, 0),
913         OSSL_PARAM_END,
914     };
915
916     return settables;
917 }
918
919 static int key2any_set_ctx_params(void *vctx, const OSSL_PARAM params[])
920 {
921     struct key2any_ctx_st *ctx = vctx;
922     OSSL_LIB_CTX *libctx = ossl_prov_ctx_get0_libctx(ctx->provctx);
923     const OSSL_PARAM *cipherp =
924         OSSL_PARAM_locate_const(params, OSSL_ENCODER_PARAM_CIPHER);
925     const OSSL_PARAM *propsp =
926         OSSL_PARAM_locate_const(params, OSSL_ENCODER_PARAM_PROPERTIES);
927
928     if (cipherp != NULL) {
929         const char *ciphername = NULL;
930         const char *props = NULL;
931
932         if (!OSSL_PARAM_get_utf8_string_ptr(cipherp, &ciphername))
933             return 0;
934         if (propsp != NULL && !OSSL_PARAM_get_utf8_string_ptr(propsp, &props))
935             return 0;
936
937         EVP_CIPHER_free(ctx->cipher);
938         ctx->cipher = NULL;
939         ctx->cipher_intent = ciphername != NULL;
940         if (ciphername != NULL
941             && ((ctx->cipher =
942                  EVP_CIPHER_fetch(libctx, ciphername, props)) == NULL))
943             return 0;
944     }
945     return 1;
946 }
947
948 static int key2any_check_selection(int selection, int selection_mask)
949 {
950     /*
951      * The selections are kinda sorta "levels", i.e. each selection given
952      * here is assumed to include those following.
953      */
954     int checks[] = {
955         OSSL_KEYMGMT_SELECT_PRIVATE_KEY,
956         OSSL_KEYMGMT_SELECT_PUBLIC_KEY,
957         OSSL_KEYMGMT_SELECT_ALL_PARAMETERS
958     };
959     size_t i;
960
961     /* The decoder implementations made here support guessing */
962     if (selection == 0)
963         return 1;
964
965     for (i = 0; i < OSSL_NELEM(checks); i++) {
966         int check1 = (selection & checks[i]) != 0;
967         int check2 = (selection_mask & checks[i]) != 0;
968
969         /*
970          * If the caller asked for the currently checked bit(s), return
971          * whether the decoder description says it's supported.
972          */
973         if (check1)
974             return check2;
975     }
976
977     /* This should be dead code, but just to be safe... */
978     return 0;
979 }
980
981 static int key2any_encode(struct key2any_ctx_st *ctx, OSSL_CORE_BIO *cout,
982                           const void *key, int type, const char *pemname,
983                           check_key_type_fn *checker,
984                           key_to_der_fn *writer,
985                           OSSL_PASSPHRASE_CALLBACK *pwcb, void *pwcbarg,
986                           key_to_paramstring_fn *key2paramstring,
987                           i2d_of_void *key2der)
988 {
989     int ret = 0;
990
991     if (key == NULL) {
992         ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_NULL_PARAMETER);
993     } else if (writer != NULL
994                && (checker == NULL || checker(key, type))) {
995         BIO *out = bio_new_from_core_bio(ctx->provctx, cout);
996
997         if (out != NULL
998             && (pwcb == NULL
999                 || ossl_pw_set_ossl_passphrase_cb(&ctx->pwdata, pwcb, pwcbarg)))
1000             ret =
1001                 writer(out, key, type, pemname, key2paramstring, key2der, ctx);
1002
1003         BIO_free(out);
1004     } else {
1005         ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_INVALID_ARGUMENT);
1006     }
1007     return ret;
1008 }
1009
1010 #define DO_PRIVATE_KEY_selection_mask OSSL_KEYMGMT_SELECT_PRIVATE_KEY
1011 #define DO_PRIVATE_KEY(impl, type, kind, output)                            \
1012     if ((selection & DO_PRIVATE_KEY_selection_mask) != 0)                   \
1013         return key2any_encode(ctx, cout, key, impl##_evp_type,              \
1014                               impl##_pem_type " PRIVATE KEY",               \
1015                               type##_check_key_type,                        \
1016                               key_to_##kind##_##output##_priv_bio,          \
1017                               cb, cbarg, prepare_##type##_params,           \
1018                               type##_##kind##_priv_to_der);
1019
1020 #define DO_PUBLIC_KEY_selection_mask OSSL_KEYMGMT_SELECT_PUBLIC_KEY
1021 #define DO_PUBLIC_KEY(impl, type, kind, output)                             \
1022     if ((selection & DO_PUBLIC_KEY_selection_mask) != 0)                    \
1023         return key2any_encode(ctx, cout, key, impl##_evp_type,              \
1024                               impl##_pem_type " PUBLIC KEY",                \
1025                               type##_check_key_type,                        \
1026                               key_to_##kind##_##output##_pub_bio,           \
1027                               cb, cbarg, prepare_##type##_params,           \
1028                               type##_##kind##_pub_to_der);
1029
1030 #define DO_PARAMETERS_selection_mask OSSL_KEYMGMT_SELECT_ALL_PARAMETERS
1031 #define DO_PARAMETERS(impl, type, kind, output)                             \
1032     if ((selection & DO_PARAMETERS_selection_mask) != 0)                    \
1033         return key2any_encode(ctx, cout, key, impl##_evp_type,              \
1034                               impl##_pem_type " PARAMETERS",                \
1035                               type##_check_key_type,                        \
1036                               key_to_##kind##_##output##_param_bio,         \
1037                               NULL, NULL, NULL,                             \
1038                               type##_##kind##_params_to_der);
1039
1040 /*-
1041  * Implement the kinds of output structure that can be produced.  They are
1042  * referred to by name, and for each name, the following macros are defined
1043  * (braces not included):
1044  *
1045  * {kind}_output_structure
1046  *
1047  *      A string that names the output structure. This is used as a selection
1048  *      criterion for each implementation.  It may be NULL, which means that
1049  *      there is only one possible output structure for the implemented output
1050  *      type.
1051  *
1052  * DO_{kind}_selection_mask
1053  *
1054  *      A mask of selection bits that must not be zero.  This is used as a
1055  *      selection criterion for each implementation.
1056  *      This mask must never be zero.
1057  *
1058  * DO_{kind}
1059  *
1060  *      The performing macro.  It must use the DO_ macros defined above,
1061  *      always in this order:
1062  *
1063  *      - DO_PRIVATE_KEY
1064  *      - DO_PUBLIC_KEY
1065  *      - DO_PARAMETERS
1066  *
1067  *      Any of those may be omitted, but the relative order must still be
1068  *      the same.
1069  */
1070
1071 /* PKCS#8 is a structure for private keys only */
1072 #define PKCS8_output_structure "pkcs8"
1073 #define DO_PKCS8_selection_mask DO_PRIVATE_KEY_selection_mask
1074 #define DO_PKCS8(impl, type, output)                                        \
1075     DO_PRIVATE_KEY(impl, type, pkcs8, output)
1076
1077 /* SubjectPublicKeyInfo is a structure for public keys only */
1078 #define SubjectPublicKeyInfo_output_structure "SubjectPublicKeyInfo"
1079 #define DO_SubjectPublicKeyInfo_selection_mask DO_PUBLIC_KEY_selection_mask
1080 #define DO_SubjectPublicKeyInfo(impl, type, output)                         \
1081     DO_PUBLIC_KEY(impl, type, spki, output)
1082
1083 /*
1084  * "type-specific" is a uniform name for key type specific output for private
1085  * and public keys as well as key parameters.  This is used internally in
1086  * libcrypto so it doesn't have to have special knowledge about select key
1087  * types, but also when no better name has been found.  If there are more
1088  * expressive DO_ names above, those are preferred.
1089  *
1090  * Three forms exist:
1091  *
1092  * - type_specific_keypair              Only supports private and public key
1093  * - type_specific_params               Only supports parameters
1094  * - type_specific                      Supports all parts of an EVP_PKEY
1095  * - type_specific_no_pub               Supports all parts of an EVP_PKEY
1096  *                                      except public key
1097  */
1098 #define type_specific_params_output_structure "type-specific"
1099 #define DO_type_specific_params_selection_mask DO_PARAMETERS_selection_mask
1100 #define DO_type_specific_params(impl, type, output)                         \
1101     DO_PARAMETERS(impl, type, type_specific, output)
1102 #define type_specific_keypair_output_structure "type-specific"
1103 #define DO_type_specific_keypair_selection_mask                             \
1104     ( DO_PRIVATE_KEY_selection_mask | DO_PUBLIC_KEY_selection_mask )
1105 #define DO_type_specific_keypair(impl, type, output)                        \
1106     DO_PRIVATE_KEY(impl, type, type_specific, output)                       \
1107     DO_PUBLIC_KEY(impl, type, type_specific, output)
1108 #define type_specific_output_structure "type-specific"
1109 #define DO_type_specific_selection_mask                                     \
1110     ( DO_type_specific_keypair_selection_mask                               \
1111       | DO_type_specific_params_selection_mask )
1112 #define DO_type_specific(impl, type, output)                                \
1113     DO_type_specific_keypair(impl, type, output)                            \
1114     DO_type_specific_params(impl, type, output)
1115 #define type_specific_no_pub_output_structure "type-specific"
1116 #define DO_type_specific_no_pub_selection_mask \
1117     ( DO_PRIVATE_KEY_selection_mask |  DO_PARAMETERS_selection_mask)
1118 #define DO_type_specific_no_pub(impl, type, output)                         \
1119     DO_PRIVATE_KEY(impl, type, type_specific, output)                       \
1120     DO_type_specific_params(impl, type, output)
1121
1122 /*
1123  * Type specific aliases for the cases where we need to refer to them by
1124  * type name.
1125  * This only covers key types that are represented with i2d_{TYPE}PrivateKey,
1126  * i2d_{TYPE}PublicKey and i2d_{TYPE}params / i2d_{TYPE}Parameters.
1127  */
1128 #define RSA_output_structure "rsa"
1129 #define DO_RSA_selection_mask DO_type_specific_keypair_selection_mask
1130 #define DO_RSA(impl, type, output) DO_type_specific_keypair(impl, type, output)
1131
1132 #define DH_output_structure "dh"
1133 #define DO_DH_selection_mask DO_type_specific_params_selection_mask
1134 #define DO_DH(impl, type, output) DO_type_specific_params(impl, type, output)
1135
1136 #define DHX_output_structure "dhx"
1137 #define DO_DHX_selection_mask DO_type_specific_params_selection_mask
1138 #define DO_DHX(impl, type, output) DO_type_specific_params(impl, type, output)
1139
1140 #define DSA_output_structure "dsa"
1141 #define DO_DSA_selection_mask DO_type_specific_selection_mask
1142 #define DO_DSA(impl, type, output) DO_type_specific(impl, type, output)
1143
1144 #define EC_output_structure "ec"
1145 #define DO_EC_selection_mask DO_type_specific_selection_mask
1146 #define DO_EC(impl, type, output) DO_type_specific(impl, type, output)
1147
1148 #define SM2_output_structure "sm2"
1149 #define DO_SM2_selection_mask DO_type_specific_selection_mask
1150 #define DO_SM2(impl, type, output) DO_type_specific(impl, type, output)
1151
1152 /* PKCS#1 defines a structure for RSA private and public keys */
1153 #define PKCS1_output_structure "pkcs1"
1154 #define DO_PKCS1_selection_mask DO_RSA_selection_mask
1155 #define DO_PKCS1(impl, type, output) DO_RSA(impl, type, output)
1156
1157 /* PKCS#3 defines a structure for DH parameters */
1158 #define PKCS3_output_structure "pkcs3"
1159 #define DO_PKCS3_selection_mask DO_DH_selection_mask
1160 #define DO_PKCS3(impl, type, output) DO_DH(impl, type, output)
1161 /* X9.42 defines a structure for DHx parameters */
1162 #define X9_42_output_structure "X9.42"
1163 #define DO_X9_42_selection_mask DO_DHX_selection_mask
1164 #define DO_X9_42(impl, type, output) DO_DHX(impl, type, output)
1165
1166 /* X9.62 defines a structure for EC keys and parameters */
1167 #define X9_62_output_structure "X9.62"
1168 #define DO_X9_62_selection_mask DO_EC_selection_mask
1169 #define DO_X9_62(impl, type, output) DO_EC(impl, type, output)
1170
1171 /*
1172  * MAKE_ENCODER is the single driver for creating OSSL_DISPATCH tables.
1173  * It takes the following arguments:
1174  *
1175  * impl         This is the key type name that's being implemented.
1176  * type         This is the type name for the set of functions that implement
1177  *              the key type.  For example, ed25519, ed448, x25519 and x448
1178  *              are all implemented with the exact same set of functions.
1179  * evp_type     The corresponding EVP_PKEY_xxx type macro for each key.
1180  *              Necessary because we currently use EVP_PKEY with legacy
1181  *              native keys internally.  This will need to be refactored
1182  *              when that legacy support goes away.
1183  * kind         What kind of support to implement.  These translate into
1184  *              the DO_##kind macros above.
1185  * output       The output type to implement.  may be der or pem.
1186  *
1187  * The resulting OSSL_DISPATCH array gets the following name (expressed in
1188  * C preprocessor terms) from those arguments:
1189  *
1190  * ossl_##impl##_to_##kind##_##output##_encoder_functions
1191  */
1192 #define MAKE_ENCODER(impl, type, evp_type, kind, output)                    \
1193     static OSSL_FUNC_encoder_gettable_params_fn                             \
1194     impl##_to_##kind##_##output##_gettable_params;                          \
1195     static OSSL_FUNC_encoder_get_params_fn                                  \
1196     impl##_to_##kind##_##output##_get_params;                               \
1197     static OSSL_FUNC_encoder_import_object_fn                               \
1198     impl##_to_##kind##_##output##_import_object;                            \
1199     static OSSL_FUNC_encoder_free_object_fn                                 \
1200     impl##_to_##kind##_##output##_free_object;                              \
1201     static OSSL_FUNC_encoder_encode_fn                                      \
1202     impl##_to_##kind##_##output##_encode;                                   \
1203                                                                             \
1204     static const OSSL_PARAM *                                               \
1205     impl##_to_##kind##_##output##_gettable_params(void *provctx)            \
1206     {                                                                       \
1207         return key2any_gettable_params(provctx,                             \
1208                                        kind##_output_structure != NULL);    \
1209     }                                                                       \
1210     static int                                                              \
1211     impl##_to_##kind##_##output##_get_params(OSSL_PARAM params[])           \
1212     {                                                                       \
1213         return key2any_get_params(params, impl##_input_type,                \
1214                                   output##_output_type,                     \
1215                                   kind##_output_structure);                 \
1216     }                                                                       \
1217     static void *                                                           \
1218     impl##_to_##kind##_##output##_import_object(void *vctx, int selection,  \
1219                                                 const OSSL_PARAM params[])  \
1220     {                                                                       \
1221         struct key2any_ctx_st *ctx = vctx;                                  \
1222                                                                             \
1223         return ossl_prov_import_key(ossl_##impl##_keymgmt_functions,        \
1224                                     ctx->provctx, selection, params);       \
1225     }                                                                       \
1226     static void impl##_to_##kind##_##output##_free_object(void *key)        \
1227     {                                                                       \
1228         ossl_prov_free_key(ossl_##impl##_keymgmt_functions, key);           \
1229     }                                                                       \
1230     static int impl##_to_##kind##_##output##_does_selection(void *ctx,      \
1231                                                             int selection)  \
1232     {                                                                       \
1233         return key2any_check_selection(selection,                           \
1234                                        DO_##kind##_selection_mask);         \
1235     }                                                                       \
1236     static int                                                              \
1237     impl##_to_##kind##_##output##_encode(void *ctx, OSSL_CORE_BIO *cout,    \
1238                                          const void *key,                   \
1239                                          const OSSL_PARAM key_abstract[],   \
1240                                          int selection,                     \
1241                                          OSSL_PASSPHRASE_CALLBACK *cb,      \
1242                                          void *cbarg)                       \
1243     {                                                                       \
1244         /* We don't deal with abstract objects */                           \
1245         if (key_abstract != NULL) {                                         \
1246             ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_INVALID_ARGUMENT);         \
1247             return 0;                                                       \
1248         }                                                                   \
1249         DO_##kind(impl, type, output)                                       \
1250                                                                             \
1251         ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_INVALID_ARGUMENT);             \
1252         return 0;                                                           \
1253     }                                                                       \
1254     const OSSL_DISPATCH                                                     \
1255     ossl_##impl##_to_##kind##_##output##_encoder_functions[] = {            \
1256         { OSSL_FUNC_ENCODER_NEWCTX,                                         \
1257           (void (*)(void))key2any_newctx },                                 \
1258         { OSSL_FUNC_ENCODER_FREECTX,                                        \
1259           (void (*)(void))key2any_freectx },                                \
1260         { OSSL_FUNC_ENCODER_GETTABLE_PARAMS,                                \
1261           (void (*)(void))impl##_to_##kind##_##output##_gettable_params },  \
1262         { OSSL_FUNC_ENCODER_GET_PARAMS,                                     \
1263           (void (*)(void))impl##_to_##kind##_##output##_get_params },       \
1264         { OSSL_FUNC_ENCODER_SETTABLE_CTX_PARAMS,                            \
1265           (void (*)(void))key2any_settable_ctx_params },                    \
1266         { OSSL_FUNC_ENCODER_SET_CTX_PARAMS,                                 \
1267           (void (*)(void))key2any_set_ctx_params },                         \
1268         { OSSL_FUNC_ENCODER_DOES_SELECTION,                                 \
1269           (void (*)(void))impl##_to_##kind##_##output##_does_selection },   \
1270         { OSSL_FUNC_ENCODER_IMPORT_OBJECT,                                  \
1271           (void (*)(void))impl##_to_##kind##_##output##_import_object },    \
1272         { OSSL_FUNC_ENCODER_FREE_OBJECT,                                    \
1273           (void (*)(void))impl##_to_##kind##_##output##_free_object },      \
1274         { OSSL_FUNC_ENCODER_ENCODE,                                         \
1275           (void (*)(void))impl##_to_##kind##_##output##_encode },           \
1276         { 0, NULL }                                                         \
1277     }
1278
1279 /*
1280  * Replacements for i2d_{TYPE}PrivateKey, i2d_{TYPE}PublicKey,
1281  * i2d_{TYPE}params, as they exist.
1282  */
1283 MAKE_ENCODER(rsa, rsa, EVP_PKEY_RSA, type_specific_keypair, der);
1284 #ifndef OPENSSL_NO_DH
1285 MAKE_ENCODER(dh, dh, EVP_PKEY_DH, type_specific_params, der);
1286 MAKE_ENCODER(dhx, dh, EVP_PKEY_DHX, type_specific_params, der);
1287 #endif
1288 #ifndef OPENSSL_NO_DSA
1289 MAKE_ENCODER(dsa, dsa, EVP_PKEY_DSA, type_specific, der);
1290 #endif
1291 #ifndef OPENSSL_NO_EC
1292 MAKE_ENCODER(ec, ec, EVP_PKEY_EC, type_specific_no_pub, der);
1293 # ifndef OPENSSL_NO_SM2
1294 MAKE_ENCODER(sm2, ec, EVP_PKEY_EC, type_specific_no_pub, der);
1295 # endif
1296 #endif
1297
1298 /*
1299  * Replacements for PEM_write_bio_{TYPE}PrivateKey,
1300  * PEM_write_bio_{TYPE}PublicKey, PEM_write_bio_{TYPE}params, as they exist.
1301  */
1302 MAKE_ENCODER(rsa, rsa, EVP_PKEY_RSA, type_specific_keypair, pem);
1303 #ifndef OPENSSL_NO_DH
1304 MAKE_ENCODER(dh, dh, EVP_PKEY_DH, type_specific_params, pem);
1305 MAKE_ENCODER(dhx, dh, EVP_PKEY_DHX, type_specific_params, pem);
1306 #endif
1307 #ifndef OPENSSL_NO_DSA
1308 MAKE_ENCODER(dsa, dsa, EVP_PKEY_DSA, type_specific, pem);
1309 #endif
1310 #ifndef OPENSSL_NO_EC
1311 MAKE_ENCODER(ec, ec, EVP_PKEY_EC, type_specific_no_pub, pem);
1312 # ifndef OPENSSL_NO_SM2
1313 MAKE_ENCODER(sm2, ec, EVP_PKEY_EC, type_specific_no_pub, pem);
1314 # endif
1315 #endif
1316
1317 /*
1318  * PKCS#8 and SubjectPublicKeyInfo support.  This may duplicate some of the
1319  * implementations specified above, but are more specific.
1320  * The SubjectPublicKeyInfo implementations also replace the
1321  * PEM_write_bio_{TYPE}_PUBKEY functions.
1322  * For PEM, these are expected to be used by PEM_write_bio_PrivateKey(),
1323  * PEM_write_bio_PUBKEY() and PEM_write_bio_Parameters().
1324  */
1325 MAKE_ENCODER(rsa, rsa, EVP_PKEY_RSA, PKCS8, der);
1326 MAKE_ENCODER(rsa, rsa, EVP_PKEY_RSA, PKCS8, pem);
1327 MAKE_ENCODER(rsa, rsa, EVP_PKEY_RSA, SubjectPublicKeyInfo, der);
1328 MAKE_ENCODER(rsa, rsa, EVP_PKEY_RSA, SubjectPublicKeyInfo, pem);
1329 MAKE_ENCODER(rsapss, rsa, EVP_PKEY_RSA_PSS, PKCS8, der);
1330 MAKE_ENCODER(rsapss, rsa, EVP_PKEY_RSA_PSS, PKCS8, pem);
1331 MAKE_ENCODER(rsapss, rsa, EVP_PKEY_RSA_PSS, SubjectPublicKeyInfo, der);
1332 MAKE_ENCODER(rsapss, rsa, EVP_PKEY_RSA_PSS, SubjectPublicKeyInfo, pem);
1333 #ifndef OPENSSL_NO_DH
1334 MAKE_ENCODER(dh, dh, EVP_PKEY_DH, PKCS8, der);
1335 MAKE_ENCODER(dh, dh, EVP_PKEY_DH, PKCS8, pem);
1336 MAKE_ENCODER(dh, dh, EVP_PKEY_DH, SubjectPublicKeyInfo, der);
1337 MAKE_ENCODER(dh, dh, EVP_PKEY_DH, SubjectPublicKeyInfo, pem);
1338 MAKE_ENCODER(dhx, dh, EVP_PKEY_DHX, PKCS8, der);
1339 MAKE_ENCODER(dhx, dh, EVP_PKEY_DHX, PKCS8, pem);
1340 MAKE_ENCODER(dhx, dh, EVP_PKEY_DHX, SubjectPublicKeyInfo, der);
1341 MAKE_ENCODER(dhx, dh, EVP_PKEY_DHX, SubjectPublicKeyInfo, pem);
1342 #endif
1343 #ifndef OPENSSL_NO_DSA
1344 MAKE_ENCODER(dsa, dsa, EVP_PKEY_DSA, PKCS8, der);
1345 MAKE_ENCODER(dsa, dsa, EVP_PKEY_DSA, PKCS8, pem);
1346 MAKE_ENCODER(dsa, dsa, EVP_PKEY_DSA, SubjectPublicKeyInfo, der);
1347 MAKE_ENCODER(dsa, dsa, EVP_PKEY_DSA, SubjectPublicKeyInfo, pem);
1348 #endif
1349 #ifndef OPENSSL_NO_EC
1350 MAKE_ENCODER(ec, ec, EVP_PKEY_EC, PKCS8, der);
1351 MAKE_ENCODER(ec, ec, EVP_PKEY_EC, PKCS8, pem);
1352 MAKE_ENCODER(ec, ec, EVP_PKEY_EC, SubjectPublicKeyInfo, der);
1353 MAKE_ENCODER(ec, ec, EVP_PKEY_EC, SubjectPublicKeyInfo, pem);
1354 # ifndef OPENSSL_NO_SM2
1355 MAKE_ENCODER(sm2, ec, EVP_PKEY_EC, PKCS8, der);
1356 MAKE_ENCODER(sm2, ec, EVP_PKEY_EC, PKCS8, pem);
1357 MAKE_ENCODER(sm2, ec, EVP_PKEY_EC, SubjectPublicKeyInfo, der);
1358 MAKE_ENCODER(sm2, ec, EVP_PKEY_EC, SubjectPublicKeyInfo, pem);
1359 # endif
1360 MAKE_ENCODER(ed25519, ecx, EVP_PKEY_ED25519, PKCS8, der);
1361 MAKE_ENCODER(ed25519, ecx, EVP_PKEY_ED25519, PKCS8, pem);
1362 MAKE_ENCODER(ed25519, ecx, EVP_PKEY_ED25519, SubjectPublicKeyInfo, der);
1363 MAKE_ENCODER(ed25519, ecx, EVP_PKEY_ED25519, SubjectPublicKeyInfo, pem);
1364 MAKE_ENCODER(ed448, ecx, EVP_PKEY_ED448, PKCS8, der);
1365 MAKE_ENCODER(ed448, ecx, EVP_PKEY_ED448, PKCS8, pem);
1366 MAKE_ENCODER(ed448, ecx, EVP_PKEY_ED448, SubjectPublicKeyInfo, der);
1367 MAKE_ENCODER(ed448, ecx, EVP_PKEY_ED448, SubjectPublicKeyInfo, pem);
1368 MAKE_ENCODER(x25519, ecx, EVP_PKEY_X25519, PKCS8, der);
1369 MAKE_ENCODER(x25519, ecx, EVP_PKEY_X25519, PKCS8, pem);
1370 MAKE_ENCODER(x25519, ecx, EVP_PKEY_X25519, SubjectPublicKeyInfo, der);
1371 MAKE_ENCODER(x25519, ecx, EVP_PKEY_X25519, SubjectPublicKeyInfo, pem);
1372 MAKE_ENCODER(x448, ecx, EVP_PKEY_ED448, PKCS8, der);
1373 MAKE_ENCODER(x448, ecx, EVP_PKEY_ED448, PKCS8, pem);
1374 MAKE_ENCODER(x448, ecx, EVP_PKEY_ED448, SubjectPublicKeyInfo, der);
1375 MAKE_ENCODER(x448, ecx, EVP_PKEY_ED448, SubjectPublicKeyInfo, pem);
1376 #endif
1377
1378 /*
1379  * Support for key type specific output formats.  Not all key types have
1380  * this, we only aim to duplicate what is available in 1.1.1 as
1381  * i2d_TYPEPrivateKey(), i2d_TYPEPublicKey() and i2d_TYPEparams().
1382  * For example, there are no publicly available i2d_ function for
1383  * ED25519, ED448, X25519 or X448, and they therefore only have PKCS#8
1384  * and SubjectPublicKeyInfo implementations as implemented above.
1385  */
1386 MAKE_ENCODER(rsa, rsa, EVP_PKEY_RSA, RSA, der);
1387 MAKE_ENCODER(rsa, rsa, EVP_PKEY_RSA, RSA, pem);
1388 #ifndef OPENSSL_NO_DH
1389 MAKE_ENCODER(dh, dh, EVP_PKEY_DH, DH, der);
1390 MAKE_ENCODER(dh, dh, EVP_PKEY_DH, DH, pem);
1391 MAKE_ENCODER(dhx, dh, EVP_PKEY_DHX, DHX, der);
1392 MAKE_ENCODER(dhx, dh, EVP_PKEY_DHX, DHX, pem);
1393 #endif
1394 #ifndef OPENSSL_NO_DSA
1395 MAKE_ENCODER(dsa, dsa, EVP_PKEY_DSA, DSA, der);
1396 MAKE_ENCODER(dsa, dsa, EVP_PKEY_DSA, DSA, pem);
1397 #endif
1398 #ifndef OPENSSL_NO_EC
1399 MAKE_ENCODER(ec, ec, EVP_PKEY_EC, EC, der);
1400 MAKE_ENCODER(ec, ec, EVP_PKEY_EC, EC, pem);
1401 # ifndef OPENSSL_NO_SM2
1402 MAKE_ENCODER(sm2, ec, EVP_PKEY_EC, SM2, der);
1403 MAKE_ENCODER(sm2, ec, EVP_PKEY_EC, SM2, pem);
1404 # endif
1405 #endif
1406
1407 /* Convenience structure names */
1408 MAKE_ENCODER(rsa, rsa, EVP_PKEY_RSA, PKCS1, der);
1409 MAKE_ENCODER(rsa, rsa, EVP_PKEY_RSA, PKCS1, pem);
1410 MAKE_ENCODER(rsapss, rsa, EVP_PKEY_RSA_PSS, PKCS1, der);
1411 MAKE_ENCODER(rsapss, rsa, EVP_PKEY_RSA_PSS, PKCS1, pem);
1412 #ifndef OPENSSL_NO_DH
1413 MAKE_ENCODER(dh, dh, EVP_PKEY_DH, PKCS3, der); /* parameters only */
1414 MAKE_ENCODER(dh, dh, EVP_PKEY_DH, PKCS3, pem); /* parameters only */
1415 MAKE_ENCODER(dhx, dh, EVP_PKEY_DHX, X9_42, der); /* parameters only */
1416 MAKE_ENCODER(dhx, dh, EVP_PKEY_DHX, X9_42, pem); /* parameters only */
1417 #endif
1418 #ifndef OPENSSL_NO_EC
1419 MAKE_ENCODER(ec, ec, EVP_PKEY_EC, X9_62, der);
1420 MAKE_ENCODER(ec, ec, EVP_PKEY_EC, X9_62, pem);
1421 #endif