Copyright consolidation 08/10
[openssl.git] / crypto / asn1 / asn_pack.c
1 /*
2  * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (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
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             ASN1err(ASN1_F_ASN1_ITEM_PACK, ERR_R_MALLOC_FAILURE);
23             return NULL;
24         }
25         if (oct)
26             *oct = octmp;
27     } else
28         octmp = *oct;
29
30     OPENSSL_free(octmp->data);
31     octmp->data = NULL;
32
33     if ((octmp->length = ASN1_item_i2d(obj, &octmp->data, it)) == 0) {
34         ASN1err(ASN1_F_ASN1_ITEM_PACK, ASN1_R_ENCODE_ERROR);
35         return NULL;
36     }
37     if (!octmp->data) {
38         ASN1err(ASN1_F_ASN1_ITEM_PACK, ERR_R_MALLOC_FAILURE);
39         return NULL;
40     }
41     return octmp;
42 }
43
44 /* Extract an ASN1 object from an ASN1_STRING */
45
46 void *ASN1_item_unpack(ASN1_STRING *oct, const ASN1_ITEM *it)
47 {
48     const unsigned char *p;
49     void *ret;
50
51     p = oct->data;
52     if ((ret = ASN1_item_d2i(NULL, &p, oct->length, it)) == NULL)
53         ASN1err(ASN1_F_ASN1_ITEM_UNPACK, ASN1_R_DECODE_ERROR);
54     return ret;
55 }