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 decryption 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 *rcert = NULL;
19 EVP_PKEY *rkey = NULL;
20 CMS_ContentInfo *cms = NULL;
21 int ret = EXIT_FAILURE;
22
23 OpenSSL_add_all_algorithms();
24 ERR_load_crypto_strings();
25
26 /* Read in recipient certificate and private key */
27 tbio = BIO_new_file("signer.pem", "r");
28
29 if (!tbio)
30 goto err;
31
32 rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
33
34 if (BIO_reset(tbio) < 0)
35 goto err;
36
37 rkey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
38
39 if (!rcert || !rkey)
40 goto err;
41
42 /* Open S/MIME message to decrypt */
43
44 in = BIO_new_file("smencr.txt", "r");
45
46 if (!in)
47 goto err;
48
49 /* Parse message */
50 cms = SMIME_read_CMS(in, NULL);
51
52 if (!cms)
53 goto err;
54
55 out = BIO_new_file("decout.txt", "w");
56 if (!out)
57 goto err;
58
59 /* Decrypt S/MIME message */
60 if (!CMS_decrypt(cms, rkey, rcert, NULL, out, 0))
61 goto err;
62
63 printf("Decryption Successful\n");
64
65 ret = EXIT_SUCCESS;
66
67 err:
68 if (ret != EXIT_SUCCESS) {
69 fprintf(stderr, "Error Decrypting Data\n");
70 ERR_print_errors_fp(stderr);
71 }
72
73 CMS_ContentInfo_free(cms);
74 X509_free(rcert);
75 EVP_PKEY_free(rkey);
76 BIO_free(in);
77 BIO_free(out);
78 BIO_free(tbio);
79 return ret;
80 }
81