2
0

cms_dec.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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, out, NULL, 0))
  36. goto err;
  37. ret = 0;
  38. err:
  39. if (ret)
  40. {
  41. fprintf(stderr, "Error Decrypting Data\n");
  42. ERR_print_errors_fp(stderr);
  43. }
  44. if (cms)
  45. CMS_ContentInfo_free(cms);
  46. if (rcert)
  47. X509_free(rcert);
  48. if (rkey)
  49. EVP_PKEY_free(rkey);
  50. if (in)
  51. BIO_free(in);
  52. if (out)
  53. BIO_free(out);
  54. if (tbio)
  55. BIO_free(tbio);
  56. return ret;
  57. }