2 * Copyright 2018-2020 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (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
12 #include <openssl/cms.h>
13 #include <openssl/bio.h>
14 #include <openssl/x509.h>
15 #include <openssl/pem.h>
21 static X509 *cert = NULL;
22 static EVP_PKEY *privkey = NULL;
24 static int test_encrypt_decrypt(const EVP_CIPHER *cipher)
27 STACK_OF(X509) *certstack = sk_X509_new_null();
28 const char *msg = "Hello world";
29 BIO *msgbio = BIO_new_mem_buf(msg, strlen(msg));
30 BIO *outmsgbio = BIO_new(BIO_s_mem());
31 CMS_ContentInfo* content = NULL;
34 if (!TEST_ptr(certstack) || !TEST_ptr(msgbio) || !TEST_ptr(outmsgbio))
37 if (!TEST_int_gt(sk_X509_push(certstack, cert), 0))
40 content = CMS_encrypt(certstack, msgbio, cipher, CMS_TEXT);
41 if (!TEST_ptr(content))
44 if (!TEST_true(CMS_decrypt(content, privkey, cert, NULL, outmsgbio,
48 /* Check we got the message we first started with */
49 if (!TEST_int_eq(BIO_gets(outmsgbio, buf, sizeof(buf)), strlen(msg))
50 || !TEST_int_eq(strcmp(buf, msg), 0))
55 sk_X509_free(certstack);
58 CMS_ContentInfo_free(content);
63 static int test_encrypt_decrypt_aes_cbc(void)
65 return test_encrypt_decrypt(EVP_aes_128_cbc());
68 static int test_encrypt_decrypt_aes_128_gcm(void)
70 return test_encrypt_decrypt(EVP_aes_128_gcm());
73 static int test_encrypt_decrypt_aes_192_gcm(void)
75 return test_encrypt_decrypt(EVP_aes_192_gcm());
78 static int test_encrypt_decrypt_aes_256_gcm(void)
80 return test_encrypt_decrypt(EVP_aes_256_gcm());
83 OPT_TEST_DECLARE_USAGE("certfile privkeyfile\n")
87 char *certin = NULL, *privkeyin = NULL;
88 BIO *certbio = NULL, *privkeybio = NULL;
90 if (!test_skip_common_options()) {
91 TEST_error("Error parsing test options\n");
95 if (!TEST_ptr(certin = test_get_argument(0))
96 || !TEST_ptr(privkeyin = test_get_argument(1)))
99 certbio = BIO_new_file(certin, "r");
100 if (!TEST_ptr(certbio))
102 if (!TEST_true(PEM_read_bio_X509(certbio, &cert, NULL, NULL))) {
108 privkeybio = BIO_new_file(privkeyin, "r");
109 if (!TEST_ptr(privkeybio)) {
114 if (!TEST_true(PEM_read_bio_PrivateKey(privkeybio, &privkey, NULL, NULL))) {
115 BIO_free(privkeybio);
120 BIO_free(privkeybio);
122 ADD_TEST(test_encrypt_decrypt_aes_cbc);
123 ADD_TEST(test_encrypt_decrypt_aes_128_gcm);
124 ADD_TEST(test_encrypt_decrypt_aes_192_gcm);
125 ADD_TEST(test_encrypt_decrypt_aes_256_gcm);
130 void cleanup_tests(void)
133 EVP_PKEY_free(privkey);