]>
Commit | Line | Data |
---|---|---|
3b28bc99 DSH |
1 | /* Simple S/MIME encrypt example */ |
2 | #include <openssl/pem.h> | |
3 | #include <openssl/cms.h> | |
4 | #include <openssl/err.h> | |
5 | ||
6 | int main(int argc, char **argv) | |
0f113f3e MC |
7 | { |
8 | BIO *in = NULL, *out = NULL, *tbio = NULL; | |
9 | X509 *rcert = NULL; | |
10 | STACK_OF(X509) *recips = NULL; | |
11 | CMS_ContentInfo *cms = NULL; | |
12 | int ret = 1; | |
3b28bc99 | 13 | |
0f113f3e MC |
14 | /* |
15 | * On OpenSSL 1.0.0 and later only: | |
16 | * for streaming set CMS_STREAM | |
17 | */ | |
18 | int flags = CMS_STREAM; | |
3b28bc99 | 19 | |
0f113f3e MC |
20 | OpenSSL_add_all_algorithms(); |
21 | ERR_load_crypto_strings(); | |
3b28bc99 | 22 | |
0f113f3e MC |
23 | /* Read in recipient certificate */ |
24 | tbio = BIO_new_file("signer.pem", "r"); | |
3b28bc99 | 25 | |
0f113f3e MC |
26 | if (!tbio) |
27 | goto err; | |
3b28bc99 | 28 | |
0f113f3e | 29 | rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL); |
3b28bc99 | 30 | |
0f113f3e MC |
31 | if (!rcert) |
32 | goto err; | |
3b28bc99 | 33 | |
0f113f3e MC |
34 | /* Create recipient STACK and add recipient cert to it */ |
35 | recips = sk_X509_new_null(); | |
3b28bc99 | 36 | |
0f113f3e MC |
37 | if (!recips || !sk_X509_push(recips, rcert)) |
38 | goto err; | |
3b28bc99 | 39 | |
0f113f3e MC |
40 | /* |
41 | * sk_X509_pop_free will free up recipient STACK and its contents so set | |
42 | * rcert to NULL so it isn't freed up twice. | |
43 | */ | |
44 | rcert = NULL; | |
3b28bc99 | 45 | |
0f113f3e | 46 | /* Open content being encrypted */ |
3b28bc99 | 47 | |
0f113f3e | 48 | in = BIO_new_file("encr.txt", "r"); |
3b28bc99 | 49 | |
0f113f3e MC |
50 | if (!in) |
51 | goto err; | |
3b28bc99 | 52 | |
0f113f3e MC |
53 | /* encrypt content */ |
54 | cms = CMS_encrypt(recips, in, EVP_des_ede3_cbc(), flags); | |
3b28bc99 | 55 | |
0f113f3e MC |
56 | if (!cms) |
57 | goto err; | |
3b28bc99 | 58 | |
0f113f3e MC |
59 | out = BIO_new_file("smencr.txt", "w"); |
60 | if (!out) | |
61 | goto err; | |
3b28bc99 | 62 | |
0f113f3e MC |
63 | /* Write out S/MIME message */ |
64 | if (!SMIME_write_CMS(out, cms, in, flags)) | |
65 | goto err; | |
3b28bc99 | 66 | |
0f113f3e | 67 | ret = 0; |
3b28bc99 | 68 | |
0f113f3e | 69 | err: |
3b28bc99 | 70 | |
0f113f3e MC |
71 | if (ret) { |
72 | fprintf(stderr, "Error Encrypting Data\n"); | |
73 | ERR_print_errors_fp(stderr); | |
74 | } | |
3b28bc99 | 75 | |
25aaa98a | 76 | CMS_ContentInfo_free(cms); |
222561fe RS |
77 | X509_free(rcert); |
78 | sk_X509_pop_free(recips, X509_free); | |
ca3a82c3 RS |
79 | BIO_free(in); |
80 | BIO_free(out); | |
81 | BIO_free(tbio); | |
0f113f3e | 82 | return ret; |
0f113f3e | 83 | } |