Fix demo comment: 0.9.9 never released.
[openssl.git] / demos / cms / cms_sign.c
1 /* Simple S/MIME signing example */
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;
10         EVP_PKEY *skey = NULL;
11         CMS_ContentInfo *cms = NULL;
12         int ret = 1;
13
14         /* For simple S/MIME signing use CMS_DETACHED.
15          * On OpenSSL 1.0.0 only:
16          * for streaming detached set CMS_DETACHED|CMS_STREAM
17          * for streaming non-detached set CMS_STREAM
18          */
19         int flags = CMS_DETACHED|CMS_STREAM;
20
21         OpenSSL_add_all_algorithms();
22         ERR_load_crypto_strings();
23
24         /* Read in signer certificate and private key */
25         tbio = BIO_new_file("signer.pem", "r");
26
27         if (!tbio)
28                 goto err;
29
30         scert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
31
32         BIO_reset(tbio);
33
34         skey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
35
36         if (!scert || !skey)
37                 goto err;
38
39         /* Open content being signed */
40
41         in = BIO_new_file("sign.txt", "r");
42
43         if (!in)
44                 goto err;
45
46         /* Sign content */
47         cms = CMS_sign(scert, skey, NULL, in, flags);
48
49         if (!cms)
50                 goto err;
51
52         out = BIO_new_file("smout.txt", "w");
53         if (!out)
54                 goto err;
55
56         if (!(flags & CMS_STREAM))
57                 BIO_reset(in);
58
59         /* Write out S/MIME message */
60         if (!SMIME_write_CMS(out, cms, in, flags))
61                 goto err;
62
63         ret = 0;
64
65         err:
66
67         if (ret)
68                 {
69                 fprintf(stderr, "Error Signing Data\n");
70                 ERR_print_errors_fp(stderr);
71                 }
72
73         if (cms)
74                 CMS_ContentInfo_free(cms);
75         if (scert)
76                 X509_free(scert);
77         if (skey)
78                 EVP_PKEY_free(skey);
79
80         if (in)
81                 BIO_free(in);
82         if (out)
83                 BIO_free(out);
84         if (tbio)
85                 BIO_free(tbio);
86
87         return ret;
88
89         }