cms_sign2.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. {
  50. fprintf(stderr, "Error Signing Data\n");
  51. ERR_print_errors_fp(stderr);
  52. }
  53. if (cms)
  54. CMS_ContentInfo_free(cms);
  55. if (scert)
  56. X509_free(scert);
  57. if (skey)
  58. EVP_PKEY_free(skey);
  59. if (scert2)
  60. X509_free(scert2);
  61. if (skey)
  62. EVP_PKEY_free(skey2);
  63. if (in)
  64. BIO_free(in);
  65. if (out)
  66. BIO_free(out);
  67. if (tbio)
  68. BIO_free(tbio);
  69. return ret;
  70. }