smsign2.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. /* S/MIME signing example: 2 signers. OpenSSL 0.9.9 only */
  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 = 1;
  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. BIO_reset(tbio);
  27. skey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
  28. BIO_free(tbio);
  29. tbio = BIO_new_file("signer2.pem", "r");
  30. if (!tbio)
  31. goto err;
  32. scert2 = PEM_read_bio_X509(tbio, NULL, 0, NULL);
  33. BIO_reset(tbio);
  34. skey2 = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
  35. if (!scert2 || !skey2)
  36. goto err;
  37. in = BIO_new_file("sign.txt", "r");
  38. if (!in)
  39. goto err;
  40. p7 = PKCS7_sign(NULL, NULL, NULL, in, PKCS7_STREAM | PKCS7_PARTIAL);
  41. if (!p7)
  42. goto err;
  43. /* Add each signer in turn */
  44. if (!PKCS7_sign_add_signer(p7, scert, skey, NULL, 0))
  45. goto err;
  46. if (!PKCS7_sign_add_signer(p7, scert2, skey2, NULL, 0))
  47. goto err;
  48. out = BIO_new_file("smout.txt", "w");
  49. if (!out)
  50. goto err;
  51. /* NB: content included and finalized by SMIME_write_PKCS7 */
  52. if (!SMIME_write_PKCS7(out, p7, in, PKCS7_STREAM))
  53. goto err;
  54. ret = 0;
  55. err:
  56. if (ret) {
  57. fprintf(stderr, "Error Signing Data\n");
  58. ERR_print_errors_fp(stderr);
  59. }
  60. PKCS7_free(p7);
  61. X509_free(scert);
  62. EVP_PKEY_free(skey);
  63. X509_free(scert2);
  64. EVP_PKEY_free(skey2);
  65. BIO_free(in);
  66. BIO_free(out);
  67. BIO_free(tbio);
  68. return ret;
  69. }