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