]> git.ipfire.org Git - thirdparty/openssl.git/blob - crypto/asn1/i2d_pr.c
Rename OSSL_SERIALIZER / OSSL_DESERIALIZER to OSSL_ENCODE / OSSL_DECODE
[thirdparty/openssl.git] / crypto / asn1 / i2d_pr.c
1 /*
2 * Copyright 1995-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 #include <stdio.h>
11 #include "internal/cryptlib.h"
12 #include <openssl/evp.h>
13 #include <openssl/encoder.h>
14 #include <openssl/buffer.h>
15 #include <openssl/x509.h>
16 #include "crypto/asn1.h"
17 #include "crypto/evp.h"
18
19 int i2d_PrivateKey(const EVP_PKEY *a, unsigned char **pp)
20 {
21 if (a->ameth && a->ameth->old_priv_encode) {
22 return a->ameth->old_priv_encode(a, pp);
23 }
24 if (a->ameth && a->ameth->priv_encode) {
25 PKCS8_PRIV_KEY_INFO *p8 = EVP_PKEY2PKCS8(a);
26 int ret = 0;
27 if (p8 != NULL) {
28 ret = i2d_PKCS8_PRIV_KEY_INFO(p8, pp);
29 PKCS8_PRIV_KEY_INFO_free(p8);
30 }
31 return ret;
32 }
33 if (a->keymgmt != NULL) {
34 const char *encprop = OSSL_ENCODER_PrivateKey_TO_DER_PQ;
35 OSSL_ENCODER_CTX *ctx =
36 OSSL_ENCODER_CTX_new_by_EVP_PKEY(a, encprop);
37 BIO *out = BIO_new(BIO_s_mem());
38 BUF_MEM *buf = NULL;
39 int ret = -1;
40
41 if (ctx != NULL
42 && out != NULL
43 && OSSL_ENCODER_CTX_get_encoder(ctx) != NULL
44 && OSSL_ENCODER_to_bio(ctx, out)
45 && BIO_get_mem_ptr(out, &buf) > 0) {
46 ret = buf->length;
47
48 if (pp != NULL) {
49 if (*pp == NULL) {
50 *pp = (unsigned char *)buf->data;
51 buf->length = 0;
52 buf->data = NULL;
53 } else {
54 memcpy(*pp, buf->data, ret);
55 *pp += ret;
56 }
57 }
58 }
59 BIO_free(out);
60 OSSL_ENCODER_CTX_free(ctx);
61 return ret;
62 }
63 ASN1err(ASN1_F_I2D_PRIVATEKEY, ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE);
64 return -1;
65 }