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