cms_ddec.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * Copyright 2008-2023 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 = EXIT_FAILURE;
  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. if (BIO_reset(tbio) < 0)
  31. goto err;
  32. rkey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
  33. if (!rcert || !rkey)
  34. goto err;
  35. /* Open PEM file containing enveloped data */
  36. in = BIO_new_file("smencr.pem", "r");
  37. if (!in)
  38. goto err;
  39. /* Parse PEM content */
  40. cms = PEM_read_bio_CMS(in, NULL, 0, NULL);
  41. if (!cms)
  42. goto err;
  43. /* Open file containing detached content */
  44. dcont = BIO_new_file("smencr.out", "rb");
  45. if (!in)
  46. goto err;
  47. out = BIO_new_file("encrout.txt", "w");
  48. if (!out)
  49. goto err;
  50. /* Decrypt S/MIME message */
  51. if (!CMS_decrypt(cms, rkey, rcert, dcont, out, 0))
  52. goto err;
  53. ret = EXIT_SUCCESS;
  54. err:
  55. if (ret != EXIT_SUCCESS) {
  56. fprintf(stderr, "Error Decrypting Data\n");
  57. ERR_print_errors_fp(stderr);
  58. }
  59. CMS_ContentInfo_free(cms);
  60. X509_free(rcert);
  61. EVP_PKEY_free(rkey);
  62. BIO_free(in);
  63. BIO_free(out);
  64. BIO_free(tbio);
  65. BIO_free(dcont);
  66. return ret;
  67. }