smsign2.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. /* S/MIME signing example: 2 signers. OpenSSL 0.9.9 only */
  2. #include <openssl/pem.h>
  3. #include <openssl/pkcs7.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. PKCS7 *p7 = 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. p7 = PKCS7_sign(NULL, NULL, NULL, in, PKCS7_STREAM|PKCS7_PARTIAL);
  33. if (!p7)
  34. goto err;
  35. /* Add each signer in turn */
  36. if (!PKCS7_sign_add_signer(p7, scert, skey, NULL, 0))
  37. goto err;
  38. if (!PKCS7_sign_add_signer(p7, 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_PKCS7 */
  44. if (!SMIME_write_PKCS7(out, p7, in, PKCS7_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 (p7)
  54. PKCS7_free(p7);
  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. }