cmsapitest.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include <string.h>
  2. #include <openssl/cms.h>
  3. #include <openssl/bio.h>
  4. #include <openssl/x509.h>
  5. #include <openssl/pem.h>
  6. #include "testutil.h"
  7. static X509 *cert = NULL;
  8. static EVP_PKEY *privkey = NULL;
  9. static int test_encrypt_decrypt(void)
  10. {
  11. int testresult = 0;
  12. STACK_OF(X509) *certstack = sk_X509_new_null();
  13. const char *msg = "Hello world";
  14. BIO *msgbio = BIO_new_mem_buf(msg, strlen(msg));
  15. BIO *outmsgbio = BIO_new(BIO_s_mem());
  16. CMS_ContentInfo* content = NULL;
  17. char buf[80];
  18. if (!TEST_ptr(certstack) || !TEST_ptr(msgbio) || !TEST_ptr(outmsgbio))
  19. goto end;
  20. if (!TEST_int_gt(sk_X509_push(certstack, cert), 0))
  21. goto end;
  22. content = CMS_encrypt(certstack, msgbio, EVP_aes_128_cbc(), CMS_TEXT);
  23. if (!TEST_ptr(content))
  24. goto end;
  25. if (!TEST_true(CMS_decrypt(content, privkey, cert, NULL, outmsgbio,
  26. CMS_TEXT)))
  27. goto end;
  28. /* Check we got the message we first started with */
  29. if (!TEST_int_eq(BIO_gets(outmsgbio, buf, sizeof(buf)), strlen(msg))
  30. || !TEST_int_eq(strcmp(buf, msg), 0))
  31. goto end;
  32. testresult = 1;
  33. end:
  34. sk_X509_free(certstack);
  35. BIO_free(msgbio);
  36. BIO_free(outmsgbio);
  37. CMS_ContentInfo_free(content);
  38. return testresult;
  39. }
  40. int setup_tests(void)
  41. {
  42. char *certin = NULL, *privkeyin = NULL;
  43. BIO *certbio = NULL, *privkeybio = NULL;
  44. if (!TEST_ptr(certin = test_get_argument(0))
  45. || !TEST_ptr(privkeyin = test_get_argument(1)))
  46. return 0;
  47. certbio = BIO_new_file(certin, "r");
  48. if (!TEST_ptr(certbio))
  49. return 0;
  50. if (!TEST_true(PEM_read_bio_X509(certbio, &cert, NULL, NULL))) {
  51. BIO_free(certbio);
  52. return 0;
  53. }
  54. BIO_free(certbio);
  55. privkeybio = BIO_new_file(privkeyin, "r");
  56. if (!TEST_ptr(privkeybio)) {
  57. X509_free(cert);
  58. cert = NULL;
  59. return 0;
  60. }
  61. if (!TEST_true(PEM_read_bio_PrivateKey(privkeybio, &privkey, NULL, NULL))) {
  62. BIO_free(privkeybio);
  63. X509_free(cert);
  64. cert = NULL;
  65. return 0;
  66. }
  67. BIO_free(privkeybio);
  68. ADD_TEST(test_encrypt_decrypt);
  69. return 1;
  70. }
  71. void cleanup_tests(void)
  72. {
  73. X509_free(cert);
  74. EVP_PKEY_free(privkey);
  75. }