]> git.ipfire.org Git - thirdparty/openssl.git/blame - demos/cms/cms_sign.c
Run util/openssl-format-source -v -c .
[thirdparty/openssl.git] / demos / cms / cms_sign.c
CommitLineData
3b28bc99
DSH
1/* Simple S/MIME signing example */
2#include <openssl/pem.h>
3#include <openssl/cms.h>
4#include <openssl/err.h>
5
6int main(int argc, char **argv)
ae5c8664
MC
7{
8 BIO *in = NULL, *out = NULL, *tbio = NULL;
9 X509 *scert = NULL;
10 EVP_PKEY *skey = NULL;
11 CMS_ContentInfo *cms = NULL;
12 int ret = 1;
3b28bc99 13
ae5c8664
MC
14 /*
15 * For simple S/MIME signing use CMS_DETACHED. On OpenSSL 1.0.0 only: for
16 * streaming detached set CMS_DETACHED|CMS_STREAM for streaming
17 * non-detached set CMS_STREAM
18 */
19 int flags = CMS_DETACHED | CMS_STREAM;
3b28bc99 20
ae5c8664
MC
21 OpenSSL_add_all_algorithms();
22 ERR_load_crypto_strings();
3b28bc99 23
ae5c8664
MC
24 /* Read in signer certificate and private key */
25 tbio = BIO_new_file("signer.pem", "r");
3b28bc99 26
ae5c8664
MC
27 if (!tbio)
28 goto err;
3b28bc99 29
ae5c8664 30 scert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
3b28bc99 31
ae5c8664 32 BIO_reset(tbio);
3b28bc99 33
ae5c8664 34 skey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
3b28bc99 35
ae5c8664
MC
36 if (!scert || !skey)
37 goto err;
3b28bc99 38
ae5c8664 39 /* Open content being signed */
3b28bc99 40
ae5c8664 41 in = BIO_new_file("sign.txt", "r");
3b28bc99 42
ae5c8664
MC
43 if (!in)
44 goto err;
3b28bc99 45
ae5c8664
MC
46 /* Sign content */
47 cms = CMS_sign(scert, skey, NULL, in, flags);
3b28bc99 48
ae5c8664
MC
49 if (!cms)
50 goto err;
3b28bc99 51
ae5c8664
MC
52 out = BIO_new_file("smout.txt", "w");
53 if (!out)
54 goto err;
3b28bc99 55
ae5c8664
MC
56 if (!(flags & CMS_STREAM))
57 BIO_reset(in);
3b28bc99 58
ae5c8664
MC
59 /* Write out S/MIME message */
60 if (!SMIME_write_CMS(out, cms, in, flags))
61 goto err;
3b28bc99 62
ae5c8664 63 ret = 0;
3b28bc99 64
ae5c8664 65 err:
3b28bc99 66
ae5c8664
MC
67 if (ret) {
68 fprintf(stderr, "Error Signing Data\n");
69 ERR_print_errors_fp(stderr);
70 }
3b28bc99 71
ae5c8664
MC
72 if (cms)
73 CMS_ContentInfo_free(cms);
74 if (scert)
75 X509_free(scert);
76 if (skey)
77 EVP_PKEY_free(skey);
3b28bc99 78
ae5c8664
MC
79 if (in)
80 BIO_free(in);
81 if (out)
82 BIO_free(out);
83 if (tbio)
84 BIO_free(tbio);
3b28bc99 85
ae5c8664 86 return ret;
3b28bc99 87
ae5c8664 88}