xref: /btstack/src/btstack_crypto.c (revision 6015e1edc2e003d8108b1cab8d122222067a4ee9)
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     uint8_t m_prime = (btstack_crypto_ccm->auth_len - 2) / 2;
368     b0[0] = (m_prime << 3) | 1 ;  // Adata = 0, M', L' = L - 1
369     memcpy(&b0[1], btstack_crypto_ccm->nonce, 13);
370     big_endian_store_16(b0, 14, btstack_crypto_ccm->message_len);
371 }
372 #endif
373 
374 #ifdef ENABLE_ECC_P256
375 
376 static void btstack_crypto_log_ec_publickey(const uint8_t * ec_q){
377     log_info("Elliptic curve: X");
378     log_info_hexdump(&ec_q[0],32);
379     log_info("Elliptic curve: Y");
380     log_info_hexdump(&ec_q[32],32);
381 }
382 
383 #if (defined(USE_MICRO_ECC_P256) && !defined(WICED_VERSION)) || defined(USE_MBEDTLS_ECC_P256)
384 // @return OK
385 static int sm_generate_f_rng(unsigned char * buffer, unsigned size){
386     if (btstack_crypto_ecc_p256_key_generation_state != ECC_P256_KEY_GENERATION_ACTIVE) return 0;
387     log_info("sm_generate_f_rng: size %u - offset %u", (int) size, btstack_crypto_ecc_p256_random_offset);
388     while (size) {
389         *buffer++ = btstack_crypto_ecc_p256_random[btstack_crypto_ecc_p256_random_offset++];
390         size--;
391     }
392     return 1;
393 }
394 #endif
395 #ifdef USE_MBEDTLS_ECC_P256
396 // @return error - just wrap sm_generate_f_rng
397 static int sm_generate_f_rng_mbedtls(void * context, unsigned char * buffer, size_t size){
398     UNUSED(context);
399     return sm_generate_f_rng(buffer, size) == 0;
400 }
401 #endif /* USE_MBEDTLS_ECC_P256 */
402 
403 static void btstack_crypto_ecc_p256_generate_key_software(void){
404 
405     btstack_crypto_ecc_p256_random_offset = 0;
406 
407     // generate EC key
408 #ifdef USE_MICRO_ECC_P256
409 
410 #ifndef WICED_VERSION
411     log_info("set uECC RNG for initial key generation with 64 random bytes");
412     // micro-ecc from WICED SDK uses its wiced_crypto_get_random by default - no need to set it
413     uECC_set_rng(&sm_generate_f_rng);
414 #endif /* WICED_VERSION */
415 
416 #if uECC_SUPPORTS_secp256r1
417     // standard version
418     uECC_make_key(btstack_crypto_ecc_p256_public_key, btstack_crypto_ecc_p256_d, uECC_secp256r1());
419 
420     // disable RNG again, as returning no randmon data lets shared key generation fail
421     log_info("disable uECC RNG in standard version after key generation");
422     uECC_set_rng(NULL);
423 #else
424     // static version
425     uECC_make_key(btstack_crypto_ecc_p256_public_key, btstack_crypto_ecc_p256_d);
426 #endif
427 #endif /* USE_MICRO_ECC_P256 */
428 
429 #ifdef USE_MBEDTLS_ECC_P256
430     mbedtls_mpi d;
431     mbedtls_ecp_point P;
432     mbedtls_mpi_init(&d);
433     mbedtls_ecp_point_init(&P);
434     int res = mbedtls_ecp_gen_keypair(&mbedtls_ec_group, &d, &P, &sm_generate_f_rng_mbedtls, NULL);
435     log_info("gen keypair %x", res);
436     mbedtls_mpi_write_binary(&P.X, &btstack_crypto_ecc_p256_public_key[0],  32);
437     mbedtls_mpi_write_binary(&P.Y, &btstack_crypto_ecc_p256_public_key[32], 32);
438     mbedtls_mpi_write_binary(&d, btstack_crypto_ecc_p256_d, 32);
439     mbedtls_ecp_point_free(&P);
440     mbedtls_mpi_free(&d);
441 #endif  /* USE_MBEDTLS_ECC_P256 */
442 }
443 
444 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
445 static void btstack_crypto_ecc_p256_calculate_dhkey_software(btstack_crypto_ecc_p256_t * btstack_crypto_ec_p192){
446     memset(btstack_crypto_ec_p192->dhkey, 0, 32);
447 
448 #ifdef USE_MICRO_ECC_P256
449 #if uECC_SUPPORTS_secp256r1
450     // standard version
451     uECC_shared_secret(btstack_crypto_ec_p192->public_key, btstack_crypto_ecc_p256_d, btstack_crypto_ec_p192->dhkey, uECC_secp256r1());
452 #else
453     // static version
454     uECC_shared_secret(btstack_crypto_ec_p192->public_key, btstack_crypto_ecc_p256_d, btstack_crypto_ec_p192->dhkey);
455 #endif
456 #endif
457 
458 #ifdef USE_MBEDTLS_ECC_P256
459     // da * Pb
460     mbedtls_mpi d;
461     mbedtls_ecp_point Q;
462     mbedtls_ecp_point DH;
463     mbedtls_mpi_init(&d);
464     mbedtls_ecp_point_init(&Q);
465     mbedtls_ecp_point_init(&DH);
466     mbedtls_mpi_read_binary(&d, btstack_crypto_ecc_p256_d, 32);
467     mbedtls_mpi_read_binary(&Q.X, &btstack_crypto_ec_p192->public_key[0] , 32);
468     mbedtls_mpi_read_binary(&Q.Y, &btstack_crypto_ec_p192->public_key[32], 32);
469     mbedtls_mpi_lset(&Q.Z, 1);
470     mbedtls_ecp_mul(&mbedtls_ec_group, &DH, &d, &Q, NULL, NULL);
471     mbedtls_mpi_write_binary(&DH.X, btstack_crypto_ec_p192->dhkey, 32);
472     mbedtls_ecp_point_free(&DH);
473     mbedtls_mpi_free(&d);
474     mbedtls_ecp_point_free(&Q);
475 #endif
476 
477     log_info("dhkey");
478     log_info_hexdump(btstack_crypto_ec_p192->dhkey, 32);
479 }
480 #endif
481 
482 #endif
483 
484 #ifdef USE_BTSTACK_AES128
485 // CCM not implemented using software AES128 yet
486 #else
487 
488 static void btstack_crypto_ccm_calc_s0(btstack_crypto_ccm_t * btstack_crypto_ccm){
489     btstack_crypto_ccm->state = CCM_W4_S0;
490     btstack_crypto_ccm_setup_a_i(btstack_crypto_ccm, 0);
491     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_s);
492 }
493 
494 static void btstack_crypto_ccm_calc_sn(btstack_crypto_ccm_t * btstack_crypto_ccm){
495     btstack_crypto_ccm->state = CCM_W4_SN;
496     btstack_crypto_ccm_setup_a_i(btstack_crypto_ccm, btstack_crypto_ccm->counter);
497     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_s);
498 }
499 
500 static void btstack_crypto_ccm_calc_x1(btstack_crypto_ccm_t * btstack_crypto_ccm){
501     uint8_t btstack_crypto_ccm_buffer[16];
502     btstack_crypto_ccm->state = CCM_W4_X1;
503     btstack_crypto_ccm_setup_b_0(btstack_crypto_ccm, btstack_crypto_ccm_buffer);
504     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_buffer);
505 }
506 
507 static void btstack_crypto_ccm_calc_xn(btstack_crypto_ccm_t * btstack_crypto_ccm, const uint8_t * plaintext){
508     int i;
509     int bytes_to_decrypt;
510     uint8_t btstack_crypto_ccm_buffer[16];
511     btstack_crypto_ccm->state = CCM_W4_XN;
512     bytes_to_decrypt = btstack_min(btstack_crypto_ccm->block_len, 16);
513     i = 0;
514     while (i < bytes_to_decrypt){
515         btstack_crypto_ccm_buffer[i] =  btstack_crypto_ccm->x_i[i] ^ plaintext[i];
516         i++;
517     }
518     memcpy(&btstack_crypto_ccm_buffer[i], &btstack_crypto_ccm->x_i[i], 16 - bytes_to_decrypt);
519     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_buffer);
520 }
521 #endif
522 
523 static void btstack_crypto_ccm_handle_s0(btstack_crypto_ccm_t * btstack_crypto_ccm, const uint8_t * data){
524     // data is little-endian, flip on the fly
525     int i;
526     for (i=0;i<16;i++){
527         btstack_crypto_ccm->x_i[i] = btstack_crypto_ccm->x_i[i] ^ data[15-i];
528     }
529     btstack_crypto_done(&btstack_crypto_ccm->btstack_crypto);
530 }
531 
532 static void btstack_crypto_ccm_handle_sn(btstack_crypto_ccm_t * btstack_crypto_ccm, const uint8_t * data){
533     // data is little-endian, flip on the fly
534     int i;
535     uint16_t bytes_to_process = btstack_min(btstack_crypto_ccm->block_len, 16);
536     for (i=0;i<bytes_to_process;i++){
537         btstack_crypto_ccm->output[i] = btstack_crypto_ccm->input[i] ^ data[15-i];
538     }
539 }
540 
541 static void btstack_crypto_ccm_next_block(btstack_crypto_ccm_t * btstack_crypto_ccm, btstack_crypto_ccm_state_t state_when_done){
542     uint16_t bytes_to_process = btstack_min(btstack_crypto_ccm->block_len, 16);
543     // next block
544     btstack_crypto_ccm->counter++;
545     btstack_crypto_ccm->input      += bytes_to_process;
546     btstack_crypto_ccm->output     += bytes_to_process;
547     btstack_crypto_ccm->block_len  -= bytes_to_process;
548     if (btstack_crypto_ccm->block_len == 0){
549         btstack_crypto_ccm->state = CCM_CALCULATE_S0;
550     }
551     else {
552         btstack_crypto_ccm->state = state_when_done;
553     }
554 }
555 
556 static void btstack_crypto_run(void){
557 
558     btstack_crypto_aes128_t        * btstack_crypto_aes128;
559     btstack_crypto_ccm_t           * btstack_crypto_ccm;
560     btstack_crypto_aes128_cmac_t   * btstack_crypto_cmac;
561 #ifdef ENABLE_ECC_P256
562     btstack_crypto_ecc_p256_t      * btstack_crypto_ec_p192;
563 #endif
564 
565     // stack up and running?
566     if (hci_get_state() != HCI_STATE_WORKING) return;
567 
568 	// already active?
569 	if (btstack_crypto_wait_for_hci_result) return;
570 
571 	// anything to do?
572 	if (btstack_linked_list_empty(&btstack_crypto_operations)) return;
573 
574     // can send a command?
575     if (!hci_can_send_command_packet_now()) return;
576 
577 	btstack_crypto_t * btstack_crypto = (btstack_crypto_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
578 	switch (btstack_crypto->operation){
579 		case BTSTACK_CRYPTO_RANDOM:
580 			btstack_crypto_wait_for_hci_result = 1;
581 		    hci_send_cmd(&hci_le_rand);
582 		    break;
583 		case BTSTACK_CRYPTO_AES128:
584             btstack_crypto_aes128 = (btstack_crypto_aes128_t *) btstack_crypto;
585 #ifdef USE_BTSTACK_AES128
586             btstack_aes128_calc(btstack_crypto_aes128->key, btstack_crypto_aes128->plaintext, btstack_crypto_aes128->ciphertext);
587             btstack_crypto_done(btstack_crypto);
588 #else
589             btstack_crypto_aes128_start(btstack_crypto_aes128->key, btstack_crypto_aes128->plaintext);
590 #endif
591 		    break;
592 		case BTSTACK_CRYPTO_CMAC_MESSAGE:
593 		case BTSTACK_CRYPTO_CMAC_GENERATOR:
594 			btstack_crypto_wait_for_hci_result = 1;
595 			btstack_crypto_cmac = (btstack_crypto_aes128_cmac_t *) btstack_crypto;
596 			if (btstack_crypto_cmac_state == CMAC_IDLE){
597 				btstack_crypto_cmac_start(btstack_crypto_cmac);
598 			} else {
599 				btstack_crypto_cmac_handle_aes_engine_ready(btstack_crypto_cmac);
600 			}
601 			break;
602 
603         case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK:
604         case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK:
605 #ifdef USE_BTSTACK_AES128
606             UNUSED(btstack_crypto_ccm);
607             log_error("ccm not implemented for software aes128 yet");
608 #else
609             btstack_crypto_ccm = (btstack_crypto_ccm_t *) btstack_crypto;
610             switch (btstack_crypto_ccm->state){
611                 case CCM_CALCULATE_X1:
612                     btstack_crypto_ccm_calc_x1(btstack_crypto_ccm);
613                     break;
614                 case CCM_CALCULATE_S0:
615                     btstack_crypto_ccm_calc_s0(btstack_crypto_ccm);
616                     break;
617                 case CCM_CALCULATE_SN:
618                     btstack_crypto_ccm_calc_sn(btstack_crypto_ccm);
619                     break;
620                 case CCM_CALCULATE_XN:
621                     btstack_crypto_ccm_calc_xn(btstack_crypto_ccm, btstack_crypto->operation == BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK ? btstack_crypto_ccm->input : btstack_crypto_ccm->output);
622                     break;
623                 default:
624                     break;
625             }
626 #endif
627             break;
628 
629 #ifdef ENABLE_ECC_P256
630         case BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY:
631             btstack_crypto_ec_p192 = (btstack_crypto_ecc_p256_t *) btstack_crypto;
632             switch (btstack_crypto_ecc_p256_key_generation_state){
633                 case ECC_P256_KEY_GENERATION_DONE:
634                     // done
635                     btstack_crypto_log_ec_publickey(btstack_crypto_ecc_p256_public_key);
636                     memcpy(btstack_crypto_ec_p192->public_key, btstack_crypto_ecc_p256_public_key, 64);
637                     btstack_linked_list_pop(&btstack_crypto_operations);
638                     (*btstack_crypto_ec_p192->btstack_crypto.context_callback.callback)(btstack_crypto_ec_p192->btstack_crypto.context_callback.context);
639                     break;
640                 case ECC_P256_KEY_GENERATION_IDLE:
641 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
642                     log_info("start ecc random");
643                     btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_GENERATING_RANDOM;
644                     btstack_crypto_ecc_p256_random_offset = 0;
645                     btstack_crypto_wait_for_hci_result = 1;
646                     hci_send_cmd(&hci_le_rand);
647 #else
648                     btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_W4_KEY;
649                     btstack_crypto_wait_for_hci_result = 1;
650                     hci_send_cmd(&hci_le_read_local_p256_public_key);
651 #endif
652                     break;
653 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
654                 case ECC_P256_KEY_GENERATION_GENERATING_RANDOM:
655                     log_info("more ecc random");
656                     btstack_crypto_wait_for_hci_result = 1;
657                     hci_send_cmd(&hci_le_rand);
658                     break;
659 #endif
660                 default:
661                     break;
662             }
663             break;
664         case BTSTACK_CRYPTO_ECC_P256_CALCULATE_DHKEY:
665             btstack_crypto_ec_p192 = (btstack_crypto_ecc_p256_t *) btstack_crypto;
666 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
667             btstack_crypto_ecc_p256_calculate_dhkey_software(btstack_crypto_ec_p192);
668             // done
669             btstack_linked_list_pop(&btstack_crypto_operations);
670             (*btstack_crypto_ec_p192->btstack_crypto.context_callback.callback)(btstack_crypto_ec_p192->btstack_crypto.context_callback.context);
671 #else
672             btstack_crypto_wait_for_hci_result = 1;
673             hci_send_cmd(&hci_le_generate_dhkey, &btstack_crypto_ec_p192->public_key[0], &btstack_crypto_ec_p192->public_key[32]);
674 #endif
675             break;
676 
677 #endif /* ENABLE_ECC_P256 */
678 
679         default:
680             break;
681     }
682 }
683 
684 static void btstack_crypto_handle_random_data(const uint8_t * data, uint16_t len){
685     btstack_crypto_random_t * btstack_crypto_random;
686     btstack_crypto_t * btstack_crypto = (btstack_crypto_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
687     uint16_t bytes_to_copy;
688 	if (!btstack_crypto) return;
689     switch (btstack_crypto->operation){
690         case BTSTACK_CRYPTO_RANDOM:
691             btstack_crypto_random = (btstack_crypto_random_t*) btstack_crypto;
692             bytes_to_copy = btstack_min(btstack_crypto_random->size, len);
693             memcpy(btstack_crypto_random->buffer, data, bytes_to_copy);
694             btstack_crypto_random->buffer += bytes_to_copy;
695             btstack_crypto_random->size   -= bytes_to_copy;
696             // data processed, more?
697             if (!btstack_crypto_random->size) {
698                 // done
699                 btstack_linked_list_pop(&btstack_crypto_operations);
700                 (*btstack_crypto_random->btstack_crypto.context_callback.callback)(btstack_crypto_random->btstack_crypto.context_callback.context);
701             }
702             break;
703 #ifdef ENABLE_ECC_P256
704         case BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY:
705             memcpy(&btstack_crypto_ecc_p256_random[btstack_crypto_ecc_p256_random_len], data, 8);
706             btstack_crypto_ecc_p256_random_len += 8;
707             if (btstack_crypto_ecc_p256_random_len >= 64) {
708                 btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_ACTIVE;
709                 btstack_crypto_ecc_p256_generate_key_software();
710                 btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_DONE;
711             }
712             break;
713 #endif
714         default:
715             break;
716     }
717 	// more work?
718 	btstack_crypto_run();
719 }
720 
721 static void btstack_crypto_handle_encryption_result(const uint8_t * data){
722 	btstack_crypto_aes128_t      * btstack_crypto_aes128;
723 	btstack_crypto_aes128_cmac_t * btstack_crypto_cmac;
724     btstack_crypto_ccm_t         * btstack_crypto_ccm;
725 	uint8_t result[16];
726 
727     btstack_crypto_t * btstack_crypto = (btstack_crypto_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
728 	if (!btstack_crypto) return;
729 	switch (btstack_crypto->operation){
730 		case BTSTACK_CRYPTO_AES128:
731 			btstack_crypto_aes128 = (btstack_crypto_aes128_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
732 		    reverse_128(data, btstack_crypto_aes128->ciphertext);
733             btstack_crypto_done(btstack_crypto);
734 			break;
735 		case BTSTACK_CRYPTO_CMAC_GENERATOR:
736 		case BTSTACK_CRYPTO_CMAC_MESSAGE:
737 			btstack_crypto_cmac = (btstack_crypto_aes128_cmac_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
738 		    reverse_128(data, result);
739 		    btstack_crypto_cmac_handle_encryption_result(btstack_crypto_cmac, result);
740 			break;
741         case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK:
742             btstack_crypto_ccm = (btstack_crypto_ccm_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
743             switch (btstack_crypto_ccm->state){
744                 case CCM_W4_X1:
745                     reverse_128(data, btstack_crypto_ccm->x_i);
746                     btstack_crypto_ccm->state = CCM_CALCULATE_XN;
747                     break;
748                 case CCM_W4_XN:
749                     reverse_128(data, btstack_crypto_ccm->x_i);
750                     btstack_crypto_ccm->state = CCM_CALCULATE_SN;
751                     break;
752                 case CCM_W4_S0:
753                     btstack_crypto_ccm_handle_s0(btstack_crypto_ccm, data);
754                     break;
755                 case CCM_W4_SN:
756                     btstack_crypto_ccm_handle_sn(btstack_crypto_ccm, data);
757                     btstack_crypto_ccm_next_block(btstack_crypto_ccm, CCM_CALCULATE_XN);
758                     break;
759                 default:
760                     break;
761             }
762             break;
763         case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK:
764             btstack_crypto_ccm = (btstack_crypto_ccm_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
765             switch (btstack_crypto_ccm->state){
766                 case CCM_W4_X1:
767                     reverse_128(data, btstack_crypto_ccm->x_i);
768                     btstack_crypto_ccm->state = CCM_CALCULATE_SN;
769                     break;
770                 case CCM_W4_XN:
771                     reverse_128(data, btstack_crypto_ccm->x_i);
772                     btstack_crypto_ccm_next_block(btstack_crypto_ccm, CCM_CALCULATE_SN);
773                     break;
774                 case CCM_W4_S0:
775                     btstack_crypto_ccm_handle_s0(btstack_crypto_ccm, data);
776                     break;
777                 case CCM_W4_SN:
778                     btstack_crypto_ccm_handle_sn(btstack_crypto_ccm, data);
779                     btstack_crypto_ccm->state = CCM_CALCULATE_XN;
780                     break;
781                 default:
782                     break;
783             }
784             break;
785 		default:
786 			break;
787 	}
788 }
789 
790 static void btstack_crypto_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
791     UNUSED(cid);         // ok: there is no channel
792     UNUSED(size);        // ok: fixed format events read from HCI buffer
793 
794 #ifdef ENABLE_ECC_P256
795 #ifndef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
796     btstack_crypto_ecc_p256_t * btstack_crypto_ec_p192;
797 #endif
798 #endif
799 
800     if (packet_type != HCI_EVENT_PACKET)  return;
801 
802     switch (hci_event_packet_get_type(packet)){
803         case HCI_EVENT_COMMAND_COMPLETE:
804     	    if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_encrypt)){
805                 if (hci_get_state() != HCI_STATE_WORKING) return;
806                 if (!btstack_crypto_wait_for_hci_result) return;
807                 btstack_crypto_wait_for_hci_result = 0;
808     	        btstack_crypto_handle_encryption_result(&packet[6]);
809     	    }
810     	    if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_rand)){
811                 if (hci_get_state() != HCI_STATE_WORKING) return;
812                 if (!btstack_crypto_wait_for_hci_result) return;
813                 btstack_crypto_wait_for_hci_result = 0;
814     	        btstack_crypto_handle_random_data(&packet[6], 8);
815     	    }
816             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_commands)){
817                 int ecdh_operations_supported = (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+34] & 0x06) == 0x06;
818                 log_info("controller supports ECDH operation: %u", ecdh_operations_supported);
819 #ifdef ENABLE_ECC_P256
820 #ifndef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
821                 if (!ecdh_operations_supported){
822                     // mbedTLS can also be used if already available (and malloc is supported)
823                     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");
824                 }
825 #endif
826 #endif
827             }
828             break;
829 
830 #ifdef ENABLE_ECC_P256
831 #ifndef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
832         case HCI_EVENT_LE_META:
833             btstack_crypto_ec_p192 = (btstack_crypto_ecc_p256_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
834             if (!btstack_crypto_ec_p192) break;
835             switch (hci_event_le_meta_get_subevent_code(packet)){
836                 case HCI_SUBEVENT_LE_READ_LOCAL_P256_PUBLIC_KEY_COMPLETE:
837                     if (btstack_crypto_ec_p192->btstack_crypto.operation != BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY) break;
838                     if (!btstack_crypto_wait_for_hci_result) return;
839                     btstack_crypto_wait_for_hci_result = 0;
840                     if (hci_subevent_le_read_local_p256_public_key_complete_get_status(packet)){
841                         log_error("Read Local P256 Public Key failed");
842                     }
843                     hci_subevent_le_read_local_p256_public_key_complete_get_dhkey_x(packet, &btstack_crypto_ecc_p256_public_key[0]);
844                     hci_subevent_le_read_local_p256_public_key_complete_get_dhkey_y(packet, &btstack_crypto_ecc_p256_public_key[32]);
845                     btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_DONE;
846                     break;
847                 case HCI_SUBEVENT_LE_GENERATE_DHKEY_COMPLETE:
848                     if (btstack_crypto_ec_p192->btstack_crypto.operation != BTSTACK_CRYPTO_ECC_P256_CALCULATE_DHKEY) break;
849                     if (!btstack_crypto_wait_for_hci_result) return;
850                     btstack_crypto_wait_for_hci_result = 0;
851                     if (hci_subevent_le_generate_dhkey_complete_get_status(packet)){
852                         log_error("Generate DHKEY failed -> abort");
853                     }
854                     hci_subevent_le_generate_dhkey_complete_get_dhkey(packet, btstack_crypto_ec_p192->dhkey);
855                     // done
856                     btstack_linked_list_pop(&btstack_crypto_operations);
857                     (*btstack_crypto_ec_p192->btstack_crypto.context_callback.callback)(btstack_crypto_ec_p192->btstack_crypto.context_callback.context);
858                     break;
859                 default:
860                     break;
861             }
862             break;
863 #endif
864 #endif
865         default:
866             break;
867     }
868 
869     // try processing
870 	btstack_crypto_run();
871 }
872 
873 void btstack_crypto_init(void){
874 	if (btstack_crypto_initialized) return;
875 	btstack_crypto_initialized = 1;
876 
877 	// register with HCI
878     hci_event_callback_registration.callback = &btstack_crypto_event_handler;
879     hci_add_event_handler(&hci_event_callback_registration);
880 
881 #ifdef USE_MBEDTLS_ECC_P256
882 	mbedtls_ecp_group_init(&mbedtls_ec_group);
883 	mbedtls_ecp_group_load(&mbedtls_ec_group, MBEDTLS_ECP_DP_SECP256R1);
884 #endif
885 }
886 
887 void btstack_crypto_random_generate(btstack_crypto_random_t * request, uint8_t * buffer, uint16_t size, void (* callback)(void * arg), void * callback_arg){
888 	request->btstack_crypto.context_callback.callback  = callback;
889 	request->btstack_crypto.context_callback.context   = callback_arg;
890 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_RANDOM;
891 	request->buffer = buffer;
892 	request->size   = size;
893 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
894 	btstack_crypto_run();
895 }
896 
897 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){
898 	request->btstack_crypto.context_callback.callback  = callback;
899 	request->btstack_crypto.context_callback.context   = callback_arg;
900 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_AES128;
901 	request->key 									   = key;
902 	request->plaintext      					       = plaintext;
903 	request->ciphertext 							   = ciphertext;
904 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
905 	btstack_crypto_run();
906 }
907 
908 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){
909 	request->btstack_crypto.context_callback.callback  = callback;
910 	request->btstack_crypto.context_callback.context   = callback_arg;
911 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_CMAC_GENERATOR;
912 	request->key 									   = key;
913 	request->size 									   = size;
914 	request->data.get_byte_callback					   = get_byte_callback;
915 	request->hash 									   = hash;
916 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
917 	btstack_crypto_run();
918 }
919 
920 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){
921 	request->btstack_crypto.context_callback.callback  = callback;
922 	request->btstack_crypto.context_callback.context   = callback_arg;
923 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_CMAC_MESSAGE;
924 	request->key 									   = key;
925 	request->size 									   = size;
926 	request->data.message      						   = message;
927 	request->hash 									   = hash;
928 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
929 	btstack_crypto_run();
930 }
931 
932 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){
933     request->btstack_crypto.context_callback.callback  = callback;
934     request->btstack_crypto.context_callback.context   = callback_arg;
935     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CMAC_MESSAGE;
936     request->key                                       = zero;
937     request->size                                      = len;
938     request->data.message                              = message;
939     request->hash                                      = hash;
940     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
941     btstack_crypto_run();
942 }
943 
944 #ifdef ENABLE_ECC_P256
945 void btstack_crypto_ecc_p256_generate_key(btstack_crypto_ecc_p256_t * request, uint8_t * public_key, void (* callback)(void * arg), void * callback_arg){
946     // reset key generation
947     if (btstack_crypto_ecc_p256_key_generation_state == ECC_P256_KEY_GENERATION_DONE){
948         btstack_crypto_ecc_p256_random_len = 0;
949         btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_IDLE;
950     }
951     request->btstack_crypto.context_callback.callback  = callback;
952     request->btstack_crypto.context_callback.context   = callback_arg;
953     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY;
954     request->public_key                                = public_key;
955     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
956     btstack_crypto_run();
957 }
958 
959 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){
960     request->btstack_crypto.context_callback.callback  = callback;
961     request->btstack_crypto.context_callback.context   = callback_arg;
962     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_ECC_P256_CALCULATE_DHKEY;
963     request->public_key                                = (uint8_t *) public_key;
964     request->dhkey                                     = dhkey;
965     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
966     btstack_crypto_run();
967 }
968 
969 int btstack_crypto_ecc_p256_validate_public_key(const uint8_t * public_key){
970 
971     // validate public key using micro-ecc
972     int err = 0;
973 
974 #ifdef USE_MICRO_ECC_P256
975 #if uECC_SUPPORTS_secp256r1
976     // standard version
977     err = uECC_valid_public_key(public_key, uECC_secp256r1()) == 0;
978 #else
979     // static version
980     err = uECC_valid_public_key(public_key) == 0;
981 #endif
982 #endif
983 
984 #ifdef USE_MBEDTLS_ECC_P256
985     mbedtls_ecp_point Q;
986     mbedtls_ecp_point_init( &Q );
987     mbedtls_mpi_read_binary(&Q.X, &public_key[0], 32);
988     mbedtls_mpi_read_binary(&Q.Y, &public_key[32], 32);
989     mbedtls_mpi_lset(&Q.Z, 1);
990     err = mbedtls_ecp_check_pubkey(&mbedtls_ec_group, &Q);
991     mbedtls_ecp_point_free( & Q);
992 #endif
993 
994     if (err){
995         log_error("public key invalid %x", err);
996     }
997     return  err;
998 }
999 #endif
1000 
1001 void btstack_crypo_ccm_init(btstack_crypto_ccm_t * request, const uint8_t * key, const uint8_t * nonce, uint16_t message_len, uint8_t auth_len){
1002     request->key         = key;
1003     request->nonce       = nonce;
1004     request->message_len = message_len;
1005     request->auth_len    = auth_len;
1006     request->counter     = 1;
1007 }
1008 
1009 void btstack_crypo_ccm_get_authentication_value(btstack_crypto_ccm_t * request, uint8_t * authentication_value){
1010     memcpy(authentication_value, request->x_i, 8);
1011 }
1012 
1013 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){
1014     request->btstack_crypto.context_callback.callback  = callback;
1015     request->btstack_crypto.context_callback.context   = callback_arg;
1016     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK;
1017     request->state                                     = CCM_CALCULATE_X1;
1018     request->block_len                                 = block_len;
1019     request->input                                     = plaintext;
1020     request->output                                    = ciphertext;
1021     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1022     btstack_crypto_run();
1023 }
1024 
1025 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){
1026     request->btstack_crypto.context_callback.callback  = callback;
1027     request->btstack_crypto.context_callback.context   = callback_arg;
1028     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK;
1029     request->state                                     = CCM_CALCULATE_X1;
1030     request->block_len                                 = block_len;
1031     request->input                                     = ciphertext;
1032     request->output                                    = plaintext;
1033     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1034     btstack_crypto_run();
1035 }
1036 
1037