fd9ea7e342db509de95360ae3fe5d3ed23c6ce4e
[openssl.git] / crypto / cms / cms_dd.c
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
10 #include "internal/cryptlib.h"
11 #include <openssl/asn1t.h>
12 #include <openssl/pem.h>
13 #include <openssl/x509v3.h>
14 #include <openssl/err.h>
15 #include <openssl/cms.h>
16 #include "cms_local.h"
17
18 /* CMS DigestedData Utilities */
19
20 CMS_ContentInfo *cms_DigestedData_create(const EVP_MD *md,
21                                          OSSL_LIB_CTX *libctx,
22                                          const char *propq)
23 {
24     CMS_ContentInfo *cms;
25     CMS_DigestedData *dd;
26
27     cms = CMS_ContentInfo_new_ex(libctx, propq);
28     if (cms == NULL)
29         return NULL;
30
31     dd = M_ASN1_new_of(CMS_DigestedData);
32
33     if (dd == NULL)
34         goto err;
35
36     cms->contentType = OBJ_nid2obj(NID_pkcs7_digest);
37     cms->d.digestedData = dd;
38
39     dd->version = 0;
40     dd->encapContentInfo->eContentType = OBJ_nid2obj(NID_pkcs7_data);
41
42     X509_ALGOR_set_md(dd->digestAlgorithm, md);
43
44     return cms;
45
46  err:
47     CMS_ContentInfo_free(cms);
48     return NULL;
49 }
50
51 BIO *cms_DigestedData_init_bio(const CMS_ContentInfo *cms)
52 {
53     CMS_DigestedData *dd = cms->d.digestedData;
54
55     return cms_DigestAlgorithm_init_bio(dd->digestAlgorithm, cms_get0_cmsctx(cms));
56 }
57
58 int cms_DigestedData_do_final(const CMS_ContentInfo *cms, BIO *chain, int verify)
59 {
60     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
61     unsigned char md[EVP_MAX_MD_SIZE];
62     unsigned int mdlen;
63     int r = 0;
64     CMS_DigestedData *dd;
65
66     if (mctx == NULL) {
67         CMSerr(CMS_F_CMS_DIGESTEDDATA_DO_FINAL, ERR_R_MALLOC_FAILURE);
68         goto err;
69     }
70
71     dd = cms->d.digestedData;
72
73     if (!cms_DigestAlgorithm_find_ctx(mctx, chain, dd->digestAlgorithm))
74         goto err;
75
76     if (EVP_DigestFinal_ex(mctx, md, &mdlen) <= 0)
77         goto err;
78
79     if (verify) {
80         if (mdlen != (unsigned int)dd->digest->length) {
81             CMSerr(CMS_F_CMS_DIGESTEDDATA_DO_FINAL,
82                    CMS_R_MESSAGEDIGEST_WRONG_LENGTH);
83             goto err;
84         }
85
86         if (memcmp(md, dd->digest->data, mdlen))
87             CMSerr(CMS_F_CMS_DIGESTEDDATA_DO_FINAL,
88                    CMS_R_VERIFICATION_FAILURE);
89         else
90             r = 1;
91     } else {
92         if (!ASN1_STRING_set(dd->digest, md, mdlen))
93             goto err;
94         r = 1;
95     }
96
97  err:
98     EVP_MD_CTX_free(mctx);
99
100     return r;
101
102 }