Path: blob/main/crypto/openssl/demos/smime/smsign.c
34914 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 signing 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 *scert = NULL;18EVP_PKEY *skey = NULL;19PKCS7 *p7 = NULL;20int ret = EXIT_FAILURE;2122/*23* For simple S/MIME signing use PKCS7_DETACHED.24* for streaming detached set PKCS7_DETACHED|PKCS7_STREAM for streaming25* non-detached set PKCS7_STREAM26*/27int flags = PKCS7_DETACHED | PKCS7_STREAM;2829OpenSSL_add_all_algorithms();30ERR_load_crypto_strings();3132/* Read in signer certificate and private key */33tbio = BIO_new_file("signer.pem", "r");3435if (!tbio)36goto err;3738scert = PEM_read_bio_X509(tbio, NULL, 0, NULL);3940if (BIO_reset(tbio) < 0)41goto err;4243skey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);4445if (!scert || !skey)46goto err;4748/* Open content being signed */4950in = BIO_new_file("sign.txt", "r");5152if (!in)53goto err;5455/* Sign content */56p7 = PKCS7_sign(scert, skey, NULL, in, flags);5758if (!p7)59goto err;6061out = BIO_new_file("smout.txt", "w");62if (!out)63goto err;6465if (!(flags & PKCS7_STREAM)) {66if (BIO_reset(in) < 0)67goto err;68}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 Signing Data\n");80ERR_print_errors_fp(stderr);81}82PKCS7_free(p7);83X509_free(scert);84EVP_PKEY_free(skey);85BIO_free(in);86BIO_free(out);87BIO_free(tbio);8889return ret;90}919293