xref: /openssl/demos/smime/smenc.c (revision 86db9588)
1 /*
2  * Copyright 2007-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 /* Simple S/MIME encrypt example */
11 #include <openssl/pem.h>
12 #include <openssl/pkcs7.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 *rcert = NULL;
19     STACK_OF(X509) *recips = NULL;
20     PKCS7 *p7 = NULL;
21     int ret = EXIT_FAILURE;
22 
23     /*
24      * for streaming set PKCS7_STREAM
25      */
26     int flags = PKCS7_STREAM;
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      * OSSL_STACK_OF_X509_free() will free up recipient STACK and its contents
50      * so set 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     if (!in)
59         goto err;
60 
61     /* encrypt content */
62     p7 = PKCS7_encrypt(recips, in, EVP_des_ede3_cbc(), flags);
63 
64     if (!p7)
65         goto err;
66 
67     out = BIO_new_file("smencr.txt", "w");
68     if (!out)
69         goto err;
70 
71     /* Write out S/MIME message */
72     if (!SMIME_write_PKCS7(out, p7, in, flags))
73         goto err;
74 
75     printf("Success\n");
76 
77     ret = EXIT_SUCCESS;
78  err:
79     if (ret != EXIT_SUCCESS) {
80         fprintf(stderr, "Error Encrypting Data\n");
81         ERR_print_errors_fp(stderr);
82     }
83     PKCS7_free(p7);
84     X509_free(rcert);
85     OSSL_STACK_OF_X509_free(recips);
86     BIO_free(in);
87     BIO_free(out);
88     BIO_free(tbio);
89     return ret;
90 }
91