2
0

smenc.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * Copyright 2007-2016 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the OpenSSL license (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/pkcs7.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. PKCS7 *p7 = NULL;
  19. int ret = 1;
  20. /*
  21. * On OpenSSL 0.9.9 only:
  22. * for streaming set PKCS7_STREAM
  23. */
  24. int flags = PKCS7_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. p7 = PKCS7_encrypt(recips, in, EVP_des_ede3_cbc(), flags);
  49. if (!p7)
  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_PKCS7(out, p7, 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. PKCS7_free(p7);
  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. }