cms_denc.c 1.9 KB
Newer Older
1 2 3
/*
 * S/MIME detached data encrypt example: rarely done but should the need
 * arise this is an example....
4 5 6 7 8 9
 */
#include <openssl/pem.h>
#include <openssl/cms.h>
#include <openssl/err.h>

int main(int argc, char **argv)
10 11 12 13 14 15
{
    BIO *in = NULL, *out = NULL, *tbio = NULL, *dout = NULL;
    X509 *rcert = NULL;
    STACK_OF(X509) *recips = NULL;
    CMS_ContentInfo *cms = NULL;
    int ret = 1;
16

17
    int flags = CMS_STREAM | CMS_DETACHED;
18

19 20
    OpenSSL_add_all_algorithms();
    ERR_load_crypto_strings();
21

22 23
    /* Read in recipient certificate */
    tbio = BIO_new_file("signer.pem", "r");
24

25 26
    if (!tbio)
        goto err;
27

28
    rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
29

30 31
    if (!rcert)
        goto err;
32

33 34
    /* Create recipient STACK and add recipient cert to it */
    recips = sk_X509_new_null();
35

36 37
    if (!recips || !sk_X509_push(recips, rcert))
        goto err;
38

39 40 41 42 43
    /*
     * 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;
44

45
    /* Open content being encrypted */
46

47
    in = BIO_new_file("encr.txt", "r");
48

49
    dout = BIO_new_file("smencr.out", "wb");
50

51 52
    if (!in)
        goto err;
53

54 55
    /* encrypt content */
    cms = CMS_encrypt(recips, in, EVP_des_ede3_cbc(), flags);
56

57 58
    if (!cms)
        goto err;
59

60 61 62
    out = BIO_new_file("smencr.pem", "w");
    if (!out)
        goto err;
63

64 65
    if (!CMS_final(cms, in, dout, flags))
        goto err;
66

67 68 69
    /* Write out CMS structure without content */
    if (!PEM_write_bio_CMS(out, cms))
        goto err;
70

71
    ret = 0;
72

73
 err:
74

75 76 77 78
    if (ret) {
        fprintf(stderr, "Error Encrypting Data\n");
        ERR_print_errors_fp(stderr);
    }
79

80 81
    if (cms)
        CMS_ContentInfo_free(cms);
R
Rich Salz 已提交
82 83
    X509_free(rcert);
    sk_X509_pop_free(recips, X509_free);
84

R
Rich Salz 已提交
85 86 87 88
    BIO_free(in);
    BIO_free(out);
    BIO_free(dout);
    BIO_free(tbio);
89

90
    return ret;
91

92
}