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