cmsapitest.c 2.6 KB

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