asn_pack.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. #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. ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB);
  19. return NULL;
  20. }
  21. } else {
  22. octmp = *oct;
  23. }
  24. ASN1_STRING_set0(octmp, NULL, 0);
  25. if ((octmp->length = ASN1_item_i2d(obj, &octmp->data, it)) <= 0) {
  26. ERR_raise(ERR_LIB_ASN1, ASN1_R_ENCODE_ERROR);
  27. goto err;
  28. }
  29. if (octmp->data == NULL) {
  30. ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB);
  31. goto err;
  32. }
  33. if (oct != NULL && *oct == NULL)
  34. *oct = octmp;
  35. return octmp;
  36. err:
  37. if (oct == NULL || *oct == NULL)
  38. ASN1_STRING_free(octmp);
  39. return NULL;
  40. }
  41. /* Extract an ASN1 object from an ASN1_STRING */
  42. void *ASN1_item_unpack(const ASN1_STRING *oct, const ASN1_ITEM *it)
  43. {
  44. const unsigned char *p;
  45. void *ret;
  46. p = oct->data;
  47. if ((ret = ASN1_item_d2i(NULL, &p, oct->length, it)) == NULL)
  48. ERR_raise(ERR_LIB_ASN1, ASN1_R_DECODE_ERROR);
  49. return ret;
  50. }
  51. void *ASN1_item_unpack_ex(const ASN1_STRING *oct, const ASN1_ITEM *it,
  52. OSSL_LIB_CTX *libctx, const char *propq)
  53. {
  54. const unsigned char *p;
  55. void *ret;
  56. p = oct->data;
  57. if ((ret = ASN1_item_d2i_ex(NULL, &p, oct->length, it,\
  58. libctx, propq)) == NULL)
  59. ERR_raise(ERR_LIB_ASN1, ASN1_R_DECODE_ERROR);
  60. return ret;
  61. }