cms_denc.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 encrypt 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, *dout = NULL;
  19. X509 *rcert = NULL;
  20. STACK_OF(X509) *recips = NULL;
  21. CMS_ContentInfo *cms = NULL;
  22. int ret = 1;
  23. int flags = CMS_STREAM | CMS_DETACHED;
  24. OpenSSL_add_all_algorithms();
  25. ERR_load_crypto_strings();
  26. /* Read in recipient certificate */
  27. tbio = BIO_new_file("signer.pem", "r");
  28. if (!tbio)
  29. goto err;
  30. rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
  31. if (!rcert)
  32. goto err;
  33. /* Create recipient STACK and add recipient cert to it */
  34. recips = sk_X509_new_null();
  35. if (!recips || !sk_X509_push(recips, rcert))
  36. goto err;
  37. /*
  38. * sk_X509_pop_free will free up recipient STACK and its contents so set
  39. * rcert to NULL so it isn't freed up twice.
  40. */
  41. rcert = NULL;
  42. /* Open content being encrypted */
  43. in = BIO_new_file("encr.txt", "r");
  44. dout = BIO_new_file("smencr.out", "wb");
  45. if (!in)
  46. goto err;
  47. /* encrypt content */
  48. cms = CMS_encrypt(recips, in, EVP_des_ede3_cbc(), flags);
  49. if (!cms)
  50. goto err;
  51. out = BIO_new_file("smencr.pem", "w");
  52. if (!out)
  53. goto err;
  54. if (!CMS_final(cms, in, dout, flags))
  55. goto err;
  56. /* Write out CMS structure without content */
  57. if (!PEM_write_bio_CMS(out, cms))
  58. goto err;
  59. ret = 0;
  60. err:
  61. if (ret) {
  62. fprintf(stderr, "Error Encrypting Data\n");
  63. ERR_print_errors_fp(stderr);
  64. }
  65. CMS_ContentInfo_free(cms);
  66. X509_free(rcert);
  67. sk_X509_pop_free(recips, X509_free);
  68. BIO_free(in);
  69. BIO_free(out);
  70. BIO_free(dout);
  71. BIO_free(tbio);
  72. return ret;
  73. }