cms_sign.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. /*
  13. * For simple S/MIME signing use CMS_DETACHED. On OpenSSL 1.0.0 only: for
  14. * streaming detached set CMS_DETACHED|CMS_STREAM for streaming
  15. * 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. fprintf(stderr, "Error Signing Data\n");
  49. ERR_print_errors_fp(stderr);
  50. }
  51. if (cms)
  52. CMS_ContentInfo_free(cms);
  53. if (scert)
  54. X509_free(scert);
  55. if (skey)
  56. EVP_PKEY_free(skey);
  57. if (in)
  58. BIO_free(in);
  59. if (out)
  60. BIO_free(out);
  61. if (tbio)
  62. BIO_free(tbio);
  63. return ret;
  64. }