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