xref: /openssl/demos/cms/cms_sign2.c (revision 86db9588)
1 /*
2  * Copyright 2008-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 
10 /* S/MIME signing example: 2 signers */
11 #include <openssl/pem.h>
12 #include <openssl/cms.h>
13 #include <openssl/err.h>
14 
main(int argc,char ** argv)15 int main(int argc, char **argv)
16 {
17     BIO *in = NULL, *out = NULL, *tbio = NULL;
18     X509 *scert = NULL, *scert2 = NULL;
19     EVP_PKEY *skey = NULL, *skey2 = NULL;
20     CMS_ContentInfo *cms = NULL;
21     int ret = EXIT_FAILURE;
22 
23     OpenSSL_add_all_algorithms();
24     ERR_load_crypto_strings();
25 
26     tbio = BIO_new_file("signer.pem", "r");
27 
28     if (!tbio)
29         goto err;
30 
31     scert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
32 
33     if (BIO_reset(tbio) < 0)
34         goto err;
35 
36     skey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
37 
38     BIO_free(tbio);
39 
40     tbio = BIO_new_file("signer2.pem", "r");
41 
42     if (!tbio)
43         goto err;
44 
45     scert2 = PEM_read_bio_X509(tbio, NULL, 0, NULL);
46 
47     if (BIO_reset(tbio) < 0)
48         goto err;
49 
50     skey2 = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
51 
52     if (!scert2 || !skey2)
53         goto err;
54 
55     in = BIO_new_file("sign.txt", "r");
56 
57     if (!in)
58         goto err;
59 
60     cms = CMS_sign(NULL, NULL, NULL, in, CMS_STREAM | CMS_PARTIAL);
61 
62     if (!cms)
63         goto err;
64 
65     /* Add each signer in turn */
66 
67     if (!CMS_add1_signer(cms, scert, skey, NULL, 0))
68         goto err;
69 
70     if (!CMS_add1_signer(cms, scert2, skey2, NULL, 0))
71         goto err;
72 
73     out = BIO_new_file("smout.txt", "w");
74     if (!out)
75         goto err;
76 
77     /* NB: content included and finalized by SMIME_write_CMS */
78 
79     if (!SMIME_write_CMS(out, cms, in, CMS_STREAM))
80         goto err;
81 
82     printf("Signing Successful\n");
83 
84     ret = EXIT_SUCCESS;
85  err:
86     if (ret != EXIT_SUCCESS) {
87         fprintf(stderr, "Error Signing Data\n");
88         ERR_print_errors_fp(stderr);
89     }
90 
91     CMS_ContentInfo_free(cms);
92     X509_free(scert);
93     EVP_PKEY_free(skey);
94     X509_free(scert2);
95     EVP_PKEY_free(skey2);
96     BIO_free(in);
97     BIO_free(out);
98     BIO_free(tbio);
99     return ret;
100 }
101