smdec.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /* Simple S/MIME signing example */
  2. #include <openssl/pem.h>
  3. #include <openssl/pkcs7.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. PKCS7 *p7 = 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 content being signed */
  24. in = BIO_new_file("smencr.txt", "r");
  25. if (!in)
  26. goto err;
  27. /* Sign content */
  28. p7 = SMIME_read_PKCS7(in, NULL);
  29. if (!p7)
  30. goto err;
  31. out = BIO_new_file("encrout.txt", "w");
  32. if (!out)
  33. goto err;
  34. /* Decrypt S/MIME message */
  35. if (!PKCS7_decrypt(p7, rkey, rcert, out, 0))
  36. goto err;
  37. ret = 0;
  38. err:
  39. if (ret)
  40. {
  41. fprintf(stderr, "Error Signing Data\n");
  42. ERR_print_errors_fp(stderr);
  43. }
  44. if (p7)
  45. PKCS7_free(p7);
  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. }