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