Path: blob/main/crypto/openssl/demos/smime/smenc.c
34889 views
/*1* Copyright 2007-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/pkcs7.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;19PKCS7 *p7 = NULL;20int ret = EXIT_FAILURE;2122/*23* for streaming set PKCS7_STREAM24*/25int flags = PKCS7_STREAM;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() will 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");5657if (!in)58goto err;5960/* encrypt content */61p7 = PKCS7_encrypt(recips, in, EVP_des_ede3_cbc(), flags);6263if (!p7)64goto err;6566out = BIO_new_file("smencr.txt", "w");67if (!out)68goto err;6970/* Write out S/MIME message */71if (!SMIME_write_PKCS7(out, p7, in, flags))72goto err;7374printf("Success\n");7576ret = EXIT_SUCCESS;77err:78if (ret != EXIT_SUCCESS) {79fprintf(stderr, "Error Encrypting Data\n");80ERR_print_errors_fp(stderr);81}82PKCS7_free(p7);83X509_free(rcert);84OSSL_STACK_OF_X509_free(recips);85BIO_free(in);86BIO_free(out);87BIO_free(tbio);88return ret;89}909192