smdec.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * Copyright 2007-2016 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 signing 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. EVP_PKEY *rkey = NULL;
  18. PKCS7 *p7 = NULL;
  19. int ret = 1;
  20. OpenSSL_add_all_algorithms();
  21. ERR_load_crypto_strings();
  22. /* Read in recipient certificate and private key */
  23. tbio = BIO_new_file("signer.pem", "r");
  24. if (!tbio)
  25. goto err;
  26. rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
  27. BIO_reset(tbio);
  28. rkey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
  29. if (!rcert || !rkey)
  30. goto err;
  31. /* Open content being signed */
  32. in = BIO_new_file("smencr.txt", "r");
  33. if (!in)
  34. goto err;
  35. /* Sign content */
  36. p7 = SMIME_read_PKCS7(in, NULL);
  37. if (!p7)
  38. goto err;
  39. out = BIO_new_file("encrout.txt", "w");
  40. if (!out)
  41. goto err;
  42. /* Decrypt S/MIME message */
  43. if (!PKCS7_decrypt(p7, rkey, rcert, out, 0))
  44. goto err;
  45. ret = 0;
  46. err:
  47. if (ret) {
  48. fprintf(stderr, "Error Signing Data\n");
  49. ERR_print_errors_fp(stderr);
  50. }
  51. PKCS7_free(p7);
  52. X509_free(rcert);
  53. EVP_PKEY_free(rkey);
  54. BIO_free(in);
  55. BIO_free(out);
  56. BIO_free(tbio);
  57. return ret;
  58. }