smsign2.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. /* S/MIME signing example: 2 signers */
  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, *scert2 = NULL;
  17. EVP_PKEY *skey = NULL, *skey2 = NULL;
  18. PKCS7 *p7 = NULL;
  19. int ret = EXIT_FAILURE;
  20. OpenSSL_add_all_algorithms();
  21. ERR_load_crypto_strings();
  22. tbio = BIO_new_file("signer.pem", "r");
  23. if (!tbio)
  24. goto err;
  25. scert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
  26. if (BIO_reset(tbio) < 0)
  27. goto err;
  28. skey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
  29. BIO_free(tbio);
  30. tbio = BIO_new_file("signer2.pem", "r");
  31. if (!tbio)
  32. goto err;
  33. scert2 = PEM_read_bio_X509(tbio, NULL, 0, NULL);
  34. if (BIO_reset(tbio) < 0)
  35. goto err;
  36. skey2 = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
  37. if (!scert2 || !skey2)
  38. goto err;
  39. in = BIO_new_file("sign.txt", "r");
  40. if (!in)
  41. goto err;
  42. p7 = PKCS7_sign(NULL, NULL, NULL, in, PKCS7_STREAM | PKCS7_PARTIAL);
  43. if (!p7)
  44. goto err;
  45. /* Add each signer in turn */
  46. if (!PKCS7_sign_add_signer(p7, scert, skey, NULL, 0))
  47. goto err;
  48. if (!PKCS7_sign_add_signer(p7, scert2, skey2, NULL, 0))
  49. goto err;
  50. out = BIO_new_file("smout.txt", "w");
  51. if (!out)
  52. goto err;
  53. /* NB: content included and finalized by SMIME_write_PKCS7 */
  54. if (!SMIME_write_PKCS7(out, p7, in, PKCS7_STREAM))
  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. X509_free(scert2);
  67. EVP_PKEY_free(skey2);
  68. BIO_free(in);
  69. BIO_free(out);
  70. BIO_free(tbio);
  71. return ret;
  72. }