Path: blob/main/crypto/openssl/demos/cms/cms_denc.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/*10* S/MIME detached data encrypt example: rarely done but should the need11* arise this is an example....12*/13#include <openssl/pem.h>14#include <openssl/cms.h>15#include <openssl/err.h>1617int main(int argc, char **argv)18{19BIO *in = NULL, *out = NULL, *tbio = NULL, *dout = NULL;20X509 *rcert = NULL;21STACK_OF(X509) *recips = NULL;22CMS_ContentInfo *cms = NULL;23int ret = EXIT_FAILURE;2425int flags = CMS_STREAM | CMS_DETACHED;2627OpenSSL_add_all_algorithms();28ERR_load_crypto_strings();2930/* Read in recipient certificate */31tbio = BIO_new_file("signer.pem", "r");3233if (!tbio)34goto err;3536rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL);3738if (!rcert)39goto err;4041/* Create recipient STACK and add recipient cert to it */42recips = sk_X509_new_null();4344if (!recips || !sk_X509_push(recips, rcert))45goto err;4647/*48* OSSL_STACK_OF_X509_free() free up recipient STACK and its contents49* so set rcert to NULL so it isn't freed up twice.50*/51rcert = NULL;5253/* Open content being encrypted */5455in = BIO_new_file("encr.txt", "r");5657dout = BIO_new_file("smencr.out", "wb");5859if (!in)60goto err;6162/* encrypt content */63cms = CMS_encrypt(recips, in, EVP_des_ede3_cbc(), flags);6465if (!cms)66goto err;6768out = BIO_new_file("smencr.pem", "w");69if (!out)70goto err;7172if (!CMS_final(cms, in, dout, flags))73goto err;7475/* Write out CMS structure without content */76if (!PEM_write_bio_CMS(out, cms))77goto err;7879ret = EXIT_SUCCESS;80err:81if (ret != EXIT_SUCCESS) {82fprintf(stderr, "Error Encrypting Data\n");83ERR_print_errors_fp(stderr);84}8586CMS_ContentInfo_free(cms);87X509_free(rcert);88OSSL_STACK_OF_X509_free(recips);89BIO_free(in);90BIO_free(out);91BIO_free(dout);92BIO_free(tbio);93return ret;94}959697