cms_denc.c 2.2 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
/*
 * S/MIME detached data encrypt example: rarely done but should the need
 * arise this is an example....
13 14 15 16 17 18
 */
#include <openssl/pem.h>
#include <openssl/cms.h>
#include <openssl/err.h>

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

26
    int flags = CMS_STREAM | CMS_DETACHED;
27

28 29
    OpenSSL_add_all_algorithms();
    ERR_load_crypto_strings();
30

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

34 35
    if (!tbio)
        goto err;
36

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

39 40
    if (!rcert)
        goto err;
41

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

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

48 49 50 51 52
    /*
     * 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;
53

54
    /* Open content being encrypted */
55

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

58
    dout = BIO_new_file("smencr.out", "wb");
59

60 61
    if (!in)
        goto err;
62

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

66 67
    if (!cms)
        goto err;
68

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

73 74
    if (!CMS_final(cms, in, dout, flags))
        goto err;
75

76 77 78
    /* Write out CMS structure without content */
    if (!PEM_write_bio_CMS(out, cms))
        goto err;
79

80
    ret = 0;
81

82
 err:
83

84 85 86 87
    if (ret) {
        fprintf(stderr, "Error Encrypting Data\n");
        ERR_print_errors_fp(stderr);
    }
88

R
Rich Salz 已提交
89
    CMS_ContentInfo_free(cms);
R
Rich Salz 已提交
90 91
    X509_free(rcert);
    sk_X509_pop_free(recips, X509_free);
R
Rich Salz 已提交
92 93 94 95
    BIO_free(in);
    BIO_free(out);
    BIO_free(dout);
    BIO_free(tbio);
96 97
    return ret;
}