cms_ddec.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. int main(int argc, char **argv)
  9. {
  10. BIO *in = NULL, *out = NULL, *tbio = NULL, *dcont = NULL;
  11. X509 *rcert = NULL;
  12. EVP_PKEY *rkey = NULL;
  13. CMS_ContentInfo *cms = NULL;
  14. int ret = 1;
  15. OpenSSL_add_all_algorithms();
  16. ERR_load_crypto_strings();
  17. /* Read in recipient certificate and private key */
  18. tbio = BIO_new_file("signer.pem", "r");
  19. if (!tbio)
  20. goto err;
  21. rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
  22. BIO_reset(tbio);
  23. rkey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
  24. if (!rcert || !rkey)
  25. goto err;
  26. /* Open PEM file containing enveloped data */
  27. in = BIO_new_file("smencr.pem", "r");
  28. if (!in)
  29. goto err;
  30. /* Parse PEM content */
  31. cms = PEM_read_bio_CMS(in, NULL, 0, NULL);
  32. if (!cms)
  33. goto err;
  34. /* Open file containing detached content */
  35. dcont = BIO_new_file("smencr.out", "rb");
  36. if (!in)
  37. goto err;
  38. out = BIO_new_file("encrout.txt", "w");
  39. if (!out)
  40. goto err;
  41. /* Decrypt S/MIME message */
  42. if (!CMS_decrypt(cms, rkey, rcert, dcont, out, 0))
  43. goto err;
  44. ret = 0;
  45. err:
  46. if (ret) {
  47. fprintf(stderr, "Error Decrypting Data\n");
  48. ERR_print_errors_fp(stderr);
  49. }
  50. if (cms)
  51. CMS_ContentInfo_free(cms);
  52. if (rcert)
  53. X509_free(rcert);
  54. if (rkey)
  55. EVP_PKEY_free(rkey);
  56. if (in)
  57. BIO_free(in);
  58. if (out)
  59. BIO_free(out);
  60. if (tbio)
  61. BIO_free(tbio);
  62. if (dcont)
  63. BIO_free(dcont);
  64. return ret;
  65. }