cms_enc.c 1.8 KB

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