xref: /openssl/demos/cms/cms_sign.c (revision 86db9588)
1 /*
2  * Copyright 2008-2023 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9 
10 /* Simple S/MIME signing example */
11 #include <openssl/pem.h>
12 #include <openssl/cms.h>
13 #include <openssl/err.h>
14 
main(int argc,char ** argv)15 int main(int argc, char **argv)
16 {
17     BIO *in = NULL, *out = NULL, *tbio = NULL;
18     X509 *scert = NULL;
19     EVP_PKEY *skey = NULL;
20     CMS_ContentInfo *cms = NULL;
21     int ret = EXIT_FAILURE;
22 
23     /*
24      * For simple S/MIME signing use CMS_DETACHED. On OpenSSL 1.0.0 only: for
25      * streaming detached set CMS_DETACHED|CMS_STREAM for streaming
26      * non-detached set CMS_STREAM
27      */
28     int flags = CMS_DETACHED | CMS_STREAM;
29 
30     OpenSSL_add_all_algorithms();
31     ERR_load_crypto_strings();
32 
33     /* Read in signer certificate and private key */
34     tbio = BIO_new_file("signer.pem", "r");
35 
36     if (!tbio)
37         goto err;
38 
39     scert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
40 
41     if (BIO_reset(tbio) < 0)
42         goto err;
43 
44     skey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
45 
46     if (!scert || !skey)
47         goto err;
48 
49     /* Open content being signed */
50 
51     in = BIO_new_file("sign.txt", "r");
52 
53     if (!in)
54         goto err;
55 
56     /* Sign content */
57     cms = CMS_sign(scert, skey, NULL, in, flags);
58 
59     if (!cms)
60         goto err;
61 
62     out = BIO_new_file("smout.txt", "w");
63     if (!out)
64         goto err;
65 
66     if (!(flags & CMS_STREAM)) {
67         if (BIO_reset(in) < 0)
68             goto err;
69     }
70 
71     /* Write out S/MIME message */
72     if (!SMIME_write_CMS(out, cms, in, flags))
73         goto err;
74 
75     ret = EXIT_SUCCESS;
76  err:
77     if (ret != EXIT_SUCCESS) {
78         fprintf(stderr, "Error Signing Data\n");
79         ERR_print_errors_fp(stderr);
80     }
81 
82     CMS_ContentInfo_free(cms);
83     X509_free(scert);
84     EVP_PKEY_free(skey);
85     BIO_free(in);
86     BIO_free(out);
87     BIO_free(tbio);
88     return ret;
89 }
90