smenc.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /* Simple S/MIME encrypt example */
  2. #include <openssl/pem.h>
  3. #include <openssl/pkcs7.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. PKCS7 *p7 = NULL;
  11. int ret = 1;
  12. /*
  13. * On OpenSSL 0.9.9 only:
  14. * for streaming set PKCS7_STREAM
  15. */
  16. int flags = PKCS7_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. /* sk_X509_pop_free will free up recipient STACK and its contents
  31. * so set 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. if (!in)
  37. goto err;
  38. /* encrypt content */
  39. p7 = PKCS7_encrypt(recips, in, EVP_des_ede3_cbc(), flags);
  40. if (!p7)
  41. goto err;
  42. out = BIO_new_file("smencr.txt", "w");
  43. if (!out)
  44. goto err;
  45. /* Write out S/MIME message */
  46. if (!SMIME_write_PKCS7(out, p7, in, flags))
  47. goto err;
  48. ret = 0;
  49. err:
  50. if (ret)
  51. {
  52. fprintf(stderr, "Error Encrypting Data\n");
  53. ERR_print_errors_fp(stderr);
  54. }
  55. if (p7)
  56. PKCS7_free(p7);
  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. }