smsign.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. * Copyright 2007-2016 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the OpenSSL license (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/pkcs7.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. PKCS7 *p7 = NULL;
  19. int ret = 1;
  20. /*
  21. * For simple S/MIME signing use PKCS7_DETACHED. On OpenSSL 0.9.9 only:
  22. * for streaming detached set PKCS7_DETACHED|PKCS7_STREAM for streaming
  23. * non-detached set PKCS7_STREAM
  24. */
  25. int flags = PKCS7_DETACHED | PKCS7_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. p7 = PKCS7_sign(scert, skey, NULL, in, flags);
  43. if (!p7)
  44. goto err;
  45. out = BIO_new_file("smout.txt", "w");
  46. if (!out)
  47. goto err;
  48. if (!(flags & PKCS7_STREAM))
  49. BIO_reset(in);
  50. /* Write out S/MIME message */
  51. if (!SMIME_write_PKCS7(out, p7, 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. PKCS7_free(p7);
  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. }