2 * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
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
11 * Low level APIs are deprecated for public use, but still ok for
14 #include "internal/deprecated.h"
17 #include "internal/cryptlib.h"
18 #include <openssl/evp.h>
19 #include <openssl/encoder.h>
20 #include <openssl/buffer.h>
21 #include <openssl/x509.h>
22 #include <openssl/rsa.h> /* For i2d_RSAPublicKey */
23 #include <openssl/dsa.h> /* For i2d_DSAPublicKey */
24 #include <openssl/ec.h> /* For i2o_ECPublicKey */
25 #include "crypto/asn1.h"
26 #include "crypto/evp.h"
28 static int i2d_provided(const EVP_PKEY *a, int selection,
29 const char *output_structures[],
32 OSSL_ENCODER_CTX *ctx = NULL;
36 ret == -1 && *output_structures != NULL;
37 output_structures++) {
39 * The i2d_ calls don't take a boundary length for *pp. However,
40 * OSSL_ENCODER_CTX_get_num_encoders() needs one, so we make one
45 ctx = OSSL_ENCODER_CTX_new_for_pkey(a, selection, "DER",
46 *output_structures, NULL);
49 if (OSSL_ENCODER_to_data(ctx, pp, &len))
51 OSSL_ENCODER_CTX_free(ctx);
56 ERR_raise(ERR_LIB_ASN1, ASN1_R_UNSUPPORTED_TYPE);
60 int i2d_KeyParams(const EVP_PKEY *a, unsigned char **pp)
62 if (evp_pkey_is_provided(a)) {
63 const char *output_structures[] = { "type-specific", NULL };
65 return i2d_provided(a, EVP_PKEY_KEY_PARAMETERS, output_structures, pp);
67 if (a->ameth != NULL && a->ameth->param_encode != NULL)
68 return a->ameth->param_encode(a, pp);
69 ERR_raise(ERR_LIB_ASN1, ASN1_R_UNSUPPORTED_TYPE);
73 int i2d_KeyParams_bio(BIO *bp, const EVP_PKEY *pkey)
75 return ASN1_i2d_bio_of(EVP_PKEY, i2d_KeyParams, bp, pkey);
78 int i2d_PrivateKey(const EVP_PKEY *a, unsigned char **pp)
80 if (evp_pkey_is_provided(a)) {
81 const char *output_structures[] = { "type-specific", "pkcs8", NULL };
83 return i2d_provided(a, EVP_PKEY_KEYPAIR, output_structures, pp);
85 if (a->ameth != NULL && a->ameth->old_priv_encode != NULL) {
86 return a->ameth->old_priv_encode(a, pp);
88 if (a->ameth != NULL && a->ameth->priv_encode != NULL) {
89 PKCS8_PRIV_KEY_INFO *p8 = EVP_PKEY2PKCS8(a);
93 ret = i2d_PKCS8_PRIV_KEY_INFO(p8, pp);
94 PKCS8_PRIV_KEY_INFO_free(p8);
98 ERR_raise(ERR_LIB_ASN1, ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE);
102 int i2d_PublicKey(const EVP_PKEY *a, unsigned char **pp)
104 if (evp_pkey_is_provided(a)) {
105 const char *output_structures[] = { "type-specific", NULL };
107 return i2d_provided(a, EVP_PKEY_PUBLIC_KEY, output_structures, pp);
109 switch (EVP_PKEY_id(a)) {
111 return i2d_RSAPublicKey(EVP_PKEY_get0_RSA(a), pp);
112 #ifndef OPENSSL_NO_DSA
114 return i2d_DSAPublicKey(EVP_PKEY_get0_DSA(a), pp);
116 #ifndef OPENSSL_NO_EC
118 return i2o_ECPublicKey(EVP_PKEY_get0_EC_KEY(a), pp);
121 ERR_raise(ERR_LIB_ASN1, ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE);