1/* 2 * S/MIME detached data decrypt example: rarely done but should the need 3 * arise this is an example.... 4 */ 5#include <openssl/pem.h> 6#include <openssl/cms.h> 7#include <openssl/err.h> 8 9int main(int argc, char **argv) 10{ 11 BIO *in = NULL, *out = NULL, *tbio = NULL, *dcont = NULL; 12 X509 *rcert = NULL; 13 EVP_PKEY *rkey = NULL; 14 CMS_ContentInfo *cms = NULL; 15 int ret = 1; 16 17 OpenSSL_add_all_algorithms(); 18 ERR_load_crypto_strings(); 19 20 /* Read in recipient certificate and private key */ 21 tbio = BIO_new_file("signer.pem", "r"); 22 23 if (!tbio) 24 goto err; 25 26 rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL); 27 28 BIO_reset(tbio); 29 30 rkey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL); 31 32 if (!rcert || !rkey) 33 goto err; 34 35 /* Open PEM file containing enveloped data */ 36 37 in = BIO_new_file("smencr.pem", "r"); 38 39 if (!in) 40 goto err; 41 42 /* Parse PEM content */ 43 cms = PEM_read_bio_CMS(in, NULL, 0, NULL); 44 45 if (!cms) 46 goto err; 47 48 /* Open file containing detached content */ 49 dcont = BIO_new_file("smencr.out", "rb"); 50 51 if (!in) 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 (!CMS_decrypt(cms, rkey, rcert, dcont, out, 0)) 60 goto err; 61 62 ret = 0; 63 64 err: 65 66 if (ret) { 67 fprintf(stderr, "Error Decrypting Data\n"); 68 ERR_print_errors_fp(stderr); 69 } 70 71 if (cms) 72 CMS_ContentInfo_free(cms); 73 if (rcert) 74 X509_free(rcert); 75 if (rkey) 76 EVP_PKEY_free(rkey); 77 78 if (in) 79 BIO_free(in); 80 if (out) 81 BIO_free(out); 82 if (tbio) 83 BIO_free(tbio); 84 if (dcont) 85 BIO_free(dcont); 86 87 return ret; 88 89} 90