cms_denc.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. * S/MIME detached data encrypt example: rarely done but should the need
  3. * arise this is an example....
  4. */
  5. #include <openssl/pem.h>
  6. #include <openssl/cms.h>
  7. #include <openssl/err.h>
  8. int main(int argc, char **argv)
  9. {
  10. BIO *in = NULL, *out = NULL, *tbio = NULL, *dout = NULL;
  11. X509 *rcert = NULL;
  12. STACK_OF(X509) *recips = NULL;
  13. CMS_ContentInfo *cms = NULL;
  14. int ret = 1;
  15. int flags = CMS_STREAM | CMS_DETACHED;
  16. OpenSSL_add_all_algorithms();
  17. ERR_load_crypto_strings();
  18. /* Read in recipient certificate */
  19. tbio = BIO_new_file("signer.pem", "r");
  20. if (!tbio)
  21. goto err;
  22. rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
  23. if (!rcert)
  24. goto err;
  25. /* Create recipient STACK and add recipient cert to it */
  26. recips = sk_X509_new_null();
  27. if (!recips || !sk_X509_push(recips, rcert))
  28. goto err;
  29. /*
  30. * sk_X509_pop_free will free up recipient STACK and its contents so set
  31. * rcert to NULL so it isn't freed up twice.
  32. */
  33. rcert = NULL;
  34. /* Open content being encrypted */
  35. in = BIO_new_file("encr.txt", "r");
  36. dout = BIO_new_file("smencr.out", "wb");
  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.pem", "w");
  44. if (!out)
  45. goto err;
  46. if (!CMS_final(cms, in, dout, flags))
  47. goto err;
  48. /* Write out CMS structure without content */
  49. if (!PEM_write_bio_CMS(out, cms))
  50. goto err;
  51. ret = 0;
  52. err:
  53. if (ret) {
  54. fprintf(stderr, "Error Encrypting Data\n");
  55. ERR_print_errors_fp(stderr);
  56. }
  57. if (cms)
  58. CMS_ContentInfo_free(cms);
  59. if (rcert)
  60. X509_free(rcert);
  61. if (recips)
  62. sk_X509_pop_free(recips, X509_free);
  63. if (in)
  64. BIO_free(in);
  65. if (out)
  66. BIO_free(out);
  67. if (dout)
  68. BIO_free(dout);
  69. if (tbio)
  70. BIO_free(tbio);
  71. return ret;
  72. }