cms_sign2.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /* S/MIME signing example: 2 signers */
  2. #include <openssl/pem.h>
  3. #include <openssl/cms.h>
  4. #include <openssl/err.h>
  5. int main(int argc, char **argv)
  6. {
  7. BIO *in = NULL, *out = NULL, *tbio = NULL;
  8. X509 *scert = NULL, *scert2 = NULL;
  9. EVP_PKEY *skey = NULL, *skey2 = NULL;
  10. CMS_ContentInfo *cms = NULL;
  11. int ret = 1;
  12. OpenSSL_add_all_algorithms();
  13. ERR_load_crypto_strings();
  14. tbio = BIO_new_file("signer.pem", "r");
  15. if (!tbio)
  16. goto err;
  17. scert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
  18. BIO_reset(tbio);
  19. skey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
  20. BIO_free(tbio);
  21. tbio = BIO_new_file("signer2.pem", "r");
  22. if (!tbio)
  23. goto err;
  24. scert2 = PEM_read_bio_X509(tbio, NULL, 0, NULL);
  25. BIO_reset(tbio);
  26. skey2 = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
  27. if (!scert2 || !skey2)
  28. goto err;
  29. in = BIO_new_file("sign.txt", "r");
  30. if (!in)
  31. goto err;
  32. cms = CMS_sign(NULL, NULL, NULL, in, CMS_STREAM | CMS_PARTIAL);
  33. if (!cms)
  34. goto err;
  35. /* Add each signer in turn */
  36. if (!CMS_add1_signer(cms, scert, skey, NULL, 0))
  37. goto err;
  38. if (!CMS_add1_signer(cms, scert2, skey2, NULL, 0))
  39. goto err;
  40. out = BIO_new_file("smout.txt", "w");
  41. if (!out)
  42. goto err;
  43. /* NB: content included and finalized by SMIME_write_CMS */
  44. if (!SMIME_write_CMS(out, cms, in, CMS_STREAM))
  45. goto err;
  46. ret = 0;
  47. err:
  48. if (ret) {
  49. fprintf(stderr, "Error Signing Data\n");
  50. ERR_print_errors_fp(stderr);
  51. }
  52. if (cms)
  53. CMS_ContentInfo_free(cms);
  54. if (scert)
  55. X509_free(scert);
  56. if (skey)
  57. EVP_PKEY_free(skey);
  58. if (scert2)
  59. X509_free(scert2);
  60. if (skey)
  61. EVP_PKEY_free(skey2);
  62. if (in)
  63. BIO_free(in);
  64. if (out)
  65. BIO_free(out);
  66. if (tbio)
  67. BIO_free(tbio);
  68. return ret;
  69. }