cms_denc.c 1.7 KB

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