cms_dd.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /*
  2. * Copyright 2008-2021 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 "internal/cryptlib.h"
  10. #include <openssl/asn1t.h>
  11. #include <openssl/pem.h>
  12. #include <openssl/x509v3.h>
  13. #include <openssl/err.h>
  14. #include <openssl/cms.h>
  15. #include "cms_local.h"
  16. /* CMS DigestedData Utilities */
  17. CMS_ContentInfo *ossl_cms_DigestedData_create(const EVP_MD *md,
  18. OSSL_LIB_CTX *libctx,
  19. const char *propq)
  20. {
  21. CMS_ContentInfo *cms;
  22. CMS_DigestedData *dd;
  23. cms = CMS_ContentInfo_new_ex(libctx, propq);
  24. if (cms == NULL)
  25. return NULL;
  26. dd = M_ASN1_new_of(CMS_DigestedData);
  27. if (dd == NULL)
  28. goto err;
  29. cms->contentType = OBJ_nid2obj(NID_pkcs7_digest);
  30. cms->d.digestedData = dd;
  31. dd->version = 0;
  32. dd->encapContentInfo->eContentType = OBJ_nid2obj(NID_pkcs7_data);
  33. X509_ALGOR_set_md(dd->digestAlgorithm, md);
  34. return cms;
  35. err:
  36. CMS_ContentInfo_free(cms);
  37. return NULL;
  38. }
  39. BIO *ossl_cms_DigestedData_init_bio(const CMS_ContentInfo *cms)
  40. {
  41. CMS_DigestedData *dd = cms->d.digestedData;
  42. return ossl_cms_DigestAlgorithm_init_bio(dd->digestAlgorithm,
  43. ossl_cms_get0_cmsctx(cms));
  44. }
  45. int ossl_cms_DigestedData_do_final(const CMS_ContentInfo *cms, BIO *chain,
  46. int verify)
  47. {
  48. EVP_MD_CTX *mctx = EVP_MD_CTX_new();
  49. unsigned char md[EVP_MAX_MD_SIZE];
  50. unsigned int mdlen;
  51. int r = 0;
  52. CMS_DigestedData *dd;
  53. if (mctx == NULL) {
  54. ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE);
  55. goto err;
  56. }
  57. dd = cms->d.digestedData;
  58. if (!ossl_cms_DigestAlgorithm_find_ctx(mctx, chain, dd->digestAlgorithm))
  59. goto err;
  60. if (EVP_DigestFinal_ex(mctx, md, &mdlen) <= 0)
  61. goto err;
  62. if (verify) {
  63. if (mdlen != (unsigned int)dd->digest->length) {
  64. ERR_raise(ERR_LIB_CMS, CMS_R_MESSAGEDIGEST_WRONG_LENGTH);
  65. goto err;
  66. }
  67. if (memcmp(md, dd->digest->data, mdlen))
  68. ERR_raise(ERR_LIB_CMS, CMS_R_VERIFICATION_FAILURE);
  69. else
  70. r = 1;
  71. } else {
  72. if (!ASN1_STRING_set(dd->digest, md, mdlen))
  73. goto err;
  74. r = 1;
  75. }
  76. err:
  77. EVP_MD_CTX_free(mctx);
  78. return r;
  79. }