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