Path: blob/main/crypto/openssl/demos/cms/cms_sign.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 signing 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 *scert = NULL;18EVP_PKEY *skey = NULL;19CMS_ContentInfo *cms = NULL;20int ret = EXIT_FAILURE;2122/*23* For simple S/MIME signing use CMS_DETACHED. On OpenSSL 1.0.0 only: for24* streaming detached set CMS_DETACHED|CMS_STREAM for streaming25* non-detached set CMS_STREAM26*/27int flags = CMS_DETACHED | CMS_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 */56cms = CMS_sign(scert, skey, NULL, in, flags);5758if (!cms)59goto err;6061out = BIO_new_file("smout.txt", "w");62if (!out)63goto err;6465if (!(flags & CMS_STREAM)) {66if (BIO_reset(in) < 0)67goto err;68}6970/* Write out S/MIME message */71if (!SMIME_write_CMS(out, cms, in, flags))72goto err;7374ret = EXIT_SUCCESS;75err:76if (ret != EXIT_SUCCESS) {77fprintf(stderr, "Error Signing Data\n");78ERR_print_errors_fp(stderr);79}8081CMS_ContentInfo_free(cms);82X509_free(scert);83EVP_PKEY_free(skey);84BIO_free(in);85BIO_free(out);86BIO_free(tbio);87return ret;88}899091