2
0

cms_dec.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * Copyright 2008-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 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 = EXIT_FAILURE;
  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. if (BIO_reset(tbio) < 0)
  28. goto err;
  29. rkey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
  30. if (!rcert || !rkey)
  31. goto err;
  32. /* Open S/MIME message to decrypt */
  33. in = BIO_new_file("smencr.txt", "r");
  34. if (!in)
  35. goto err;
  36. /* Parse message */
  37. cms = SMIME_read_CMS(in, NULL);
  38. if (!cms)
  39. goto err;
  40. out = BIO_new_file("decout.txt", "w");
  41. if (!out)
  42. goto err;
  43. /* Decrypt S/MIME message */
  44. if (!CMS_decrypt(cms, rkey, rcert, NULL, out, 0))
  45. goto err;
  46. printf("Decryption Successful\n");
  47. ret = EXIT_SUCCESS;
  48. err:
  49. if (ret != EXIT_SUCCESS) {
  50. fprintf(stderr, "Error Decrypting Data\n");
  51. ERR_print_errors_fp(stderr);
  52. }
  53. CMS_ContentInfo_free(cms);
  54. X509_free(rcert);
  55. EVP_PKEY_free(rkey);
  56. BIO_free(in);
  57. BIO_free(out);
  58. BIO_free(tbio);
  59. return ret;
  60. }