asn_pack.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Copyright 1999-2016 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. #include <stdio.h>
  10. #include "internal/cryptlib.h"
  11. #include <openssl/asn1.h>
  12. /* ASN1 packing and unpacking functions */
  13. ASN1_STRING *ASN1_item_pack(void *obj, const ASN1_ITEM *it, ASN1_STRING **oct)
  14. {
  15. ASN1_STRING *octmp;
  16. if (oct == NULL || *oct == NULL) {
  17. if ((octmp = ASN1_STRING_new()) == NULL) {
  18. ASN1err(ASN1_F_ASN1_ITEM_PACK, ERR_R_MALLOC_FAILURE);
  19. return NULL;
  20. }
  21. } else {
  22. octmp = *oct;
  23. }
  24. OPENSSL_free(octmp->data);
  25. octmp->data = NULL;
  26. if ((octmp->length = ASN1_item_i2d(obj, &octmp->data, it)) == 0) {
  27. ASN1err(ASN1_F_ASN1_ITEM_PACK, ASN1_R_ENCODE_ERROR);
  28. goto err;
  29. }
  30. if (octmp->data == NULL) {
  31. ASN1err(ASN1_F_ASN1_ITEM_PACK, ERR_R_MALLOC_FAILURE);
  32. goto err;
  33. }
  34. if (oct != NULL && *oct == NULL)
  35. *oct = octmp;
  36. return octmp;
  37. err:
  38. if (oct == NULL || *oct == NULL)
  39. ASN1_STRING_free(octmp);
  40. return NULL;
  41. }
  42. /* Extract an ASN1 object from an ASN1_STRING */
  43. void *ASN1_item_unpack(const ASN1_STRING *oct, const ASN1_ITEM *it)
  44. {
  45. const unsigned char *p;
  46. void *ret;
  47. p = oct->data;
  48. if ((ret = ASN1_item_d2i(NULL, &p, oct->length, it)) == NULL)
  49. ASN1err(ASN1_F_ASN1_ITEM_UNPACK, ASN1_R_DECODE_ERROR);
  50. return ret;
  51. }