smenc.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * Copyright 2007-2023 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (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 = EXIT_FAILURE;
  20. /*
  21. * for streaming set PKCS7_STREAM
  22. */
  23. int flags = PKCS7_STREAM;
  24. OpenSSL_add_all_algorithms();
  25. ERR_load_crypto_strings();
  26. /* Read in recipient certificate */
  27. tbio = BIO_new_file("signer.pem", "r");
  28. if (!tbio)
  29. goto err;
  30. rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
  31. if (!rcert)
  32. goto err;
  33. /* Create recipient STACK and add recipient cert to it */
  34. recips = sk_X509_new_null();
  35. if (!recips || !sk_X509_push(recips, rcert))
  36. goto err;
  37. /*
  38. * OSSL_STACK_OF_X509_free() will free up recipient STACK and its contents
  39. * so set rcert to NULL so it isn't freed up twice.
  40. */
  41. rcert = NULL;
  42. /* Open content being encrypted */
  43. in = BIO_new_file("encr.txt", "r");
  44. if (!in)
  45. goto err;
  46. /* encrypt content */
  47. p7 = PKCS7_encrypt(recips, in, EVP_des_ede3_cbc(), flags);
  48. if (!p7)
  49. goto err;
  50. out = BIO_new_file("smencr.txt", "w");
  51. if (!out)
  52. goto err;
  53. /* Write out S/MIME message */
  54. if (!SMIME_write_PKCS7(out, p7, in, flags))
  55. goto err;
  56. printf("Success\n");
  57. ret = EXIT_SUCCESS;
  58. err:
  59. if (ret != EXIT_SUCCESS) {
  60. fprintf(stderr, "Error Encrypting Data\n");
  61. ERR_print_errors_fp(stderr);
  62. }
  63. PKCS7_free(p7);
  64. X509_free(rcert);
  65. OSSL_STACK_OF_X509_free(recips);
  66. BIO_free(in);
  67. BIO_free(out);
  68. BIO_free(tbio);
  69. return ret;
  70. }