A local copy of OpenSSL from GitHub
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
1.9 KiB

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