852671771c7aecff7bec1c9d19e2ab0e1e8c7f8f
[openssl.git] / demos / cms / cms_denc.c
1 /*
2  * S/MIME detached data encrypt example: rarely done but should the need
3  * arise this is an example....
4  */
5 #include <openssl/pem.h>
6 #include <openssl/cms.h>
7 #include <openssl/err.h>
8
9 int main(int argc, char **argv)
10 {
11     BIO *in = NULL, *out = NULL, *tbio = NULL, *dout = NULL;
12     X509 *rcert = NULL;
13     STACK_OF(X509) *recips = NULL;
14     CMS_ContentInfo *cms = NULL;
15     int ret = 1;
16
17     int flags = CMS_STREAM | CMS_DETACHED;
18
19     OpenSSL_add_all_algorithms();
20     ERR_load_crypto_strings();
21
22     /* Read in recipient certificate */
23     tbio = BIO_new_file("signer.pem", "r");
24
25     if (!tbio)
26         goto err;
27
28     rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
29
30     if (!rcert)
31         goto err;
32
33     /* Create recipient STACK and add recipient cert to it */
34     recips = sk_X509_new_null();
35
36     if (!recips || !sk_X509_push(recips, rcert))
37         goto err;
38
39     /*
40      * sk_X509_pop_free will free up recipient STACK and its contents so set
41      * rcert to NULL so it isn't freed up twice.
42      */
43     rcert = NULL;
44
45     /* Open content being encrypted */
46
47     in = BIO_new_file("encr.txt", "r");
48
49     dout = BIO_new_file("smencr.out", "wb");
50
51     if (!in)
52         goto err;
53
54     /* encrypt content */
55     cms = CMS_encrypt(recips, in, EVP_des_ede3_cbc(), flags);
56
57     if (!cms)
58         goto err;
59
60     out = BIO_new_file("smencr.pem", "w");
61     if (!out)
62         goto err;
63
64     if (!CMS_final(cms, in, dout, flags))
65         goto err;
66
67     /* Write out CMS structure without content */
68     if (!PEM_write_bio_CMS(out, cms))
69         goto err;
70
71     ret = 0;
72
73  err:
74
75     if (ret) {
76         fprintf(stderr, "Error Encrypting Data\n");
77         ERR_print_errors_fp(stderr);
78     }
79
80     if (cms)
81         CMS_ContentInfo_free(cms);
82     if (rcert)
83         X509_free(rcert);
84     if (recips)
85         sk_X509_pop_free(recips, X509_free);
86
87     BIO_free(in);
88     BIO_free(out);
89     BIO_free(dout);
90     BIO_free(tbio);
91
92     return ret;
93
94 }