2
0

cms_enc.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. /* Simple S/MIME encrypt example */
  10. #include <openssl/pem.h>
  11. #include <openssl/cms.h>
  12. #include <openssl/err.h>
  13. int main(int argc, char **argv)
  14. {
  15. BIO *in = NULL, *out = NULL, *tbio = NULL;
  16. X509 *rcert = NULL;
  17. STACK_OF(X509) *recips = NULL;
  18. CMS_ContentInfo *cms = NULL;
  19. int ret = 1;
  20. /*
  21. * On OpenSSL 1.0.0 and later only:
  22. * for streaming set CMS_STREAM
  23. */
  24. int flags = CMS_STREAM;
  25. OpenSSL_add_all_algorithms();
  26. ERR_load_crypto_strings();
  27. /* Read in recipient certificate */
  28. tbio = BIO_new_file("signer.pem", "r");
  29. if (!tbio)
  30. goto err;
  31. rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
  32. if (!rcert)
  33. goto err;
  34. /* Create recipient STACK and add recipient cert to it */
  35. recips = sk_X509_new_null();
  36. if (!recips || !sk_X509_push(recips, rcert))
  37. goto err;
  38. /*
  39. * sk_X509_pop_free will free up recipient STACK and its contents so set
  40. * rcert to NULL so it isn't freed up twice.
  41. */
  42. rcert = NULL;
  43. /* Open content being encrypted */
  44. in = BIO_new_file("encr.txt", "r");
  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.txt", "w");
  52. if (!out)
  53. goto err;
  54. /* Write out S/MIME message */
  55. if (!SMIME_write_CMS(out, cms, in, flags))
  56. goto err;
  57. ret = 0;
  58. err:
  59. if (ret) {
  60. fprintf(stderr, "Error Encrypting Data\n");
  61. ERR_print_errors_fp(stderr);
  62. }
  63. CMS_ContentInfo_free(cms);
  64. X509_free(rcert);
  65. sk_X509_pop_free(recips, X509_free);
  66. BIO_free(in);
  67. BIO_free(out);
  68. BIO_free(tbio);
  69. return ret;
  70. }