2
0

smsign.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * Copyright 2007-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/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 = EXIT_FAILURE;
  20. /*
  21. * For simple S/MIME signing use PKCS7_DETACHED.
  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. 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. p7 = PKCS7_sign(scert, skey, NULL, in, flags);
  44. if (!p7)
  45. goto err;
  46. out = BIO_new_file("smout.txt", "w");
  47. if (!out)
  48. goto err;
  49. if (!(flags & PKCS7_STREAM)) {
  50. if (BIO_reset(in) < 0)
  51. goto err;
  52. }
  53. /* Write out S/MIME message */
  54. if (!SMIME_write_PKCS7(out, p7, in, flags))
  55. goto err;
  56. printf("Success\n");
  57. ret = EXIT_SUCCESS;
  58. err:
  59. if (ret != EXIT_SUCCESS) {
  60. fprintf(stderr, "Error Signing Data\n");
  61. ERR_print_errors_fp(stderr);
  62. }
  63. PKCS7_free(p7);
  64. X509_free(scert);
  65. EVP_PKEY_free(skey);
  66. BIO_free(in);
  67. BIO_free(out);
  68. BIO_free(tbio);
  69. return ret;
  70. }