]> git.ipfire.org Git - thirdparty/openssl.git/blame - demos/cms/cms_denc.c
free NULL cleanup 5a
[thirdparty/openssl.git] / demos / cms / cms_denc.c
CommitLineData
0f113f3e
MC
1/*
2 * S/MIME detached data encrypt example: rarely done but should the need
3 * arise this is an example....
17287562
DSH
4 */
5#include <openssl/pem.h>
6#include <openssl/cms.h>
7#include <openssl/err.h>
8
9int main(int argc, char **argv)
0f113f3e
MC
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;
17287562 16
0f113f3e 17 int flags = CMS_STREAM | CMS_DETACHED;
17287562 18
0f113f3e
MC
19 OpenSSL_add_all_algorithms();
20 ERR_load_crypto_strings();
17287562 21
0f113f3e
MC
22 /* Read in recipient certificate */
23 tbio = BIO_new_file("signer.pem", "r");
17287562 24
0f113f3e
MC
25 if (!tbio)
26 goto err;
17287562 27
0f113f3e 28 rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
17287562 29
0f113f3e
MC
30 if (!rcert)
31 goto err;
17287562 32
0f113f3e
MC
33 /* Create recipient STACK and add recipient cert to it */
34 recips = sk_X509_new_null();
17287562 35
0f113f3e
MC
36 if (!recips || !sk_X509_push(recips, rcert))
37 goto err;
17287562 38
0f113f3e
MC
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;
17287562 44
0f113f3e 45 /* Open content being encrypted */
17287562 46
0f113f3e 47 in = BIO_new_file("encr.txt", "r");
17287562 48
0f113f3e 49 dout = BIO_new_file("smencr.out", "wb");
17287562 50
0f113f3e
MC
51 if (!in)
52 goto err;
17287562 53
0f113f3e
MC
54 /* encrypt content */
55 cms = CMS_encrypt(recips, in, EVP_des_ede3_cbc(), flags);
17287562 56
0f113f3e
MC
57 if (!cms)
58 goto err;
17287562 59
0f113f3e
MC
60 out = BIO_new_file("smencr.pem", "w");
61 if (!out)
62 goto err;
17287562 63
0f113f3e
MC
64 if (!CMS_final(cms, in, dout, flags))
65 goto err;
17287562 66
0f113f3e
MC
67 /* Write out CMS structure without content */
68 if (!PEM_write_bio_CMS(out, cms))
69 goto err;
17287562 70
0f113f3e 71 ret = 0;
17287562 72
0f113f3e 73 err:
17287562 74
0f113f3e
MC
75 if (ret) {
76 fprintf(stderr, "Error Encrypting Data\n");
77 ERR_print_errors_fp(stderr);
78 }
17287562 79
0f113f3e
MC
80 if (cms)
81 CMS_ContentInfo_free(cms);
222561fe
RS
82 X509_free(rcert);
83 sk_X509_pop_free(recips, X509_free);
17287562 84
ca3a82c3
RS
85 BIO_free(in);
86 BIO_free(out);
87 BIO_free(dout);
88 BIO_free(tbio);
17287562 89
0f113f3e 90 return ret;
17287562 91
0f113f3e 92}