2
0

cms_sign.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /* Simple S/MIME signing 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 *scert = NULL;
  9. EVP_PKEY *skey = NULL;
  10. CMS_ContentInfo *cms = NULL;
  11. int ret = 1;
  12. /* For simple S/MIME signing use CMS_DETACHED.
  13. * On OpenSSL 0.9.9 only:
  14. * for streaming detached set CMS_DETACHED|CMS_STREAM
  15. * for streaming non-detached set CMS_STREAM
  16. */
  17. int flags = CMS_DETACHED|CMS_STREAM;
  18. OpenSSL_add_all_algorithms();
  19. ERR_load_crypto_strings();
  20. /* Read in signer certificate and private key */
  21. tbio = BIO_new_file("signer.pem", "r");
  22. if (!tbio)
  23. goto err;
  24. scert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
  25. BIO_reset(tbio);
  26. skey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
  27. if (!scert || !skey)
  28. goto err;
  29. /* Open content being signed */
  30. in = BIO_new_file("sign.txt", "r");
  31. if (!in)
  32. goto err;
  33. /* Sign content */
  34. cms = CMS_sign(scert, skey, NULL, in, flags);
  35. if (!cms)
  36. goto err;
  37. out = BIO_new_file("smout.txt", "w");
  38. if (!out)
  39. goto err;
  40. if (!(flags & CMS_STREAM))
  41. BIO_reset(in);
  42. /* Write out S/MIME message */
  43. if (!SMIME_write_CMS(out, cms, in, flags))
  44. goto err;
  45. ret = 0;
  46. err:
  47. if (ret)
  48. {
  49. fprintf(stderr, "Error Signing Data\n");
  50. ERR_print_errors_fp(stderr);
  51. }
  52. if (cms)
  53. CMS_ContentInfo_free(cms);
  54. if (scert)
  55. X509_free(scert);
  56. if (skey)
  57. EVP_PKEY_free(skey);
  58. if (in)
  59. BIO_free(in);
  60. if (out)
  61. BIO_free(out);
  62. if (tbio)
  63. BIO_free(tbio);
  64. return ret;
  65. }