1 /* Copyright (c) 2023 Nordic Semiconductor ASA
2  * SPDX-License-Identifier: Apache-2.0
3  */
4 
5 #include <string.h>
6 #include <stdlib.h>
7 
8 #include <zephyr/ztest.h>
9 #include <zephyr/ztest_assert.h>
10 
11 #include <zephyr/logging/log.h>
12 #include <zephyr/bluetooth/crypto.h>
13 
14 #include "common/bt_str.h"
15 
16 #include "test_vectors.h"
17 
18 LOG_MODULE_REGISTER(test_bt_crypto_ccm, LOG_LEVEL_INF);
19 
20 ZTEST_SUITE(bt_crypto_ccm, NULL, NULL, NULL, NULL, NULL);
21 
ZTEST(bt_crypto_ccm,test_result_rfc_test_vectors)22 ZTEST(bt_crypto_ccm, test_result_rfc_test_vectors)
23 {
24 	for (int i = 0; i < NUMBER_OF_TEST; i++) {
25 		LOG_DBG("=============== Packet Vector #%d ==================", i + 1);
26 		int err;
27 		struct test_data *p = input_packets[i];
28 
29 		p->expected_output_len = p->input_len + p->mic_len;
30 
31 		const uint8_t *aad = p->input;
32 
33 		uint8_t *encrypted_data =
34 			(uint8_t *)malloc(p->expected_output_len * sizeof(uint8_t));
35 
36 		memcpy(encrypted_data, p->input, p->input_len);
37 
38 		err = bt_ccm_encrypt(p->key, p->nonce, &p->input[p->aad_len],
39 				     p->input_len - p->aad_len, aad, p->aad_len,
40 				     &encrypted_data[p->aad_len], p->mic_len);
41 		zassert_true(err == 0, "CCM Encrypt failed for packet vector %d with error %d",
42 			     i + 1, err);
43 
44 		LOG_DBG("encrypted data %s (len: %d)",
45 			bt_hex(encrypted_data, p->expected_output_len), p->expected_output_len);
46 		LOG_DBG("expected data  %s (len: %d)",
47 			bt_hex(p->expected_output, p->expected_output_len), p->expected_output_len);
48 
49 		zassert_mem_equal(encrypted_data, p->expected_output, p->expected_output_len,
50 				  "Encrypted data are not correct for packet vector %d", i + 1);
51 
52 		uint8_t *decrypted_data = (uint8_t *)malloc(p->input_len * sizeof(uint8_t));
53 
54 		memcpy(decrypted_data, encrypted_data, p->aad_len);
55 
56 		err = bt_ccm_decrypt(p->key, p->nonce, &encrypted_data[p->aad_len],
57 				     p->input_len - p->aad_len, aad, p->aad_len,
58 				     &decrypted_data[p->aad_len], p->mic_len);
59 		zassert_true(err == 0, "CCM Decrypt failed for packet vector %d with error %d",
60 			     i + 1, err);
61 
62 		LOG_DBG("decrypted data %s (len: %d)", bt_hex(decrypted_data, p->input_len),
63 			p->input_len);
64 		LOG_DBG("expected data %s (len: %d)", bt_hex(p->input, p->input_len), p->input_len);
65 
66 		zassert_mem_equal(decrypted_data, p->input, p->input_len,
67 				  "Decrypted data are not correct for packet vector %d", i + 1);
68 
69 		free(encrypted_data);
70 		free(decrypted_data);
71 	}
72 }
73