cms_dd.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /*
  2. * Copyright 2008-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 "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 *cms_DigestedData_create(const EVP_MD *md)
  18. {
  19. CMS_ContentInfo *cms;
  20. CMS_DigestedData *dd;
  21. cms = CMS_ContentInfo_new();
  22. if (cms == NULL)
  23. return NULL;
  24. dd = M_ASN1_new_of(CMS_DigestedData);
  25. if (dd == NULL)
  26. goto err;
  27. cms->contentType = OBJ_nid2obj(NID_pkcs7_digest);
  28. cms->d.digestedData = dd;
  29. dd->version = 0;
  30. dd->encapContentInfo->eContentType = OBJ_nid2obj(NID_pkcs7_data);
  31. X509_ALGOR_set_md(dd->digestAlgorithm, md);
  32. return cms;
  33. err:
  34. CMS_ContentInfo_free(cms);
  35. return NULL;
  36. }
  37. BIO *cms_DigestedData_init_bio(const CMS_ContentInfo *cms)
  38. {
  39. CMS_DigestedData *dd;
  40. dd = cms->d.digestedData;
  41. return cms_DigestAlgorithm_init_bio(dd->digestAlgorithm);
  42. }
  43. int cms_DigestedData_do_final(const CMS_ContentInfo *cms, BIO *chain, int verify)
  44. {
  45. EVP_MD_CTX *mctx = EVP_MD_CTX_new();
  46. unsigned char md[EVP_MAX_MD_SIZE];
  47. unsigned int mdlen;
  48. int r = 0;
  49. CMS_DigestedData *dd;
  50. if (mctx == NULL) {
  51. CMSerr(CMS_F_CMS_DIGESTEDDATA_DO_FINAL, ERR_R_MALLOC_FAILURE);
  52. goto err;
  53. }
  54. dd = cms->d.digestedData;
  55. if (!cms_DigestAlgorithm_find_ctx(mctx, chain, dd->digestAlgorithm))
  56. goto err;
  57. if (EVP_DigestFinal_ex(mctx, md, &mdlen) <= 0)
  58. goto err;
  59. if (verify) {
  60. if (mdlen != (unsigned int)dd->digest->length) {
  61. CMSerr(CMS_F_CMS_DIGESTEDDATA_DO_FINAL,
  62. CMS_R_MESSAGEDIGEST_WRONG_LENGTH);
  63. goto err;
  64. }
  65. if (memcmp(md, dd->digest->data, mdlen))
  66. CMSerr(CMS_F_CMS_DIGESTEDDATA_DO_FINAL,
  67. CMS_R_VERIFICATION_FAILURE);
  68. else
  69. r = 1;
  70. } else {
  71. if (!ASN1_STRING_set(dd->digest, md, mdlen))
  72. goto err;
  73. r = 1;
  74. }
  75. err:
  76. EVP_MD_CTX_free(mctx);
  77. return r;
  78. }