]> git.ipfire.org Git - thirdparty/openssl.git/blame - demos/smime/smsign.c
free NULL cleanup 5a
[thirdparty/openssl.git] / demos / smime / smsign.c
CommitLineData
b2b2dafc
DSH
1/* Simple S/MIME signing example */
2#include <openssl/pem.h>
3#include <openssl/pkcs7.h>
4#include <openssl/err.h>
5
6int main(int argc, char **argv)
0f113f3e
MC
7{
8 BIO *in = NULL, *out = NULL, *tbio = NULL;
9 X509 *scert = NULL;
10 EVP_PKEY *skey = NULL;
11 PKCS7 *p7 = NULL;
12 int ret = 1;
b2b2dafc 13
0f113f3e
MC
14 /*
15 * For simple S/MIME signing use PKCS7_DETACHED. On OpenSSL 0.9.9 only:
16 * for streaming detached set PKCS7_DETACHED|PKCS7_STREAM for streaming
17 * non-detached set PKCS7_STREAM
18 */
19 int flags = PKCS7_DETACHED | PKCS7_STREAM;
b2b2dafc 20
0f113f3e
MC
21 OpenSSL_add_all_algorithms();
22 ERR_load_crypto_strings();
b2b2dafc 23
0f113f3e
MC
24 /* Read in signer certificate and private key */
25 tbio = BIO_new_file("signer.pem", "r");
b2b2dafc 26
0f113f3e
MC
27 if (!tbio)
28 goto err;
b2b2dafc 29
0f113f3e 30 scert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
b2b2dafc 31
0f113f3e 32 BIO_reset(tbio);
b2b2dafc 33
0f113f3e 34 skey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
b2b2dafc 35
0f113f3e
MC
36 if (!scert || !skey)
37 goto err;
b2b2dafc 38
0f113f3e 39 /* Open content being signed */
b2b2dafc 40
0f113f3e 41 in = BIO_new_file("sign.txt", "r");
b2b2dafc 42
0f113f3e
MC
43 if (!in)
44 goto err;
b2b2dafc 45
0f113f3e
MC
46 /* Sign content */
47 p7 = PKCS7_sign(scert, skey, NULL, in, flags);
b2b2dafc 48
0f113f3e
MC
49 if (!p7)
50 goto err;
b2b2dafc 51
0f113f3e
MC
52 out = BIO_new_file("smout.txt", "w");
53 if (!out)
54 goto err;
b2b2dafc 55
0f113f3e
MC
56 if (!(flags & PKCS7_STREAM))
57 BIO_reset(in);
b2b2dafc 58
0f113f3e
MC
59 /* Write out S/MIME message */
60 if (!SMIME_write_PKCS7(out, p7, in, flags))
61 goto err;
b2b2dafc 62
0f113f3e 63 ret = 0;
b2b2dafc 64
0f113f3e 65 err:
0f113f3e
MC
66 if (ret) {
67 fprintf(stderr, "Error Signing Data\n");
68 ERR_print_errors_fp(stderr);
69 }
e0e920b1 70 PKCS7_free(p7);
222561fe 71 X509_free(scert);
c5ba2d99 72 EVP_PKEY_free(skey);
ca3a82c3
RS
73 BIO_free(in);
74 BIO_free(out);
75 BIO_free(tbio);
b2b2dafc 76
0f113f3e 77 return ret;
b2b2dafc 78
0f113f3e 79}