yuezonghe | 824eb0c | 2024-06-27 02:32:26 -0700 | [diff] [blame] | 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 | /* Simple S/MIME signing example */ |
| 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 *rcert = NULL; |
| 19 | EVP_PKEY *rkey = NULL; |
| 20 | PKCS7 *p7 = NULL; |
| 21 | int ret = 1; |
| 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 | BIO_reset(tbio); |
| 35 | |
| 36 | rkey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL); |
| 37 | |
| 38 | if (!rcert || !rkey) |
| 39 | goto err; |
| 40 | |
| 41 | /* Open content being signed */ |
| 42 | |
| 43 | in = BIO_new_file("smencr.txt", "r"); |
| 44 | |
| 45 | if (!in) |
| 46 | goto err; |
| 47 | |
| 48 | /* Sign content */ |
| 49 | p7 = SMIME_read_PKCS7(in, NULL); |
| 50 | |
| 51 | if (!p7) |
| 52 | goto err; |
| 53 | |
| 54 | out = BIO_new_file("encrout.txt", "w"); |
| 55 | if (!out) |
| 56 | goto err; |
| 57 | |
| 58 | /* Decrypt S/MIME message */ |
| 59 | if (!PKCS7_decrypt(p7, rkey, rcert, out, 0)) |
| 60 | goto err; |
| 61 | |
| 62 | ret = 0; |
| 63 | |
| 64 | err: |
| 65 | if (ret) { |
| 66 | fprintf(stderr, "Error Signing Data\n"); |
| 67 | ERR_print_errors_fp(stderr); |
| 68 | } |
| 69 | PKCS7_free(p7); |
| 70 | X509_free(rcert); |
| 71 | EVP_PKEY_free(rkey); |
| 72 | BIO_free(in); |
| 73 | BIO_free(out); |
| 74 | BIO_free(tbio); |
| 75 | |
| 76 | return ret; |
| 77 | |
| 78 | } |