cms_sign2.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. * Copyright 2008-2016 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/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, *scert2 = NULL;
  17. EVP_PKEY *skey = NULL, *skey2 = NULL;
  18. CMS_ContentInfo *cms = 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. cms = CMS_sign(NULL, NULL, NULL, in, CMS_STREAM | CMS_PARTIAL);
  41. if (!cms)
  42. goto err;
  43. /* Add each signer in turn */
  44. if (!CMS_add1_signer(cms, scert, skey, NULL, 0))
  45. goto err;
  46. if (!CMS_add1_signer(cms, 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_CMS */
  52. if (!SMIME_write_CMS(out, cms, in, CMS_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. CMS_ContentInfo_free(cms);
  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. }