cms_sign.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 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 = EXIT_FAILURE;
  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. if (BIO_reset(tbio) < 0)
  34. goto err;
  35. skey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
  36. if (!scert || !skey)
  37. goto err;
  38. /* Open content being signed */
  39. in = BIO_new_file("sign.txt", "r");
  40. if (!in)
  41. goto err;
  42. /* Sign content */
  43. cms = CMS_sign(scert, skey, NULL, in, flags);
  44. if (!cms)
  45. goto err;
  46. out = BIO_new_file("smout.txt", "w");
  47. if (!out)
  48. goto err;
  49. if (!(flags & CMS_STREAM)) {
  50. if (BIO_reset(in) < 0)
  51. goto err;
  52. }
  53. /* Write out S/MIME message */
  54. if (!SMIME_write_CMS(out, cms, in, flags))
  55. goto err;
  56. ret = EXIT_SUCCESS;
  57. err:
  58. if (ret != EXIT_SUCCESS) {
  59. fprintf(stderr, "Error Signing Data\n");
  60. ERR_print_errors_fp(stderr);
  61. }
  62. CMS_ContentInfo_free(cms);
  63. X509_free(scert);
  64. EVP_PKEY_free(skey);
  65. BIO_free(in);
  66. BIO_free(out);
  67. BIO_free(tbio);
  68. return ret;
  69. }