cms_ddec.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. * Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (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. * S/MIME detached data decrypt example: rarely done but should the need
  11. * arise this is an example....
  12. */
  13. #include <openssl/pem.h>
  14. #include <openssl/cms.h>
  15. #include <openssl/err.h>
  16. int main(int argc, char **argv)
  17. {
  18. BIO *in = NULL, *out = NULL, *tbio = NULL, *dcont = NULL;
  19. X509 *rcert = NULL;
  20. EVP_PKEY *rkey = NULL;
  21. CMS_ContentInfo *cms = NULL;
  22. int ret = 1;
  23. OpenSSL_add_all_algorithms();
  24. ERR_load_crypto_strings();
  25. /* Read in recipient certificate and private key */
  26. tbio = BIO_new_file("signer.pem", "r");
  27. if (!tbio)
  28. goto err;
  29. rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
  30. BIO_reset(tbio);
  31. rkey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
  32. if (!rcert || !rkey)
  33. goto err;
  34. /* Open PEM file containing enveloped data */
  35. in = BIO_new_file("smencr.pem", "r");
  36. if (!in)
  37. goto err;
  38. /* Parse PEM content */
  39. cms = PEM_read_bio_CMS(in, NULL, 0, NULL);
  40. if (!cms)
  41. goto err;
  42. /* Open file containing detached content */
  43. dcont = BIO_new_file("smencr.out", "rb");
  44. if (!in)
  45. goto err;
  46. out = BIO_new_file("encrout.txt", "w");
  47. if (!out)
  48. goto err;
  49. /* Decrypt S/MIME message */
  50. if (!CMS_decrypt(cms, rkey, rcert, dcont, out, 0))
  51. goto err;
  52. ret = 0;
  53. err:
  54. if (ret) {
  55. fprintf(stderr, "Error Decrypting Data\n");
  56. ERR_print_errors_fp(stderr);
  57. }
  58. CMS_ContentInfo_free(cms);
  59. X509_free(rcert);
  60. EVP_PKEY_free(rkey);
  61. BIO_free(in);
  62. BIO_free(out);
  63. BIO_free(tbio);
  64. BIO_free(dcont);
  65. return ret;
  66. }