cms_dec.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /* Simple S/MIME decryption example */
  2. #include <openssl/pem.h>
  3. #include <openssl/cms.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. EVP_PKEY *rkey = NULL;
  10. CMS_ContentInfo *cms = NULL;
  11. int ret = 1;
  12. OpenSSL_add_all_algorithms();
  13. ERR_load_crypto_strings();
  14. /* Read in recipient certificate and private key */
  15. tbio = BIO_new_file("signer.pem", "r");
  16. if (!tbio)
  17. goto err;
  18. rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
  19. BIO_reset(tbio);
  20. rkey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
  21. if (!rcert || !rkey)
  22. goto err;
  23. /* Open S/MIME message to decrypt */
  24. in = BIO_new_file("smencr.txt", "r");
  25. if (!in)
  26. goto err;
  27. /* Parse message */
  28. cms = SMIME_read_CMS(in, NULL);
  29. if (!cms)
  30. goto err;
  31. out = BIO_new_file("decout.txt", "w");
  32. if (!out)
  33. goto err;
  34. /* Decrypt S/MIME message */
  35. if (!CMS_decrypt(cms, rkey, rcert, NULL, out, 0))
  36. goto err;
  37. ret = 0;
  38. err:
  39. if (ret) {
  40. fprintf(stderr, "Error Decrypting Data\n");
  41. ERR_print_errors_fp(stderr);
  42. }
  43. if (cms)
  44. CMS_ContentInfo_free(cms);
  45. if (rcert)
  46. X509_free(rcert);
  47. if (rkey)
  48. EVP_PKEY_free(rkey);
  49. if (in)
  50. BIO_free(in);
  51. if (out)
  52. BIO_free(out);
  53. if (tbio)
  54. BIO_free(tbio);
  55. return ret;
  56. }