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