xref: /btstack/src/btstack_crypto.c (revision 9e6f2329910d5193795b796692002063e5d8752d)
1 /*
2  * Copyright (C) 2017 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY MATTHIAS RINGWALD AND CONTRIBUTORS
18  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
21  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
24  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
27  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  */
31 
32 #define __BTSTACK_FILE__ "btstack_crypto.c"
33 
34 /*
35  * btstack_crypto.h
36  *
37  * Central place for all crypto-related functions with completion callbacks to allow
38  * using of MCU crypto peripherals or the Bluetooth controller
39  */
40 
41 #include "btstack_crypto.h"
42 
43 #include "btstack_debug.h"
44 #include "btstack_event.h"
45 #include "btstack_linked_list.h"
46 #include "btstack_util.h"
47 #include "hci.h"
48 
49 // backwards-compatitility ENABLE_MICRO_ECC_FOR_LE_SECURE_CONNECTIONS -> ENABLE_MICRO_ECC_P256
50 #if defined(ENABLE_MICRO_ECC_FOR_LE_SECURE_CONNECTIONS) && !defined(ENABLE_MICRO_ECC_P256)
51 #define ENABLE_MICRO_ECC_P256
52 #endif
53 
54 // configure ECC implementations
55 #if defined(ENABLE_MICRO_ECC_P256) && defined(HAVE_MBEDTLS_ECC_P256)
56 #error "If you have mbedTLS (HAVE_MBEDTLS_ECC_P256), please disable uECC (ENABLE_MICRO_ECC_P256) in bstack_config.h"
57 #endif
58 
59 // Software ECC-P256 implementation provided by micro-ecc
60 #ifdef ENABLE_MICRO_ECC_P256
61 #define ENABLE_ECC_P256
62 #define USE_MICRO_ECC_P256
63 #define USE_SOFTWARE_ECC_P256_IMPLEMENTATION
64 #include "uECC.h"
65 #endif
66 
67 // Software ECC-P256 implementation provided by mbedTLS
68 #ifdef HAVE_MBEDTLS_ECC_P256
69 #define ENABLE_ECC_P256
70 #define USE_MBEDTLS_ECC_P256
71 #define USE_SOFTWARE_ECC_P256_IMPLEMENTATION
72 #include "mbedtls/config.h"
73 #include "mbedtls/platform.h"
74 #include "mbedtls/ecp.h"
75 #endif
76 
77 #if defined(ENABLE_LE_SECURE_CONNECTIONS) && !defined(ENABLE_ECC_P256)
78 #define ENABLE_ECC_P256
79 #endif
80 
81 // Software AES128
82 #ifdef HAVE_AES128
83 #define USE_BTSTACK_AES128
84 void btstack_aes128_calc(const uint8_t * key, const uint8_t * plaintext, uint8_t * result);
85 #endif
86 
87 typedef enum {
88     CMAC_IDLE,
89     CMAC_CALC_SUBKEYS,
90     CMAC_W4_SUBKEYS,
91     CMAC_CALC_MI,
92     CMAC_W4_MI,
93     CMAC_CALC_MLAST,
94     CMAC_W4_MLAST
95 } btstack_crypto_cmac_state_t;
96 
97 typedef enum {
98     ECC_P256_KEY_GENERATION_IDLE,
99     ECC_P256_KEY_GENERATION_GENERATING_RANDOM,
100     ECC_P256_KEY_GENERATION_ACTIVE,
101     ECC_P256_KEY_GENERATION_W4_KEY,
102     ECC_P256_KEY_GENERATION_DONE,
103 } btstack_crypto_ecc_p256_key_generation_state_t;
104 
105 static void btstack_crypto_run(void);
106 
107 const static uint8_t zero[16] = { 0 };
108 
109 static uint8_t btstack_crypto_initialized;
110 static btstack_linked_list_t btstack_crypto_operations;
111 static btstack_packet_callback_registration_t hci_event_callback_registration;
112 static uint8_t btstack_crypto_wait_for_hci_result;
113 
114 // state for AES-CMAC
115 static btstack_crypto_cmac_state_t btstack_crypto_cmac_state;
116 static sm_key_t btstack_crypto_cmac_k;
117 static sm_key_t btstack_crypto_cmac_x;
118 static sm_key_t btstack_crypto_cmac_m_last;
119 static uint8_t  btstack_crypto_cmac_block_current;
120 static uint8_t  btstack_crypto_cmac_block_count;
121 
122 // state for AES-CCM
123 #ifndef USE_BTSTACK_AES128
124 static uint8_t btstack_crypto_ccm_s[16];
125 #endif
126 
127 #ifdef ENABLE_ECC_P256
128 
129 static uint8_t  btstack_crypto_ecc_p256_public_key[64];
130 static uint8_t  btstack_crypto_ecc_p256_random[64];
131 static uint8_t  btstack_crypto_ecc_p256_random_len;
132 static uint8_t  btstack_crypto_ecc_p256_random_offset;
133 static btstack_crypto_ecc_p256_key_generation_state_t btstack_crypto_ecc_p256_key_generation_state;
134 
135 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
136 static uint8_t btstack_crypto_ecc_p256_d[32];
137 #endif
138 
139 #endif /* ENABLE_ECC_P256 */
140 
141 static void btstack_crypto_done(btstack_crypto_t * btstack_crypto){
142     btstack_linked_list_pop(&btstack_crypto_operations);
143     (*btstack_crypto->context_callback.callback)(btstack_crypto->context_callback.context);
144 }
145 
146 static inline void btstack_crypto_cmac_next_state(void){
147     btstack_crypto_cmac_state = (btstack_crypto_cmac_state_t) (((int)btstack_crypto_cmac_state) + 1);
148 }
149 
150 static int btstack_crypto_cmac_last_block_complete(btstack_crypto_aes128_cmac_t * btstack_crypto_cmac){
151 	uint16_t len = btstack_crypto_cmac->size;
152     if (len == 0) return 0;
153     return (len & 0x0f) == 0;
154 }
155 
156 static void btstack_crypto_aes128_start(const sm_key_t key, const sm_key_t plaintext){
157  	uint8_t key_flipped[16];
158  	uint8_t plaintext_flipped[16];
159     reverse_128(key, key_flipped);
160     reverse_128(plaintext, plaintext_flipped);
161  	btstack_crypto_wait_for_hci_result = 1;
162     hci_send_cmd(&hci_le_encrypt, key_flipped, plaintext_flipped);
163 }
164 
165 static uint8_t btstack_crypto_cmac_get_byte(btstack_crypto_aes128_cmac_t * btstack_crypto_cmac, uint16_t pos){
166 	if (btstack_crypto_cmac->btstack_crypto.operation == BTSTACK_CRYPTO_CMAC_GENERATOR){
167 		return (*btstack_crypto_cmac->get_byte_callback)(pos);
168 	} else {
169 		return btstack_crypto_cmac->message[pos];
170 	}
171 }
172 
173 static void btstack_crypto_cmac_handle_aes_engine_ready(btstack_crypto_aes128_cmac_t * btstack_crypto_cmac){
174     switch (btstack_crypto_cmac_state){
175         case CMAC_CALC_SUBKEYS: {
176             sm_key_t const_zero;
177             memset(const_zero, 0, 16);
178             btstack_crypto_cmac_next_state();
179             btstack_crypto_aes128_start(btstack_crypto_cmac_k, const_zero);
180             break;
181         }
182         case CMAC_CALC_MI: {
183             int j;
184             sm_key_t y;
185             for (j=0;j<16;j++){
186                 y[j] = btstack_crypto_cmac_x[j] ^ btstack_crypto_cmac_get_byte(btstack_crypto_cmac, btstack_crypto_cmac_block_current*16 + j);
187             }
188             btstack_crypto_cmac_block_current++;
189             btstack_crypto_cmac_next_state();
190             btstack_crypto_aes128_start(btstack_crypto_cmac_k, y);
191             break;
192         }
193         case CMAC_CALC_MLAST: {
194             int i;
195             sm_key_t y;
196             for (i=0;i<16;i++){
197                 y[i] = btstack_crypto_cmac_x[i] ^ btstack_crypto_cmac_m_last[i];
198             }
199             btstack_crypto_cmac_block_current++;
200             btstack_crypto_cmac_next_state();
201             btstack_crypto_aes128_start(btstack_crypto_cmac_k, y);
202             break;
203         }
204         default:
205             log_info("btstack_crypto_cmac_handle_aes_engine_ready called in state %u", btstack_crypto_cmac_state);
206             break;
207     }
208 }
209 
210 static void btstack_crypto_cmac_shift_left_by_one_bit_inplace(int len, uint8_t * data){
211     int i;
212     int carry = 0;
213     for (i=len-1; i >= 0 ; i--){
214         int new_carry = data[i] >> 7;
215         data[i] = data[i] << 1 | carry;
216         carry = new_carry;
217     }
218 }
219 
220 static void btstack_crypto_cmac_handle_encryption_result(btstack_crypto_aes128_cmac_t * btstack_crypto_cmac, sm_key_t data){
221     switch (btstack_crypto_cmac_state){
222         case CMAC_W4_SUBKEYS: {
223             sm_key_t k1;
224             memcpy(k1, data, 16);
225             btstack_crypto_cmac_shift_left_by_one_bit_inplace(16, k1);
226             if (data[0] & 0x80){
227                 k1[15] ^= 0x87;
228             }
229             sm_key_t k2;
230             memcpy(k2, k1, 16);
231             btstack_crypto_cmac_shift_left_by_one_bit_inplace(16, k2);
232             if (k1[0] & 0x80){
233                 k2[15] ^= 0x87;
234             }
235 
236             log_info_key("k", btstack_crypto_cmac_k);
237             log_info_key("k1", k1);
238             log_info_key("k2", k2);
239 
240             // step 4: set m_last
241             int i;
242             if (btstack_crypto_cmac_last_block_complete(btstack_crypto_cmac)){
243                 for (i=0;i<16;i++){
244                     btstack_crypto_cmac_m_last[i] = btstack_crypto_cmac_get_byte(btstack_crypto_cmac, btstack_crypto_cmac->size - 16 + i) ^ k1[i];
245                 }
246             } else {
247                 int valid_octets_in_last_block = btstack_crypto_cmac->size & 0x0f;
248                 for (i=0;i<16;i++){
249                     if (i < valid_octets_in_last_block){
250                         btstack_crypto_cmac_m_last[i] = btstack_crypto_cmac_get_byte(btstack_crypto_cmac, (btstack_crypto_cmac->size & 0xfff0) + i) ^ k2[i];
251                         continue;
252                     }
253                     if (i == valid_octets_in_last_block){
254                         btstack_crypto_cmac_m_last[i] = 0x80 ^ k2[i];
255                         continue;
256                     }
257                     btstack_crypto_cmac_m_last[i] = k2[i];
258                 }
259             }
260 
261             // next
262             btstack_crypto_cmac_state = btstack_crypto_cmac_block_current < btstack_crypto_cmac_block_count - 1 ? CMAC_CALC_MI : CMAC_CALC_MLAST;
263             break;
264         }
265         case CMAC_W4_MI:
266             memcpy(btstack_crypto_cmac_x, data, 16);
267             btstack_crypto_cmac_state = btstack_crypto_cmac_block_current < btstack_crypto_cmac_block_count - 1 ? CMAC_CALC_MI : CMAC_CALC_MLAST;
268             break;
269         case CMAC_W4_MLAST:
270             // done
271             log_info("Setting CMAC Engine to IDLE");
272             btstack_crypto_cmac_state = CMAC_IDLE;
273             log_info_key("CMAC", data);
274             memcpy(btstack_crypto_cmac->hash, data, 16);
275 			btstack_linked_list_pop(&btstack_crypto_operations);
276 			(*btstack_crypto_cmac->btstack_crypto.context_callback.callback)(btstack_crypto_cmac->btstack_crypto.context_callback.context);
277             break;
278         default:
279             log_info("btstack_crypto_cmac_handle_encryption_result called in state %u", btstack_crypto_cmac_state);
280             break;
281     }
282 }
283 
284 static void btstack_crypto_cmac_start(btstack_crypto_aes128_cmac_t * btstack_crypto_cmac){
285 
286     memcpy(btstack_crypto_cmac_k, btstack_crypto_cmac->key, 16);
287     memset(btstack_crypto_cmac_x, 0, 16);
288     btstack_crypto_cmac_block_current = 0;
289 
290     // step 2: n := ceil(len/const_Bsize);
291     btstack_crypto_cmac_block_count = (btstack_crypto_cmac->size + 15) / 16;
292 
293     // step 3: ..
294     if (btstack_crypto_cmac_block_count==0){
295         btstack_crypto_cmac_block_count = 1;
296     }
297     log_info("btstack_crypto_cmac_start: len %u, block count %u", btstack_crypto_cmac->size, btstack_crypto_cmac_block_count);
298 
299     // first, we need to compute l for k1, k2, and m_last
300     btstack_crypto_cmac_state = CMAC_CALC_SUBKEYS;
301 
302     // let's go
303     btstack_crypto_cmac_handle_aes_engine_ready(btstack_crypto_cmac);
304 }
305 
306 #ifndef USE_BTSTACK_AES128
307 
308 /*
309   To encrypt the message data we use Counter (CTR) mode.  We first
310   define the key stream blocks by:
311 
312       S_i := E( K, A_i )   for i=0, 1, 2, ...
313 
314   The values A_i are formatted as follows, where the Counter field i is
315   encoded in most-significant-byte first order:
316 
317   Octet Number   Contents
318   ------------   ---------
319   0              Flags
320   1 ... 15-L     Nonce N
321   16-L ... 15    Counter i
322 
323   Bit Number   Contents
324   ----------   ----------------------
325   7            Reserved (always zero)
326   6            Reserved (always zero)
327   5 ... 3      Zero
328   2 ... 0      L'
329 */
330 
331 static void btstack_crypto_ccm_setup_a_i(btstack_crypto_ccm_t * btstack_crypto_ccm, uint16_t counter){
332     btstack_crypto_ccm_s[0] = 1;  // L' = L - 1
333     memcpy(&btstack_crypto_ccm_s[1], btstack_crypto_ccm->nonce, 13);
334     big_endian_store_16(btstack_crypto_ccm_s, 14, counter);
335 }
336 
337 /*
338  The first step is to compute the authentication field T.  This is
339    done using CBC-MAC [MAC].  We first define a sequence of blocks B_0,
340    B_1, ..., B_n and then apply CBC-MAC to these blocks.
341 
342    The first block B_0 is formatted as follows, where l(m) is encoded in
343    most-significant-byte first order:
344 
345       Octet Number   Contents
346       ------------   ---------
347       0              Flags
348       1 ... 15-L     Nonce N
349       16-L ... 15    l(m)
350 
351    Within the first block B_0, the Flags field is formatted as follows:
352 
353       Bit Number   Contents
354       ----------   ----------------------
355       7            Reserved (always zero)
356       6            Adata
357       5 ... 3      M'
358       2 ... 0      L'
359  */
360 
361 static void btstack_crypto_ccm_setup_b_0(btstack_crypto_ccm_t * btstack_crypto_ccm, uint8_t * b0){
362     b0[0] = (3 << 3) | 1 ;  // Adata = 0, M' = (M-2)/2, L' = L - 1
363     memcpy(&b0[1], btstack_crypto_ccm->nonce, 13);
364     big_endian_store_16(b0, 14, btstack_crypto_ccm->message_len);
365 }
366 #endif
367 
368 #ifdef ENABLE_ECC_P256
369 
370 static void btstack_crypto_log_ec_publickey(const uint8_t * ec_q){
371     log_info("Elliptic curve: X");
372     log_info_hexdump(&ec_q[0],32);
373     log_info("Elliptic curve: Y");
374     log_info_hexdump(&ec_q[32],32);
375 }
376 
377 #if (defined(USE_MICRO_ECC_P256) && !defined(WICED_VERSION)) || defined(USE_MBEDTLS_ECC_P256)
378 // @return OK
379 static int sm_generate_f_rng(unsigned char * buffer, unsigned size){
380     if (btstack_crypto_ecc_p256_key_generation_state != ECC_P256_KEY_GENERATION_ACTIVE) return 0;
381     log_info("sm_generate_f_rng: size %u - offset %u", (int) size, btstack_crypto_ecc_p256_random_offset);
382     while (size) {
383         *buffer++ = btstack_crypto_ecc_p256_random[btstack_crypto_ecc_p256_random_offset++];
384         size--;
385     }
386     return 1;
387 }
388 #endif
389 #ifdef USE_MBEDTLS_ECC_P256
390 // @return error - just wrap sm_generate_f_rng
391 static int sm_generate_f_rng_mbedtls(void * context, unsigned char * buffer, size_t size){
392     UNUSED(context);
393     return sm_generate_f_rng(buffer, size) == 0;
394 }
395 #endif /* USE_MBEDTLS_ECC_P256 */
396 
397 static void btstack_crypto_ecc_p256_generate_key_software(void){
398 
399     btstack_crypto_ecc_p256_random_offset = 0;
400 
401     // generate EC key
402 #ifdef USE_MICRO_ECC_P256
403 
404 #ifndef WICED_VERSION
405     log_info("set uECC RNG for initial key generation with 64 random bytes");
406     // micro-ecc from WICED SDK uses its wiced_crypto_get_random by default - no need to set it
407     uECC_set_rng(&sm_generate_f_rng);
408 #endif /* WICED_VERSION */
409 
410 #if uECC_SUPPORTS_secp256r1
411     // standard version
412     uECC_make_key(btstack_crypto_ecc_p256_public_key, btstack_crypto_ecc_p256_d, uECC_secp256r1());
413 
414     // disable RNG again, as returning no randmon data lets shared key generation fail
415     log_info("disable uECC RNG in standard version after key generation");
416     uECC_set_rng(NULL);
417 #else
418     // static version
419     uECC_make_key(btstack_crypto_ecc_p256_public_key, btstack_crypto_ecc_p256_d);
420 #endif
421 #endif /* USE_MICRO_ECC_P256 */
422 
423 #ifdef USE_MBEDTLS_ECC_P256
424     mbedtls_mpi d;
425     mbedtls_ecp_point P;
426     mbedtls_mpi_init(&d);
427     mbedtls_ecp_point_init(&P);
428     int res = mbedtls_ecp_gen_keypair(&mbedtls_ec_group, &d, &P, &sm_generate_f_rng_mbedtls, NULL);
429     log_info("gen keypair %x", res);
430     mbedtls_mpi_write_binary(&P.X, &btstack_crypto_ecc_p256_public_key[0],  32);
431     mbedtls_mpi_write_binary(&P.Y, &btstack_crypto_ecc_p256_public_key[32], 32);
432     mbedtls_mpi_write_binary(&d, btstack_crypto_ecc_p256_d, 32);
433     mbedtls_ecp_point_free(&P);
434     mbedtls_mpi_free(&d);
435 #endif  /* USE_MBEDTLS_ECC_P256 */
436 }
437 
438 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
439 static void btstack_crypto_ecc_p256_calculate_dhkey_software(btstack_crypto_ecc_p256_t * btstack_crypto_ec_p192){
440     memset(btstack_crypto_ec_p192->dhkey, 0, 32);
441 
442 #ifdef USE_MICRO_ECC_P256
443 #if uECC_SUPPORTS_secp256r1
444     // standard version
445     uECC_shared_secret(btstack_crypto_ec_p192->public_key, btstack_crypto_ecc_p256_d, btstack_crypto_ec_p192->dhkey, uECC_secp256r1());
446 #else
447     // static version
448     uECC_shared_secret(btstack_crypto_ec_p192->public_key, btstack_crypto_ecc_p256_d, btstack_crypto_ec_p192->dhkey);
449 #endif
450 #endif
451 
452 #ifdef USE_MBEDTLS_ECC_P256
453     // da * Pb
454     mbedtls_mpi d;
455     mbedtls_ecp_point Q;
456     mbedtls_ecp_point DH;
457     mbedtls_mpi_init(&d);
458     mbedtls_ecp_point_init(&Q);
459     mbedtls_ecp_point_init(&DH);
460     mbedtls_mpi_read_binary(&d, btstack_crypto_ecc_p256_d, 32);
461     mbedtls_mpi_read_binary(&Q.X, &btstack_crypto_ec_p192->public_key[0] , 32);
462     mbedtls_mpi_read_binary(&Q.Y, &btstack_crypto_ec_p192->public_key[32], 32);
463     mbedtls_mpi_lset(&Q.Z, 1);
464     mbedtls_ecp_mul(&mbedtls_ec_group, &DH, &d, &Q, NULL, NULL);
465     mbedtls_mpi_write_binary(&DH.X, btstack_crypto_ec_p192->dhkey, 32);
466     mbedtls_ecp_point_free(&DH);
467     mbedtls_mpi_free(&d);
468     mbedtls_ecp_point_free(&Q);
469 #endif
470 
471     log_info("dhkey");
472     log_info_hexdump(btstack_crypto_ec_p192->dhkey, 32);
473 }
474 #endif
475 
476 #endif
477 
478 #ifdef USE_BTSTACK_AES128
479 // CCM not implemented using software AES128 yet
480 #else
481 
482 static void btstack_crypto_ccm_calc_s0(btstack_crypto_ccm_t * btstack_crypto_ccm){
483     btstack_crypto_ccm->state = CCM_W4_S0;
484     btstack_crypto_ccm_setup_a_i(btstack_crypto_ccm, 0);
485     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_s);
486 }
487 
488 static void btstack_crypto_ccm_calc_sn(btstack_crypto_ccm_t * btstack_crypto_ccm){
489     btstack_crypto_ccm->state = CCM_W4_SN;
490     btstack_crypto_ccm_setup_a_i(btstack_crypto_ccm, btstack_crypto_ccm->counter);
491     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_s);
492 }
493 
494 static void btstack_crypto_ccm_calc_x1(btstack_crypto_ccm_t * btstack_crypto_ccm){
495     uint8_t btstack_crypto_ccm_buffer[16];
496     btstack_crypto_ccm->state = CCM_W4_X1;
497     btstack_crypto_ccm_setup_b_0(btstack_crypto_ccm, btstack_crypto_ccm_buffer);
498     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_buffer);
499 }
500 
501 static void btstack_crypto_ccm_calc_xn(btstack_crypto_ccm_t * btstack_crypto_ccm, const uint8_t * plaintext){
502     int i;
503     int bytes_to_decrypt;
504     uint8_t btstack_crypto_ccm_buffer[16];
505     btstack_crypto_ccm->state = CCM_W4_XN;
506     bytes_to_decrypt = btstack_min(btstack_crypto_ccm->block_len, 16);
507     i = 0;
508     while (i < bytes_to_decrypt){
509         btstack_crypto_ccm_buffer[i] =  btstack_crypto_ccm->x_i[i] ^ plaintext[i];
510         i++;
511     }
512     memcpy(&btstack_crypto_ccm_buffer[i], &btstack_crypto_ccm->x_i[i], 16 - bytes_to_decrypt);
513     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_buffer);
514 }
515 #endif
516 
517 static void btstack_crypto_ccm_handle_s0(btstack_crypto_ccm_t * btstack_crypto_ccm, const uint8_t * data){
518     // data is little-endian, flip on the fly
519     int i;
520     for (i=0;i<16;i++){
521         btstack_crypto_ccm->x_i[i] = btstack_crypto_ccm->x_i[i] ^ data[15-i];
522     }
523     btstack_crypto_done(&btstack_crypto_ccm->btstack_crypto);
524 }
525 
526 static void btstack_crypto_ccm_handle_sn(btstack_crypto_ccm_t * btstack_crypto_ccm, const uint8_t * data){
527     // data is little-endian, flip on the fly
528     int i;
529     uint16_t bytes_to_process = btstack_min(btstack_crypto_ccm->block_len, 16);
530     for (i=0;i<bytes_to_process;i++){
531         btstack_crypto_ccm->output[i] = btstack_crypto_ccm->input[i] ^ data[15-i];
532     }
533 }
534 
535 static void btstack_crypto_ccm_next_block(btstack_crypto_ccm_t * btstack_crypto_ccm, btstack_crypto_ccm_state_t state_when_done){
536     uint16_t bytes_to_process = btstack_min(btstack_crypto_ccm->block_len, 16);
537     // next block
538     btstack_crypto_ccm->counter++;
539     btstack_crypto_ccm->input      += bytes_to_process;
540     btstack_crypto_ccm->output     += bytes_to_process;
541     btstack_crypto_ccm->block_len  -= bytes_to_process;
542     if (btstack_crypto_ccm->block_len == 0){
543         btstack_crypto_ccm->state = CCM_CALCULATE_S0;
544     }
545     else {
546         btstack_crypto_ccm->state = state_when_done;
547     }
548 }
549 
550 static void btstack_crypto_run(void){
551 
552     btstack_crypto_aes128_t        * btstack_crypto_aes128;
553     btstack_crypto_ccm_t           * btstack_crypto_ccm;
554     btstack_crypto_aes128_cmac_t   * btstack_crypto_cmac;
555 #ifdef ENABLE_ECC_P256
556     btstack_crypto_ecc_p256_t      * btstack_crypto_ec_p192;
557 #endif
558 
559     // stack up and running?
560     if (hci_get_state() != HCI_STATE_WORKING) return;
561 
562 	// already active?
563 	if (btstack_crypto_wait_for_hci_result) return;
564 
565 	// anything to do?
566 	if (btstack_linked_list_empty(&btstack_crypto_operations)) return;
567 
568     // can send a command?
569     if (!hci_can_send_command_packet_now()) return;
570 
571 	btstack_crypto_t * btstack_crypto = (btstack_crypto_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
572 	switch (btstack_crypto->operation){
573 		case BTSTACK_CRYPTO_RANDOM:
574 			btstack_crypto_wait_for_hci_result = 1;
575 		    hci_send_cmd(&hci_le_rand);
576 		    break;
577 		case BTSTACK_CRYPTO_AES128:
578             btstack_crypto_aes128 = (btstack_crypto_aes128_t *) btstack_crypto;
579 #ifdef USE_BTSTACK_AES128
580             btstack_aes128_calc(btstack_crypto_aes128->key, btstack_crypto_aes128->plaintext, btstack_crypto_aes128->ciphertext);
581             btstack_crypto_done(btstack_crypto);
582 #else
583             btstack_crypto_aes128_start(btstack_crypto_aes128->key, btstack_crypto_aes128->plaintext);
584 #endif
585 		    break;
586 		case BTSTACK_CRYPTO_CMAC_MESSAGE:
587 		case BTSTACK_CRYPTO_CMAC_GENERATOR:
588 			btstack_crypto_wait_for_hci_result = 1;
589 			btstack_crypto_cmac = (btstack_crypto_aes128_cmac_t *) btstack_crypto;
590 			if (btstack_crypto_cmac_state == CMAC_IDLE){
591 				btstack_crypto_cmac_start(btstack_crypto_cmac);
592 			} else {
593 				btstack_crypto_cmac_handle_aes_engine_ready(btstack_crypto_cmac);
594 			}
595 			break;
596 
597         case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK:
598         case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK:
599 #ifdef USE_BTSTACK_AES128
600             UNUSED(btstack_crypto_ccm);
601             log_error("ccm not implemented for software aes128 yet");
602 #else
603             btstack_crypto_ccm = (btstack_crypto_ccm_t *) btstack_crypto;
604             switch (btstack_crypto_ccm->state){
605                 case CCM_CALCULATE_X1:
606                     btstack_crypto_ccm_calc_x1(btstack_crypto_ccm);
607                     break;
608                 case CCM_CALCULATE_S0:
609                     btstack_crypto_ccm_calc_s0(btstack_crypto_ccm);
610                     break;
611                 case CCM_CALCULATE_SN:
612                     btstack_crypto_ccm_calc_sn(btstack_crypto_ccm);
613                     break;
614                 case CCM_CALCULATE_XN:
615                     btstack_crypto_ccm_calc_xn(btstack_crypto_ccm, btstack_crypto->operation == BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK ? btstack_crypto_ccm->input : btstack_crypto_ccm->output);
616                     break;
617                 default:
618                     break;
619             }
620 #endif
621             break;
622 
623 #ifdef ENABLE_ECC_P256
624         case BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY:
625             btstack_crypto_ec_p192 = (btstack_crypto_ecc_p256_t *) btstack_crypto;
626             switch (btstack_crypto_ecc_p256_key_generation_state){
627                 case ECC_P256_KEY_GENERATION_DONE:
628                     // done
629                     btstack_crypto_log_ec_publickey(btstack_crypto_ecc_p256_public_key);
630                     memcpy(btstack_crypto_ec_p192->public_key, btstack_crypto_ecc_p256_public_key, 64);
631                     btstack_linked_list_pop(&btstack_crypto_operations);
632                     (*btstack_crypto_ec_p192->btstack_crypto.context_callback.callback)(btstack_crypto_ec_p192->btstack_crypto.context_callback.context);
633                     break;
634                 case ECC_P256_KEY_GENERATION_IDLE:
635 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
636                     log_info("start ecc random");
637                     btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_GENERATING_RANDOM;
638                     btstack_crypto_ecc_p256_random_offset = 0;
639                     btstack_crypto_wait_for_hci_result = 1;
640                     hci_send_cmd(&hci_le_rand);
641 #else
642                     btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_W4_KEY;
643                     btstack_crypto_wait_for_hci_result = 1;
644                     hci_send_cmd(&hci_le_read_local_p256_public_key);
645 #endif
646                     break;
647 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
648                 case ECC_P256_KEY_GENERATION_GENERATING_RANDOM:
649                     log_info("more ecc random");
650                     btstack_crypto_wait_for_hci_result = 1;
651                     hci_send_cmd(&hci_le_rand);
652                     break;
653 #endif
654                 default:
655                     break;
656             }
657             break;
658         case BTSTACK_CRYPTO_ECC_P256_CALCULATE_DHKEY:
659             btstack_crypto_ec_p192 = (btstack_crypto_ecc_p256_t *) btstack_crypto;
660 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
661             btstack_crypto_ecc_p256_calculate_dhkey_software(btstack_crypto_ec_p192);
662             // done
663             btstack_linked_list_pop(&btstack_crypto_operations);
664             (*btstack_crypto_ec_p192->btstack_crypto.context_callback.callback)(btstack_crypto_ec_p192->btstack_crypto.context_callback.context);
665 #else
666             btstack_crypto_wait_for_hci_result = 1;
667             hci_send_cmd(&hci_le_generate_dhkey, &btstack_crypto_ec_p192->public_key[0], &btstack_crypto_ec_p192->public_key[32]);
668 #endif
669 #endif
670             break;
671 		default:
672 			break;
673 	}
674 }
675 
676 static void btstack_crypto_handle_random_data(const uint8_t * data, uint16_t len){
677     btstack_crypto_random_t * btstack_crypto_random;
678     btstack_crypto_t * btstack_crypto = (btstack_crypto_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
679     uint16_t bytes_to_copy;
680 	if (!btstack_crypto) return;
681     switch (btstack_crypto->operation){
682         case BTSTACK_CRYPTO_RANDOM:
683             btstack_crypto_random = (btstack_crypto_random_t*) btstack_crypto;
684             bytes_to_copy = btstack_min(btstack_crypto_random->size, len);
685             memcpy(btstack_crypto_random->buffer, data, bytes_to_copy);
686             btstack_crypto_random->buffer += bytes_to_copy;
687             btstack_crypto_random->size   -= bytes_to_copy;
688             // data processed, more?
689             if (!btstack_crypto_random->size) {
690                 // done
691                 btstack_linked_list_pop(&btstack_crypto_operations);
692                 (*btstack_crypto_random->btstack_crypto.context_callback.callback)(btstack_crypto_random->btstack_crypto.context_callback.context);
693             }
694             break;
695 #ifdef ENABLE_ECC_P256
696         case BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY:
697             memcpy(&btstack_crypto_ecc_p256_random[btstack_crypto_ecc_p256_random_len], data, 8);
698             btstack_crypto_ecc_p256_random_len += 8;
699             if (btstack_crypto_ecc_p256_random_len >= 64) {
700                 btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_ACTIVE;
701                 btstack_crypto_ecc_p256_generate_key_software();
702                 btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_DONE;
703             }
704             break;
705 #endif
706         default:
707             break;
708     }
709 	// more work?
710 	btstack_crypto_run();
711 }
712 
713 static void btstack_crypto_handle_encryption_result(const uint8_t * data){
714 	btstack_crypto_aes128_t      * btstack_crypto_aes128;
715 	btstack_crypto_aes128_cmac_t * btstack_crypto_cmac;
716     btstack_crypto_ccm_t         * btstack_crypto_ccm;
717 	uint8_t result[16];
718 
719     btstack_crypto_t * btstack_crypto = (btstack_crypto_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
720 	if (!btstack_crypto) return;
721 	switch (btstack_crypto->operation){
722 		case BTSTACK_CRYPTO_AES128:
723 			btstack_crypto_aes128 = (btstack_crypto_aes128_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
724 		    reverse_128(data, btstack_crypto_aes128->ciphertext);
725             btstack_crypto_done(btstack_crypto);
726 			break;
727 		case BTSTACK_CRYPTO_CMAC_GENERATOR:
728 		case BTSTACK_CRYPTO_CMAC_MESSAGE:
729 			btstack_crypto_cmac = (btstack_crypto_aes128_cmac_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
730 		    reverse_128(data, result);
731 		    btstack_crypto_cmac_handle_encryption_result(btstack_crypto_cmac, result);
732 			break;
733         case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK:
734             btstack_crypto_ccm = (btstack_crypto_ccm_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
735             switch (btstack_crypto_ccm->state){
736                 case CCM_W4_X1:
737                     reverse_128(data, btstack_crypto_ccm->x_i);
738                     btstack_crypto_ccm->state = CCM_CALCULATE_XN;
739                     break;
740                 case CCM_W4_XN:
741                     reverse_128(data, btstack_crypto_ccm->x_i);
742                     btstack_crypto_ccm->state = CCM_CALCULATE_SN;
743                     break;
744                 case CCM_W4_S0:
745                     btstack_crypto_ccm_handle_s0(btstack_crypto_ccm, data);
746                     break;
747                 case CCM_W4_SN:
748                     btstack_crypto_ccm_handle_sn(btstack_crypto_ccm, data);
749                     btstack_crypto_ccm_next_block(btstack_crypto_ccm, CCM_CALCULATE_XN);
750                     break;
751                 default:
752                     break;
753             }
754             break;
755         case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK:
756             btstack_crypto_ccm = (btstack_crypto_ccm_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
757             switch (btstack_crypto_ccm->state){
758                 case CCM_W4_X1:
759                     reverse_128(data, btstack_crypto_ccm->x_i);
760                     btstack_crypto_ccm->state = CCM_CALCULATE_SN;
761                     break;
762                 case CCM_W4_XN:
763                     reverse_128(data, btstack_crypto_ccm->x_i);
764                     btstack_crypto_ccm_next_block(btstack_crypto_ccm, CCM_CALCULATE_SN);
765                     break;
766                 case CCM_W4_S0:
767                     btstack_crypto_ccm_handle_s0(btstack_crypto_ccm, data);
768                     break;
769                 case CCM_W4_SN:
770                     btstack_crypto_ccm_handle_sn(btstack_crypto_ccm, data);
771                     btstack_crypto_ccm->state = CCM_CALCULATE_XN;
772                     break;
773                 default:
774                     break;
775             }
776             break;
777 		default:
778 			break;
779 	}
780 }
781 
782 static void btstack_crypto_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
783     UNUSED(cid);         // ok: there is no channel
784     UNUSED(size);        // ok: fixed format events read from HCI buffer
785 
786 #ifdef ENABLE_ECC_P256
787 #ifndef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
788     btstack_crypto_ecc_p256_t * btstack_crypto_ec_p192;
789 #endif
790 #endif
791 
792     if (packet_type != HCI_EVENT_PACKET)  return;
793 
794     switch (hci_event_packet_get_type(packet)){
795         case HCI_EVENT_COMMAND_COMPLETE:
796     	    if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_encrypt)){
797                 if (hci_get_state() != HCI_STATE_WORKING) return;
798                 if (!btstack_crypto_wait_for_hci_result) return;
799                 btstack_crypto_wait_for_hci_result = 0;
800     	        btstack_crypto_handle_encryption_result(&packet[6]);
801     	    }
802     	    if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_rand)){
803                 if (hci_get_state() != HCI_STATE_WORKING) return;
804                 if (!btstack_crypto_wait_for_hci_result) return;
805                 btstack_crypto_wait_for_hci_result = 0;
806     	        btstack_crypto_handle_random_data(&packet[6], 8);
807     	    }
808             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_commands)){
809                 int ecdh_operations_supported = (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+34] & 0x06) == 0x06;
810                 log_info("controller supports ECDH operation: %u", ecdh_operations_supported);
811 #ifdef ENABLE_ECC_P256
812 #ifndef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
813                 if (!ecdh_operations_supported){
814                     // mbedTLS can also be used if already available (and malloc is supported)
815                     log_error("ECC-P256 support enabled, but HCI Controller doesn't support it. Please add USE_MICRO_ECC_P256 to btstack_config.h");
816                 }
817 #endif
818 #endif
819             }
820             break;
821 
822 #ifdef ENABLE_ECC_P256
823 #ifndef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
824         case HCI_EVENT_LE_META:
825             btstack_crypto_ec_p192 = (btstack_crypto_ecc_p256_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
826             if (!btstack_crypto_ec_p192) break;
827             switch (hci_event_le_meta_get_subevent_code(packet)){
828                 case HCI_SUBEVENT_LE_READ_LOCAL_P256_PUBLIC_KEY_COMPLETE:
829                     if (btstack_crypto_ec_p192->btstack_crypto.operation != BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY) break;
830                     if (!btstack_crypto_wait_for_hci_result) return;
831                     btstack_crypto_wait_for_hci_result = 0;
832                     if (hci_subevent_le_read_local_p256_public_key_complete_get_status(packet)){
833                         log_error("Read Local P256 Public Key failed");
834                     }
835                     hci_subevent_le_read_local_p256_public_key_complete_get_dhkey_x(packet, &btstack_crypto_ecc_p256_public_key[0]);
836                     hci_subevent_le_read_local_p256_public_key_complete_get_dhkey_y(packet, &btstack_crypto_ecc_p256_public_key[32]);
837                     btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_DONE;
838                     break;
839                 case HCI_SUBEVENT_LE_GENERATE_DHKEY_COMPLETE:
840                     if (btstack_crypto_ec_p192->btstack_crypto.operation != BTSTACK_CRYPTO_ECC_P256_CALCULATE_DHKEY) break;
841                     if (!btstack_crypto_wait_for_hci_result) return;
842                     btstack_crypto_wait_for_hci_result = 0;
843                     if (hci_subevent_le_generate_dhkey_complete_get_status(packet)){
844                         log_error("Generate DHKEY failed -> abort");
845                     }
846                     hci_subevent_le_generate_dhkey_complete_get_dhkey(packet, btstack_crypto_ec_p192->dhkey);
847                     // done
848                     btstack_linked_list_pop(&btstack_crypto_operations);
849                     (*btstack_crypto_ec_p192->btstack_crypto.context_callback.callback)(btstack_crypto_ec_p192->btstack_crypto.context_callback.context);
850                     break;
851                 default:
852                     break;
853             }
854             break;
855 #endif
856 #endif
857         default:
858             break;
859     }
860 
861     // try processing
862 	btstack_crypto_run();
863 }
864 
865 void btstack_crypto_init(void){
866 	if (btstack_crypto_initialized) return;
867 	btstack_crypto_initialized = 1;
868 	// register with HCI
869     hci_event_callback_registration.callback = &btstack_crypto_event_handler;
870     hci_add_event_handler(&hci_event_callback_registration);
871 }
872 
873 void btstack_crypto_random_generate(btstack_crypto_random_t * request, uint8_t * buffer, uint16_t size, void (* callback)(void * arg), void * callback_arg){
874 	request->btstack_crypto.context_callback.callback  = callback;
875 	request->btstack_crypto.context_callback.context   = callback_arg;
876 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_RANDOM;
877 	request->buffer = buffer;
878 	request->size   = size;
879 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
880 	btstack_crypto_run();
881 }
882 
883 void btstack_crypto_aes128_encrypt(btstack_crypto_aes128_t * request, const uint8_t * key, const uint8_t * plaintext, uint8_t * ciphertext, void (* callback)(void * arg), void * callback_arg){
884 	request->btstack_crypto.context_callback.callback  = callback;
885 	request->btstack_crypto.context_callback.context   = callback_arg;
886 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_AES128;
887 	request->key 									   = key;
888 	request->plaintext      					       = plaintext;
889 	request->ciphertext 							   = ciphertext;
890 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
891 	btstack_crypto_run();
892 }
893 
894 void btstack_crypto_aes128_cmac_generator(btstack_crypto_aes128_cmac_t * request, const uint8_t * key, uint16_t size, uint8_t (*get_byte_callback)(uint16_t pos), uint8_t * hash, void (* callback)(void * arg), void * callback_arg){
895 	request->btstack_crypto.context_callback.callback  = callback;
896 	request->btstack_crypto.context_callback.context   = callback_arg;
897 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_CMAC_GENERATOR;
898 	request->key 									   = key;
899 	request->size 									   = size;
900 	request->get_byte_callback 						   = get_byte_callback;
901 	request->hash 									   = hash;
902 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
903 	btstack_crypto_run();
904 }
905 
906 void btstack_crypto_aes128_cmac_message(btstack_crypto_aes128_cmac_t * request, const uint8_t * key, uint16_t size, const uint8_t * message, uint8_t * hash, void (* callback)(void * arg), void * callback_arg){
907 	request->btstack_crypto.context_callback.callback  = callback;
908 	request->btstack_crypto.context_callback.context   = callback_arg;
909 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_CMAC_MESSAGE;
910 	request->key 									   = key;
911 	request->size 									   = size;
912 	request->message        						   = message;
913 	request->hash 									   = hash;
914 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
915 	btstack_crypto_run();
916 }
917 
918 void btstack_crypto_aes128_cmac_zero(btstack_crypto_aes128_cmac_t * request, uint16_t len, const uint8_t * message,  uint8_t * hash, void (* callback)(void * arg), void * callback_arg){
919     request->btstack_crypto.context_callback.callback  = callback;
920     request->btstack_crypto.context_callback.context   = callback_arg;
921     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CMAC_MESSAGE;
922     request->key                                       = zero;
923     request->size                                      = len;
924     request->message                                   = message;
925     request->hash                                      = hash;
926     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
927     btstack_crypto_run();
928 }
929 
930 #ifdef ENABLE_ECC_P256
931 void btstack_crypto_ecc_p256_generate_key(btstack_crypto_ecc_p256_t * request, uint8_t * public_key, void (* callback)(void * arg), void * callback_arg){
932     request->btstack_crypto.context_callback.callback  = callback;
933     request->btstack_crypto.context_callback.context   = callback_arg;
934     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY;
935     request->public_key                                = public_key;
936     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
937     btstack_crypto_run();
938 }
939 
940 void btstack_crypto_ecc_p256_calculate_dhkey(btstack_crypto_ecc_p256_t * request, const uint8_t * public_key, uint8_t * dhkey, void (* callback)(void * arg), void * callback_arg){
941     request->btstack_crypto.context_callback.callback  = callback;
942     request->btstack_crypto.context_callback.context   = callback_arg;
943     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_ECC_P256_CALCULATE_DHKEY;
944     request->public_key                                = (uint8_t *) public_key;
945     request->dhkey                                     = dhkey;
946     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
947     btstack_crypto_run();
948 }
949 
950 int btstack_crypto_ecc_p256_validate_public_key(const uint8_t * public_key){
951 
952     // validate public key using micro-ecc
953     int err = 0;
954 
955 #ifdef USE_MICRO_ECC_P256
956 #if uECC_SUPPORTS_secp256r1
957     // standard version
958     err = uECC_valid_public_key(public_key, uECC_secp256r1()) == 0;
959 #else
960     // static version
961     err = uECC_valid_public_key(public_key) == 0;
962 #endif
963 #endif
964 
965 #ifdef USE_MBEDTLS_ECC_P256
966     mbedtls_ecp_point Q;
967     mbedtls_ecp_point_init( &Q );
968     mbedtls_mpi_read_binary(&Q.X, &public_key[0], 32);
969     mbedtls_mpi_read_binary(&Q.Y, &public_key[32], 32);
970     mbedtls_mpi_lset(&Q.Z, 1);
971     err = mbedtls_ecp_check_pubkey(&mbedtls_ec_group, &Q);
972     mbedtls_ecp_point_free( & Q);
973 #endif
974 
975     if (err){
976         log_error("public key invalid %x", err);
977     }
978     return  err;
979 }
980 #endif
981 
982 void btstack_crypo_ccm_init(btstack_crypto_ccm_t * request, const uint8_t * key, const uint8_t * nonce, uint16_t message_len){
983     request->key         = key;
984     request->nonce       = nonce;
985     request->message_len = message_len;
986     request->counter     = 1;
987 }
988 
989 void btstack_crypo_ccm_get_authentication_value(btstack_crypto_ccm_t * request, uint8_t * authentication_value){
990     memcpy(authentication_value, request->x_i, 8);
991 }
992 
993 void btstack_crypto_ccm_encrypt_block(btstack_crypto_ccm_t * request, uint16_t block_len, const uint8_t * plaintext, uint8_t * ciphertext, void (* callback)(void * arg), void * callback_arg){
994     request->btstack_crypto.context_callback.callback  = callback;
995     request->btstack_crypto.context_callback.context   = callback_arg;
996     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK;
997     request->state                                     = CCM_CALCULATE_X1;
998     request->block_len                                 = block_len;
999     request->input                                     = plaintext;
1000     request->output                                    = ciphertext;
1001     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1002     btstack_crypto_run();
1003 }
1004 
1005 void btstack_crypto_ccm_decrypt_block(btstack_crypto_ccm_t * request, uint16_t block_len, const uint8_t * ciphertext, uint8_t * plaintext, void (* callback)(void * arg), void * callback_arg){
1006     request->btstack_crypto.context_callback.callback  = callback;
1007     request->btstack_crypto.context_callback.context   = callback_arg;
1008     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK;
1009     request->state                                     = CCM_CALCULATE_X1;
1010     request->block_len                                 = block_len;
1011     request->input                                     = ciphertext;
1012     request->output                                    = plaintext;
1013     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1014     btstack_crypto_run();
1015 }
1016 
1017