Path: blob/main/crypto/openssl/demos/cms/cms_enc.c
34879 views
/*1* Copyright 2008-2023 The OpenSSL Project Authors. All Rights Reserved.2*3* Licensed under the Apache License 2.0 (the "License"). You may not use4* this file except in compliance with the License. You can obtain a copy5* in the file LICENSE in the source distribution or at6* https://www.openssl.org/source/license.html7*/89/* Simple S/MIME encrypt example */10#include <openssl/pem.h>11#include <openssl/cms.h>12#include <openssl/err.h>1314int main(int argc, char **argv)15{16BIO *in = NULL, *out = NULL, *tbio = NULL;17X509 *rcert = NULL;18STACK_OF(X509) *recips = NULL;19CMS_ContentInfo *cms = NULL;20int ret = EXIT_FAILURE;2122/*23* On OpenSSL 1.0.0 and later only:24* for streaming set CMS_STREAM25*/26int flags = CMS_STREAM;2728OpenSSL_add_all_algorithms();29ERR_load_crypto_strings();3031/* Read in recipient certificate */32tbio = BIO_new_file("signer.pem", "r");3334if (!tbio)35goto err;3637rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL);3839if (!rcert)40goto err;4142/* Create recipient STACK and add recipient cert to it */43recips = sk_X509_new_null();4445if (!recips || !sk_X509_push(recips, rcert))46goto err;4748/*49* OSSL_STACK_OF_X509_free() will free up recipient STACK and its contents50* so set rcert to NULL so it isn't freed up twice.51*/52rcert = NULL;5354/* Open content being encrypted */5556in = BIO_new_file("encr.txt", "r");5758if (!in)59goto err;6061/* encrypt content */62cms = CMS_encrypt(recips, in, EVP_des_ede3_cbc(), flags);6364if (!cms)65goto err;6667out = BIO_new_file("smencr.txt", "w");68if (!out)69goto err;7071/* Write out S/MIME message */72if (!SMIME_write_CMS(out, cms, in, flags))73goto err;7475printf("Encryption Successful\n");7677ret = EXIT_SUCCESS;78err:79if (ret != EXIT_SUCCESS) {80fprintf(stderr, "Error Encrypting Data\n");81ERR_print_errors_fp(stderr);82}8384CMS_ContentInfo_free(cms);85X509_free(rcert);86OSSL_STACK_OF_X509_free(recips);87BIO_free(in);88BIO_free(out);89BIO_free(tbio);90return ret;91}929394