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