2
0

cms_dec.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * Copyright 2008-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 decryption example */
  10. #include <openssl/pem.h>
  11. #include <openssl/cms.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. CMS_ContentInfo *cms = 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 S/MIME message to decrypt */
  32. in = BIO_new_file("smencr.txt", "r");
  33. if (!in)
  34. goto err;
  35. /* Parse message */
  36. cms = SMIME_read_CMS(in, NULL);
  37. if (!cms)
  38. goto err;
  39. out = BIO_new_file("decout.txt", "w");
  40. if (!out)
  41. goto err;
  42. /* Decrypt S/MIME message */
  43. if (!CMS_decrypt(cms, rkey, rcert, NULL, out, 0))
  44. goto err;
  45. ret = 0;
  46. err:
  47. if (ret) {
  48. fprintf(stderr, "Error Decrypting Data\n");
  49. ERR_print_errors_fp(stderr);
  50. }
  51. CMS_ContentInfo_free(cms);
  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. }