2b7f45b294a2b12439e069e8e81b0ba6a84841bd
[openssl.git] / demos / smime / smsign2.c
1 /*
2  * Copyright 2007-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (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 /* S/MIME signing example: 2 signers. OpenSSL 0.9.9 only */
11 #include <openssl/pem.h>
12 #include <openssl/pkcs7.h>
13 #include <openssl/err.h>
14
15 int main(int argc, char **argv)
16 {
17     BIO *in = NULL, *out = NULL, *tbio = NULL;
18     X509 *scert = NULL, *scert2 = NULL;
19     EVP_PKEY *skey = NULL, *skey2 = NULL;
20     PKCS7 *p7 = NULL;
21     int ret = 1;
22
23     OpenSSL_add_all_algorithms();
24     ERR_load_crypto_strings();
25
26     tbio = BIO_new_file("signer.pem", "r");
27
28     if (!tbio)
29         goto err;
30
31     scert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
32
33     BIO_reset(tbio);
34
35     skey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
36
37     BIO_free(tbio);
38
39     tbio = BIO_new_file("signer2.pem", "r");
40
41     if (!tbio)
42         goto err;
43
44     scert2 = PEM_read_bio_X509(tbio, NULL, 0, NULL);
45
46     BIO_reset(tbio);
47
48     skey2 = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
49
50     if (!scert2 || !skey2)
51         goto err;
52
53     in = BIO_new_file("sign.txt", "r");
54
55     if (!in)
56         goto err;
57
58     p7 = PKCS7_sign(NULL, NULL, NULL, in, PKCS7_STREAM | PKCS7_PARTIAL);
59
60     if (!p7)
61         goto err;
62
63     /* Add each signer in turn */
64
65     if (!PKCS7_sign_add_signer(p7, scert, skey, NULL, 0))
66         goto err;
67
68     if (!PKCS7_sign_add_signer(p7, scert2, skey2, NULL, 0))
69         goto err;
70
71     out = BIO_new_file("smout.txt", "w");
72     if (!out)
73         goto err;
74
75     /* NB: content included and finalized by SMIME_write_PKCS7 */
76
77     if (!SMIME_write_PKCS7(out, p7, in, PKCS7_STREAM))
78         goto err;
79
80     ret = 0;
81
82  err:
83     if (ret) {
84         fprintf(stderr, "Error Signing Data\n");
85         ERR_print_errors_fp(stderr);
86     }
87     PKCS7_free(p7);
88     X509_free(scert);
89     EVP_PKEY_free(skey);
90     X509_free(scert2);
91     EVP_PKEY_free(skey2);
92     BIO_free(in);
93     BIO_free(out);
94     BIO_free(tbio);
95     return ret;
96 }