cms_ddec.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /* S/MIME detached data decrypt example: rarely done but
  2. * should the need arise this is an example....
  3. */
  4. #include <openssl/pem.h>
  5. #include <openssl/cms.h>
  6. #include <openssl/err.h>
  7. int main(int argc, char **argv)
  8. {
  9. BIO *in = NULL, *out = NULL, *tbio = NULL, *dcont = NULL;
  10. X509 *rcert = NULL;
  11. EVP_PKEY *rkey = NULL;
  12. CMS_ContentInfo *cms = NULL;
  13. int ret = 1;
  14. OpenSSL_add_all_algorithms();
  15. ERR_load_crypto_strings();
  16. /* Read in recipient certificate and private key */
  17. tbio = BIO_new_file("signer.pem", "r");
  18. if (!tbio)
  19. goto err;
  20. rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
  21. BIO_reset(tbio);
  22. rkey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
  23. if (!rcert || !rkey)
  24. goto err;
  25. /* Open PEM file containing enveloped data */
  26. in = BIO_new_file("smencr.pem", "r");
  27. if (!in)
  28. goto err;
  29. /* Parse PEM content */
  30. cms = PEM_read_bio_CMS(in, NULL, 0, NULL);
  31. if (!cms)
  32. goto err;
  33. /* Open file containing detached content */
  34. dcont = BIO_new_file("smencr.out", "rb");
  35. if (!in)
  36. goto err;
  37. out = BIO_new_file("encrout.txt", "w");
  38. if (!out)
  39. goto err;
  40. /* Decrypt S/MIME message */
  41. if (!CMS_decrypt(cms, rkey, rcert, dcont, out, 0))
  42. goto err;
  43. ret = 0;
  44. err:
  45. if (ret)
  46. {
  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. }