cms_enc.c 2.0 KB
Newer Older
R
Rich Salz 已提交
1 2 3 4 5 6 7 8 9
/*
 * Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved.
 *
 * Licensed under the OpenSSL license (the "License").  You may not use
 * this file except in compliance with the License.  You can obtain a copy
 * in the file LICENSE in the source distribution or at
 * https://www.openssl.org/source/license.html
 */

10 11 12 13 14 15
/* Simple S/MIME encrypt example */
#include <openssl/pem.h>
#include <openssl/cms.h>
#include <openssl/err.h>

int main(int argc, char **argv)
16 17 18 19 20 21
{
    BIO *in = NULL, *out = NULL, *tbio = NULL;
    X509 *rcert = NULL;
    STACK_OF(X509) *recips = NULL;
    CMS_ContentInfo *cms = NULL;
    int ret = 1;
22

23 24 25 26 27
    /*
     * On OpenSSL 1.0.0 and later only:
     * for streaming set CMS_STREAM
     */
    int flags = CMS_STREAM;
28

29 30
    OpenSSL_add_all_algorithms();
    ERR_load_crypto_strings();
31

32 33
    /* Read in recipient certificate */
    tbio = BIO_new_file("signer.pem", "r");
34

35 36
    if (!tbio)
        goto err;
37

38
    rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
39

40 41
    if (!rcert)
        goto err;
42

43 44
    /* Create recipient STACK and add recipient cert to it */
    recips = sk_X509_new_null();
45

46 47
    if (!recips || !sk_X509_push(recips, rcert))
        goto err;
48

49 50 51 52 53
    /*
     * sk_X509_pop_free will free up recipient STACK and its contents so set
     * rcert to NULL so it isn't freed up twice.
     */
    rcert = NULL;
54

55
    /* Open content being encrypted */
56

57
    in = BIO_new_file("encr.txt", "r");
58

59 60
    if (!in)
        goto err;
61

62 63
    /* encrypt content */
    cms = CMS_encrypt(recips, in, EVP_des_ede3_cbc(), flags);
64

65 66
    if (!cms)
        goto err;
67

68 69 70
    out = BIO_new_file("smencr.txt", "w");
    if (!out)
        goto err;
71

72 73 74
    /* Write out S/MIME message */
    if (!SMIME_write_CMS(out, cms, in, flags))
        goto err;
75

76
    ret = 0;
77

78
 err:
79

80 81 82 83
    if (ret) {
        fprintf(stderr, "Error Encrypting Data\n");
        ERR_print_errors_fp(stderr);
    }
84

R
Rich Salz 已提交
85
    CMS_ContentInfo_free(cms);
R
Rich Salz 已提交
86 87
    X509_free(rcert);
    sk_X509_pop_free(recips, X509_free);
R
Rich Salz 已提交
88 89 90
    BIO_free(in);
    BIO_free(out);
    BIO_free(tbio);
91 92
    return ret;
}