title: openssl decrypt a signed & encrypted message
body: <p>I am trying out a small example program to decrypt a message that has been signed and then encrypted using openSSL. It works well in the command line. However upon trying out the code after modifying the code in the 'demos' folder of OpenSSL, the decryption fails</p>
  
  <p>Here is the decryption code:</p>
  
  <pre><code>   int decrypt_smime(){
  
          BIO *in = NULL, *out = NULL, *tbio = NULL;
          X509 *rcert = NULL;
          EVP_PKEY *rkey = NULL;
          //PKCS7 *cms = NULL;
          CMS_ContentInfo *cms = NULL;
          int ret = 1;
          int flags = CMS_STREAM;
          OpenSSL_add_all_algorithms();
          ERR_load_crypto_strings();
          printf("decrypt...\n");
          /* Read in recipient certificate and private key */
          tbio = BIO_new_file("signer.pem", "r");
  
          if (!tbio)
              goto err;
  
          rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
  
          BIO_reset(tbio);
  
          rkey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
  
          if (!rcert || !rkey)
              goto err;
          printf("decrypt...\n");
          /* Open S/MIME message to decrypt */
  
          in = BIO_new_file("smencsign.txt", "r");
  
          if (!in)
              goto err;
          printf("keys read...\n");
          /* Parse message */
          cms = SMIME_read_CMS(in, NULL); //here is the problem I think
  
          if (!cms)
              goto err;
          printf("keys read...\n");
          out = BIO_new_file("decout.txt", "w");
          if (!out)
              goto err;
  
          /* Decrypt S/MIME message */
          if (!CMS_decrypt(cms, rkey, rcert, NULL, out, flags))
              goto err;
  
          ret = 0;
  
          err:
  
          if (ret)
          {
              fprintf(stderr, "Error Decrypting Data\n");
              ERR_print_errors_fp(stderr);
          }
  
          if (cms)
              //PKCS7_free(cms);
              CMS_ContentInfo_free(cms);
          if (rcert)
              X509_free(rcert);
          if (rkey)
              EVP_PKEY_free(rkey);
  
          if (in)
              BIO_free(in);
          if (out)
              BIO_free(out);
          if (tbio)
              BIO_free(tbio);
  
          return ret;
  
      }
  </code></pre>
  
  <p>The error I get is:
  Error Verifying Data
  *3074258568:error:0D0D40D1:asn1 encoding routines:SMIME_read_ASN1:no content type:asn_mime.c:451:*</p>
  
  <pre><code>The commands on openssl that worked:
  
  openssl cms -sign -in encr.txt -signer signer.pem -text | openssl cms -encrypt -out smencsign.txt signer.pem 
  
  openssl smime -decrypt -in smencsign.txt -recip signer.pem -inkey signer.pem
  </code></pre>
  
  <p>So clearly openssl uses 'cms' utility to sign and encrypt but seems to use 'smime' utility for decryption. What is then the code equivalent?</p>