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 #include "internal/cryptlib.h"
12 #include <openssl/evp.h>
13 #include <openssl/serializer.h>
14 #include <openssl/buffer.h>
15 #include <openssl/x509.h>
16 #include "crypto/asn1.h"
17 #include "crypto/evp.h"
19 int i2d_PrivateKey(const EVP_PKEY *a, unsigned char **pp)
21 if (a->ameth && a->ameth->old_priv_encode) {
22 return a->ameth->old_priv_encode(a, pp);
24 if (a->ameth && a->ameth->priv_encode) {
25 PKCS8_PRIV_KEY_INFO *p8 = EVP_PKEY2PKCS8(a);
28 ret = i2d_PKCS8_PRIV_KEY_INFO(p8, pp);
29 PKCS8_PRIV_KEY_INFO_free(p8);
33 if (a->keymgmt != NULL) {
34 const char *serprop = OSSL_SERIALIZER_PrivateKey_TO_DER_PQ;
35 OSSL_SERIALIZER_CTX *ctx =
36 OSSL_SERIALIZER_CTX_new_by_EVP_PKEY(a, serprop);
37 BIO *out = BIO_new(BIO_s_mem());
43 && OSSL_SERIALIZER_CTX_get_serializer(ctx) != NULL
44 && OSSL_SERIALIZER_to_bio(ctx, out)
45 && BIO_get_mem_ptr(out, &buf) > 0) {
50 *pp = (unsigned char *)buf->data;
54 memcpy(*pp, buf->data, ret);
60 OSSL_SERIALIZER_CTX_free(ctx);
63 ASN1err(ASN1_F_I2D_PRIVATEKEY, ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE);