1 /* Copyright (c) 2022 Nordic Semiconductor ASA
2  * SPDX-License-Identifier: Apache-2.0
3  */
4 
5 #include <errno.h>
6 #include <string.h>
7 
8 #include <zephyr/sys/byteorder.h>
9 
10 #include "psa/crypto.h"
11 
12 #include "common/bt_str.h"
13 #include "bt_crypto.h"
14 
15 #define LOG_LEVEL CONFIG_BT_CRYPTO_LOG_LEVEL
16 #include <zephyr/logging/log.h>
17 LOG_MODULE_DECLARE(bt_crypto);
18 
bt_crypto_aes_cmac(const uint8_t * key,const uint8_t * in,size_t len,uint8_t * out)19 int bt_crypto_aes_cmac(const uint8_t *key, const uint8_t *in, size_t len, uint8_t *out)
20 {
21 	psa_key_id_t key_id;
22 	psa_key_attributes_t key_attr = PSA_KEY_ATTRIBUTES_INIT;
23 	size_t out_size;
24 	psa_status_t status, destroy_status;
25 
26 	psa_set_key_type(&key_attr, PSA_KEY_TYPE_AES);
27 	psa_set_key_bits(&key_attr, 128);
28 	psa_set_key_usage_flags(&key_attr, PSA_KEY_USAGE_SIGN_MESSAGE |
29 					   PSA_KEY_USAGE_VERIFY_MESSAGE);
30 	psa_set_key_algorithm(&key_attr, PSA_ALG_CMAC);
31 
32 	status = psa_import_key(&key_attr, key, 16, &key_id);
33 	if (status != PSA_SUCCESS) {
34 		LOG_ERR("Failed to import AES key %d", status);
35 		return -EIO;
36 	}
37 
38 	status = psa_mac_compute(key_id, PSA_ALG_CMAC, in, len, out, 16, &out_size);
39 	destroy_status = psa_destroy_key(key_id);
40 	if ((status != PSA_SUCCESS) || (destroy_status != PSA_SUCCESS)) {
41 		LOG_ERR("Failed to compute MAC %d", status);
42 		return -EIO;
43 	}
44 
45 	return 0;
46 }
47