xref: /openssl/crypto/asn1/asn_pack.c (revision da1c088f)
1 /*
2  * Copyright 1999-2023 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/asn1.h>
13 
14 /* ASN1 packing and unpacking functions */
15 
ASN1_item_pack(void * obj,const ASN1_ITEM * it,ASN1_STRING ** oct)16 ASN1_STRING *ASN1_item_pack(void *obj, const ASN1_ITEM *it, ASN1_STRING **oct)
17 {
18     ASN1_STRING *octmp;
19 
20     if (oct == NULL || *oct == NULL) {
21         if ((octmp = ASN1_STRING_new()) == NULL) {
22             ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB);
23             return NULL;
24         }
25     } else {
26         octmp = *oct;
27     }
28 
29     ASN1_STRING_set0(octmp, NULL, 0);
30 
31     if ((octmp->length = ASN1_item_i2d(obj, &octmp->data, it)) <= 0) {
32         ERR_raise(ERR_LIB_ASN1, ASN1_R_ENCODE_ERROR);
33         goto err;
34     }
35     if (octmp->data == NULL) {
36         ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB);
37         goto err;
38     }
39 
40     if (oct != NULL && *oct == NULL)
41         *oct = octmp;
42 
43     return octmp;
44  err:
45     if (oct == NULL || *oct == NULL)
46         ASN1_STRING_free(octmp);
47     return NULL;
48 }
49 
50 /* Extract an ASN1 object from an ASN1_STRING */
51 
ASN1_item_unpack(const ASN1_STRING * oct,const ASN1_ITEM * it)52 void *ASN1_item_unpack(const ASN1_STRING *oct, const ASN1_ITEM *it)
53 {
54     const unsigned char *p;
55     void *ret;
56 
57     p = oct->data;
58     if ((ret = ASN1_item_d2i(NULL, &p, oct->length, it)) == NULL)
59         ERR_raise(ERR_LIB_ASN1, ASN1_R_DECODE_ERROR);
60     return ret;
61 }
62 
ASN1_item_unpack_ex(const ASN1_STRING * oct,const ASN1_ITEM * it,OSSL_LIB_CTX * libctx,const char * propq)63 void *ASN1_item_unpack_ex(const ASN1_STRING *oct, const ASN1_ITEM *it,
64                           OSSL_LIB_CTX *libctx, const char *propq)
65 {
66     const unsigned char *p;
67     void *ret;
68 
69     p = oct->data;
70     if ((ret = ASN1_item_d2i_ex(NULL, &p, oct->length, it,\
71                                 libctx, propq)) == NULL)
72         ERR_raise(ERR_LIB_ASN1, ASN1_R_DECODE_ERROR);
73     return ret;
74 }
75