xref: /btstack/src/btstack_crypto.c (revision ff3cc4a5378c2f681cc9b75cf54d154a12a3051e)
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 static const 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             (void)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             (void)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             (void)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             (void)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     (void)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     (void)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("ststack_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     uint8_t Adata   = btstack_crypto_ccm->aad_len ? 1 : 0;
377     b0[0] = (Adata << 6) | (m_prime << 3) | 1 ;  // Adata, M', L' = L - 1
378     (void)memcpy(&b0[1], btstack_crypto_ccm->nonce, 13);
379     big_endian_store_16(b0, 14, btstack_crypto_ccm->message_len);
380 #ifdef DEBUG_CCM
381     printf("%16s: ", "B0");
382     printf_hexdump(b0, 16);
383 #endif
384 }
385 #endif
386 
387 #ifdef ENABLE_ECC_P256
388 
389 static void btstack_crypto_log_ec_publickey(const uint8_t * ec_q){
390     log_info("Elliptic curve: X");
391     log_info_hexdump(&ec_q[0],32);
392     log_info("Elliptic curve: Y");
393     log_info_hexdump(&ec_q[32],32);
394 }
395 
396 #if (defined(USE_MICRO_ECC_P256) && !defined(WICED_VERSION)) || defined(USE_MBEDTLS_ECC_P256)
397 // @return OK
398 static int sm_generate_f_rng(unsigned char * buffer, unsigned size){
399     if (btstack_crypto_ecc_p256_key_generation_state != ECC_P256_KEY_GENERATION_ACTIVE) return 0;
400     log_info("sm_generate_f_rng: size %u - offset %u", (int) size, btstack_crypto_ecc_p256_random_offset);
401     while (size) {
402         *buffer++ = btstack_crypto_ecc_p256_random[btstack_crypto_ecc_p256_random_offset++];
403         size--;
404     }
405     return 1;
406 }
407 #endif
408 #ifdef USE_MBEDTLS_ECC_P256
409 // @return error - just wrap sm_generate_f_rng
410 static int sm_generate_f_rng_mbedtls(void * context, unsigned char * buffer, size_t size){
411     UNUSED(context);
412     return sm_generate_f_rng(buffer, size) == 0;
413 }
414 #endif /* USE_MBEDTLS_ECC_P256 */
415 
416 static void btstack_crypto_ecc_p256_generate_key_software(void){
417 
418     btstack_crypto_ecc_p256_random_offset = 0;
419 
420     // generate EC key
421 #ifdef USE_MICRO_ECC_P256
422 
423 #ifndef WICED_VERSION
424     log_info("set uECC RNG for initial key generation with 64 random bytes");
425     // micro-ecc from WICED SDK uses its wiced_crypto_get_random by default - no need to set it
426     uECC_set_rng(&sm_generate_f_rng);
427 #endif /* WICED_VERSION */
428 
429 #if uECC_SUPPORTS_secp256r1
430     // standard version
431     uECC_make_key(btstack_crypto_ecc_p256_public_key, btstack_crypto_ecc_p256_d, uECC_secp256r1());
432 
433     // disable RNG again, as returning no randmon data lets shared key generation fail
434     log_info("disable uECC RNG in standard version after key generation");
435     uECC_set_rng(NULL);
436 #else
437     // static version
438     uECC_make_key(btstack_crypto_ecc_p256_public_key, btstack_crypto_ecc_p256_d);
439 #endif
440 #endif /* USE_MICRO_ECC_P256 */
441 
442 #ifdef USE_MBEDTLS_ECC_P256
443     mbedtls_mpi d;
444     mbedtls_ecp_point P;
445     mbedtls_mpi_init(&d);
446     mbedtls_ecp_point_init(&P);
447     int res = mbedtls_ecp_gen_keypair(&mbedtls_ec_group, &d, &P, &sm_generate_f_rng_mbedtls, NULL);
448     log_info("gen keypair %x", res);
449     mbedtls_mpi_write_binary(&P.X, &btstack_crypto_ecc_p256_public_key[0],  32);
450     mbedtls_mpi_write_binary(&P.Y, &btstack_crypto_ecc_p256_public_key[32], 32);
451     mbedtls_mpi_write_binary(&d, btstack_crypto_ecc_p256_d, 32);
452     mbedtls_ecp_point_free(&P);
453     mbedtls_mpi_free(&d);
454 #endif  /* USE_MBEDTLS_ECC_P256 */
455 }
456 
457 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
458 static void btstack_crypto_ecc_p256_calculate_dhkey_software(btstack_crypto_ecc_p256_t * btstack_crypto_ec_p192){
459     memset(btstack_crypto_ec_p192->dhkey, 0, 32);
460 
461 #ifdef USE_MICRO_ECC_P256
462 #if uECC_SUPPORTS_secp256r1
463     // standard version
464     uECC_shared_secret(btstack_crypto_ec_p192->public_key, btstack_crypto_ecc_p256_d, btstack_crypto_ec_p192->dhkey, uECC_secp256r1());
465 #else
466     // static version
467     uECC_shared_secret(btstack_crypto_ec_p192->public_key, btstack_crypto_ecc_p256_d, btstack_crypto_ec_p192->dhkey);
468 #endif
469 #endif
470 
471 #ifdef USE_MBEDTLS_ECC_P256
472     // da * Pb
473     mbedtls_mpi d;
474     mbedtls_ecp_point Q;
475     mbedtls_ecp_point DH;
476     mbedtls_mpi_init(&d);
477     mbedtls_ecp_point_init(&Q);
478     mbedtls_ecp_point_init(&DH);
479     mbedtls_mpi_read_binary(&d, btstack_crypto_ecc_p256_d, 32);
480     mbedtls_mpi_read_binary(&Q.X, &btstack_crypto_ec_p192->public_key[0] , 32);
481     mbedtls_mpi_read_binary(&Q.Y, &btstack_crypto_ec_p192->public_key[32], 32);
482     mbedtls_mpi_lset(&Q.Z, 1);
483     mbedtls_ecp_mul(&mbedtls_ec_group, &DH, &d, &Q, NULL, NULL);
484     mbedtls_mpi_write_binary(&DH.X, btstack_crypto_ec_p192->dhkey, 32);
485     mbedtls_ecp_point_free(&DH);
486     mbedtls_mpi_free(&d);
487     mbedtls_ecp_point_free(&Q);
488 #endif
489 
490     log_info("dhkey");
491     log_info_hexdump(btstack_crypto_ec_p192->dhkey, 32);
492 }
493 #endif
494 
495 #endif
496 
497 #ifdef USE_BTSTACK_AES128
498 // CCM not implemented using software AES128 yet
499 #else
500 
501 static void btstack_crypto_ccm_calc_s0(btstack_crypto_ccm_t * btstack_crypto_ccm){
502 #ifdef DEBUG_CCM
503     printf("btstack_crypto_ccm_calc_s0\n");
504 #endif
505     btstack_crypto_ccm->state = CCM_W4_S0;
506     btstack_crypto_ccm_setup_a_i(btstack_crypto_ccm, 0);
507     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_s);
508 }
509 
510 static void btstack_crypto_ccm_calc_sn(btstack_crypto_ccm_t * btstack_crypto_ccm){
511 #ifdef DEBUG_CCM
512     printf("btstack_crypto_ccm_calc_s%u\n", btstack_crypto_ccm->counter);
513 #endif
514     btstack_crypto_ccm->state = CCM_W4_SN;
515     btstack_crypto_ccm_setup_a_i(btstack_crypto_ccm, btstack_crypto_ccm->counter);
516     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_s);
517 }
518 
519 static void btstack_crypto_ccm_calc_x1(btstack_crypto_ccm_t * btstack_crypto_ccm){
520     uint8_t btstack_crypto_ccm_buffer[16];
521     btstack_crypto_ccm->state = CCM_W4_X1;
522     btstack_crypto_ccm_setup_b_0(btstack_crypto_ccm, btstack_crypto_ccm_buffer);
523     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_buffer);
524 }
525 
526 static void btstack_crypto_ccm_calc_xn(btstack_crypto_ccm_t * btstack_crypto_ccm, const uint8_t * plaintext){
527     uint8_t btstack_crypto_ccm_buffer[16];
528     btstack_crypto_ccm->state = CCM_W4_XN;
529 
530 #ifdef DEBUG_CCM
531     printf("%16s: ", "bn");
532     printf_hexdump(plaintext, 16);
533 #endif
534     uint8_t i;
535     uint8_t bytes_to_decrypt = btstack_crypto_ccm->block_len;
536     // use explicit min implementation as c-stat worried about out-of-bounds-reads
537     if (bytes_to_decrypt > 16) {
538         bytes_to_decrypt = 16;
539     }
540     for (i = 0; i < bytes_to_decrypt ; i++){
541         btstack_crypto_ccm_buffer[i] =  btstack_crypto_ccm->x_i[i] ^ plaintext[i];
542     }
543     (void)memcpy(&btstack_crypto_ccm_buffer[i], &btstack_crypto_ccm->x_i[i],
544                  16 - bytes_to_decrypt);
545 #ifdef DEBUG_CCM
546     printf("%16s: ", "Xn XOR bn");
547     printf_hexdump(btstack_crypto_ccm_buffer, 16);
548 #endif
549 
550     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_buffer);
551 }
552 #endif
553 
554 static void btstack_crypto_ccm_calc_aad_xn(btstack_crypto_ccm_t * btstack_crypto_ccm){
555     // store length
556     if (btstack_crypto_ccm->aad_offset == 0){
557         uint8_t len_buffer[2];
558         big_endian_store_16(len_buffer, 0, btstack_crypto_ccm->aad_len);
559         btstack_crypto_ccm->x_i[0] ^= len_buffer[0];
560         btstack_crypto_ccm->x_i[1] ^= len_buffer[1];
561         btstack_crypto_ccm->aad_remainder_len += 2;
562         btstack_crypto_ccm->aad_offset        += 2;
563     }
564 
565     // fill from input
566     uint16_t bytes_free = 16 - btstack_crypto_ccm->aad_remainder_len;
567     uint16_t bytes_to_copy = btstack_min(bytes_free, btstack_crypto_ccm->block_len);
568     while (bytes_to_copy){
569         btstack_crypto_ccm->x_i[btstack_crypto_ccm->aad_remainder_len++] ^= *btstack_crypto_ccm->input++;
570         btstack_crypto_ccm->aad_offset++;
571         btstack_crypto_ccm->block_len--;
572         bytes_to_copy--;
573         bytes_free--;
574     }
575 
576     // if last block, fill with zeros
577     if (btstack_crypto_ccm->aad_offset == (btstack_crypto_ccm->aad_len + 2)){
578         btstack_crypto_ccm->aad_remainder_len = 16;
579     }
580     // if not full, notify done
581     if (btstack_crypto_ccm->aad_remainder_len < 16){
582         btstack_crypto_done(&btstack_crypto_ccm->btstack_crypto);
583         return;
584     }
585 
586     // encrypt block
587 #ifdef DEBUG_CCM
588     printf("%16s: ", "Xn XOR Bn (aad)");
589     printf_hexdump(btstack_crypto_ccm->x_i, 16);
590 #endif
591 
592     btstack_crypto_ccm->aad_remainder_len = 0;
593     btstack_crypto_ccm->state = CCM_W4_AAD_XN;
594     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm->x_i);
595 }
596 
597 static void btstack_crypto_ccm_handle_s0(btstack_crypto_ccm_t * btstack_crypto_ccm, const uint8_t * data){
598     // data is little-endian, flip on the fly
599     int i;
600     for (i=0;i<16;i++){
601         btstack_crypto_ccm->x_i[i] = btstack_crypto_ccm->x_i[i] ^ data[15-i];
602     }
603     btstack_crypto_done(&btstack_crypto_ccm->btstack_crypto);
604 }
605 
606 static void btstack_crypto_ccm_handle_sn(btstack_crypto_ccm_t * btstack_crypto_ccm, const uint8_t * data){
607     // data is little-endian, flip on the fly
608     int i;
609     uint16_t bytes_to_process = btstack_min(btstack_crypto_ccm->block_len, 16);
610     for (i=0;i<bytes_to_process;i++){
611         btstack_crypto_ccm->output[i] = btstack_crypto_ccm->input[i] ^ data[15-i];
612     }
613 }
614 
615 static void btstack_crypto_ccm_next_block(btstack_crypto_ccm_t * btstack_crypto_ccm, btstack_crypto_ccm_state_t state_when_done){
616     uint16_t bytes_to_process = btstack_min(btstack_crypto_ccm->block_len, 16);
617     // next block
618     btstack_crypto_ccm->counter++;
619     btstack_crypto_ccm->input       += bytes_to_process;
620     btstack_crypto_ccm->output      += bytes_to_process;
621     btstack_crypto_ccm->block_len   -= bytes_to_process;
622     btstack_crypto_ccm->message_len -= bytes_to_process;
623 #ifdef DEBUG_CCM
624     printf("btstack_crypto_ccm_next_block (message len %u, block_len %u)\n", btstack_crypto_ccm->message_len, btstack_crypto_ccm->block_len);
625 #endif
626     if (btstack_crypto_ccm->message_len == 0){
627         btstack_crypto_ccm->state = CCM_CALCULATE_S0;
628     } else {
629         btstack_crypto_ccm->state = state_when_done;
630         if (btstack_crypto_ccm->block_len == 0){
631             btstack_crypto_done(&btstack_crypto_ccm->btstack_crypto);
632         }
633     }
634 }
635 
636 static void btstack_crypto_run(void){
637 
638     btstack_crypto_aes128_t        * btstack_crypto_aes128;
639     btstack_crypto_ccm_t           * btstack_crypto_ccm;
640     btstack_crypto_aes128_cmac_t   * btstack_crypto_cmac;
641 #ifdef ENABLE_ECC_P256
642     btstack_crypto_ecc_p256_t      * btstack_crypto_ec_p192;
643 #endif
644 
645     // stack up and running?
646     if (hci_get_state() != HCI_STATE_WORKING) return;
647 
648     // try to do as much as possible
649     while (true){
650 
651         // anything to do?
652         if (btstack_linked_list_empty(&btstack_crypto_operations)) return;
653 
654         // already active?
655         if (btstack_crypto_wait_for_hci_result) return;
656 
657         // can send a command?
658         if (!hci_can_send_command_packet_now()) return;
659 
660         // ok, find next task
661     	btstack_crypto_t * btstack_crypto = (btstack_crypto_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
662     	switch (btstack_crypto->operation){
663     		case BTSTACK_CRYPTO_RANDOM:
664     			btstack_crypto_wait_for_hci_result = 1;
665     		    hci_send_cmd(&hci_le_rand);
666     		    break;
667     		case BTSTACK_CRYPTO_AES128:
668                 btstack_crypto_aes128 = (btstack_crypto_aes128_t *) btstack_crypto;
669 #ifdef USE_BTSTACK_AES128
670                 btstack_aes128_calc(btstack_crypto_aes128->key, btstack_crypto_aes128->plaintext, btstack_crypto_aes128->ciphertext);
671                 btstack_crypto_done(btstack_crypto);
672 #else
673                 btstack_crypto_aes128_start(btstack_crypto_aes128->key, btstack_crypto_aes128->plaintext);
674 #endif
675     		    break;
676     		case BTSTACK_CRYPTO_CMAC_MESSAGE:
677     		case BTSTACK_CRYPTO_CMAC_GENERATOR:
678     			btstack_crypto_wait_for_hci_result = 1;
679     			btstack_crypto_cmac = (btstack_crypto_aes128_cmac_t *) btstack_crypto;
680     			if (btstack_crypto_cmac_state == CMAC_IDLE){
681     				btstack_crypto_cmac_start(btstack_crypto_cmac);
682     			} else {
683     				btstack_crypto_cmac_handle_aes_engine_ready(btstack_crypto_cmac);
684     			}
685     			break;
686 
687             case BTSTACK_CRYPTO_CCM_DIGEST_BLOCK:
688             case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK:
689             case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK:
690 #ifdef USE_BTSTACK_AES128
691                 UNUSED(btstack_crypto_ccm);
692                 // NOTE: infinite output of this message
693                 log_error("ccm not implemented for software aes128 yet");
694 #else
695                 btstack_crypto_ccm = (btstack_crypto_ccm_t *) btstack_crypto;
696                 switch (btstack_crypto_ccm->state){
697                     case CCM_CALCULATE_AAD_XN:
698                         btstack_crypto_ccm_calc_aad_xn(btstack_crypto_ccm);
699                         break;
700                     case CCM_CALCULATE_X1:
701                         btstack_crypto_ccm_calc_x1(btstack_crypto_ccm);
702                         break;
703                     case CCM_CALCULATE_S0:
704                         btstack_crypto_ccm_calc_s0(btstack_crypto_ccm);
705                         break;
706                     case CCM_CALCULATE_SN:
707                         btstack_crypto_ccm_calc_sn(btstack_crypto_ccm);
708                         break;
709                     case CCM_CALCULATE_XN:
710                         btstack_crypto_ccm_calc_xn(btstack_crypto_ccm, (btstack_crypto->operation == BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK) ? btstack_crypto_ccm->input : btstack_crypto_ccm->output);
711                         break;
712                     default:
713                         break;
714                 }
715 #endif
716                 break;
717 
718 #ifdef ENABLE_ECC_P256
719             case BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY:
720                 btstack_crypto_ec_p192 = (btstack_crypto_ecc_p256_t *) btstack_crypto;
721                 switch (btstack_crypto_ecc_p256_key_generation_state){
722                     case ECC_P256_KEY_GENERATION_DONE:
723                         // done
724                         btstack_crypto_log_ec_publickey(btstack_crypto_ecc_p256_public_key);
725                         (void)memcpy(btstack_crypto_ec_p192->public_key,
726                                      btstack_crypto_ecc_p256_public_key, 64);
727                         btstack_linked_list_pop(&btstack_crypto_operations);
728                         (*btstack_crypto_ec_p192->btstack_crypto.context_callback.callback)(btstack_crypto_ec_p192->btstack_crypto.context_callback.context);
729                         break;
730                     case ECC_P256_KEY_GENERATION_IDLE:
731 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
732                         log_info("start ecc random");
733                         btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_GENERATING_RANDOM;
734                         btstack_crypto_ecc_p256_random_offset = 0;
735                         btstack_crypto_wait_for_hci_result = 1;
736                         hci_send_cmd(&hci_le_rand);
737 #else
738                         btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_W4_KEY;
739                         btstack_crypto_wait_for_hci_result = 1;
740                         hci_send_cmd(&hci_le_read_local_p256_public_key);
741 #endif
742                         break;
743 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
744                     case ECC_P256_KEY_GENERATION_GENERATING_RANDOM:
745                         log_info("more ecc random");
746                         btstack_crypto_wait_for_hci_result = 1;
747                         hci_send_cmd(&hci_le_rand);
748                         break;
749 #endif
750                     default:
751                         break;
752                 }
753                 break;
754             case BTSTACK_CRYPTO_ECC_P256_CALCULATE_DHKEY:
755                 btstack_crypto_ec_p192 = (btstack_crypto_ecc_p256_t *) btstack_crypto;
756 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
757                 btstack_crypto_ecc_p256_calculate_dhkey_software(btstack_crypto_ec_p192);
758                 // done
759                 btstack_linked_list_pop(&btstack_crypto_operations);
760                 (*btstack_crypto_ec_p192->btstack_crypto.context_callback.callback)(btstack_crypto_ec_p192->btstack_crypto.context_callback.context);
761 #else
762                 btstack_crypto_wait_for_hci_result = 1;
763                 hci_send_cmd(&hci_le_generate_dhkey, &btstack_crypto_ec_p192->public_key[0], &btstack_crypto_ec_p192->public_key[32]);
764 #endif
765                 break;
766 
767 #endif /* ENABLE_ECC_P256 */
768 
769             default:
770                 break;
771         }
772     }
773 }
774 
775 static void btstack_crypto_handle_random_data(const uint8_t * data, uint16_t len){
776     btstack_crypto_random_t * btstack_crypto_random;
777     btstack_crypto_t * btstack_crypto = (btstack_crypto_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
778     uint16_t bytes_to_copy;
779 	if (!btstack_crypto) return;
780     switch (btstack_crypto->operation){
781         case BTSTACK_CRYPTO_RANDOM:
782             btstack_crypto_random = (btstack_crypto_random_t*) btstack_crypto;
783             bytes_to_copy = btstack_min(btstack_crypto_random->size, len);
784             (void)memcpy(btstack_crypto_random->buffer, data, bytes_to_copy);
785             btstack_crypto_random->buffer += bytes_to_copy;
786             btstack_crypto_random->size   -= bytes_to_copy;
787             // data processed, more?
788             if (!btstack_crypto_random->size) {
789                 // done
790                 btstack_linked_list_pop(&btstack_crypto_operations);
791                 (*btstack_crypto_random->btstack_crypto.context_callback.callback)(btstack_crypto_random->btstack_crypto.context_callback.context);
792             }
793             break;
794 #ifdef ENABLE_ECC_P256
795         case BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY:
796             (void)memcpy(&btstack_crypto_ecc_p256_random[btstack_crypto_ecc_p256_random_len],
797 			 data, 8);
798             btstack_crypto_ecc_p256_random_len += 8;
799             if (btstack_crypto_ecc_p256_random_len >= 64) {
800                 btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_ACTIVE;
801                 btstack_crypto_ecc_p256_generate_key_software();
802                 btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_DONE;
803             }
804             break;
805 #endif
806         default:
807             break;
808     }
809 	// more work?
810 	btstack_crypto_run();
811 }
812 
813 static void btstack_crypto_handle_encryption_result(const uint8_t * data){
814 	btstack_crypto_aes128_t      * btstack_crypto_aes128;
815 	btstack_crypto_aes128_cmac_t * btstack_crypto_cmac;
816     btstack_crypto_ccm_t         * btstack_crypto_ccm;
817 	uint8_t result[16];
818 
819     btstack_crypto_t * btstack_crypto = (btstack_crypto_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
820 	if (!btstack_crypto) return;
821 	switch (btstack_crypto->operation){
822 		case BTSTACK_CRYPTO_AES128:
823 			btstack_crypto_aes128 = (btstack_crypto_aes128_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
824 		    reverse_128(data, btstack_crypto_aes128->ciphertext);
825             btstack_crypto_done(btstack_crypto);
826 			break;
827 		case BTSTACK_CRYPTO_CMAC_GENERATOR:
828 		case BTSTACK_CRYPTO_CMAC_MESSAGE:
829 			btstack_crypto_cmac = (btstack_crypto_aes128_cmac_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
830 		    reverse_128(data, result);
831 		    btstack_crypto_cmac_handle_encryption_result(btstack_crypto_cmac, result);
832 			break;
833         case BTSTACK_CRYPTO_CCM_DIGEST_BLOCK:
834             btstack_crypto_ccm = (btstack_crypto_ccm_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
835             switch (btstack_crypto_ccm->state){
836                 case CCM_W4_X1:
837                     reverse_128(data, btstack_crypto_ccm->x_i);
838 #ifdef DEBUG_CCM
839     printf("%16s: ", "X1");
840     printf_hexdump(btstack_crypto_ccm->x_i, 16);
841 #endif
842                     btstack_crypto_ccm->aad_remainder_len = 0;
843                     btstack_crypto_ccm->state = CCM_CALCULATE_AAD_XN;
844                     break;
845                 case CCM_W4_AAD_XN:
846                     reverse_128(data, btstack_crypto_ccm->x_i);
847 #ifdef DEBUG_CCM
848     printf("%16s: ", "Xn+1 AAD");
849     printf_hexdump(btstack_crypto_ccm->x_i, 16);
850 #endif
851                     // more aad?
852                     if (btstack_crypto_ccm->aad_offset < (btstack_crypto_ccm->aad_len + 2)){
853                         btstack_crypto_ccm->state = CCM_CALCULATE_AAD_XN;
854                     } else {
855                         // done
856                         btstack_crypto_done(btstack_crypto);
857                     }
858                     break;
859                 default:
860                     break;
861             }
862             break;
863         case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK:
864             btstack_crypto_ccm = (btstack_crypto_ccm_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
865             switch (btstack_crypto_ccm->state){
866                 case CCM_W4_X1:
867                     reverse_128(data, btstack_crypto_ccm->x_i);
868 #ifdef DEBUG_CCM
869     printf("%16s: ", "X1");
870     printf_hexdump(btstack_crypto_ccm->x_i, 16);
871 #endif
872                     btstack_crypto_ccm->state = CCM_CALCULATE_XN;
873                     break;
874                 case CCM_W4_XN:
875                     reverse_128(data, btstack_crypto_ccm->x_i);
876 #ifdef DEBUG_CCM
877     printf("%16s: ", "Xn+1");
878     printf_hexdump(btstack_crypto_ccm->x_i, 16);
879 #endif
880                     btstack_crypto_ccm->state = CCM_CALCULATE_SN;
881                     break;
882                 case CCM_W4_S0:
883 #ifdef DEBUG_CCM
884     reverse_128(data, result);
885     printf("%16s: ", "X0");
886     printf_hexdump(btstack_crypto_ccm->x_i, 16);
887 #endif
888                     btstack_crypto_ccm_handle_s0(btstack_crypto_ccm, data);
889                     break;
890                 case CCM_W4_SN:
891 #ifdef DEBUG_CCM
892     reverse_128(data, result);
893     printf("%16s: ", "Sn");
894     printf_hexdump(btstack_crypto_ccm->x_i, 16);
895 #endif
896                     btstack_crypto_ccm_handle_sn(btstack_crypto_ccm, data);
897                     btstack_crypto_ccm_next_block(btstack_crypto_ccm, CCM_CALCULATE_XN);
898                     break;
899                 default:
900                     break;
901             }
902             break;
903         case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK:
904             btstack_crypto_ccm = (btstack_crypto_ccm_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
905             switch (btstack_crypto_ccm->state){
906                 case CCM_W4_X1:
907                     reverse_128(data, btstack_crypto_ccm->x_i);
908 #ifdef DEBUG_CCM
909     printf("%16s: ", "X1");
910     printf_hexdump(btstack_crypto_ccm->x_i, 16);
911 #endif
912                     btstack_crypto_ccm->state = CCM_CALCULATE_SN;
913                     break;
914                 case CCM_W4_XN:
915                     reverse_128(data, btstack_crypto_ccm->x_i);
916 #ifdef DEBUG_CCM
917     printf("%16s: ", "Xn+1");
918     printf_hexdump(btstack_crypto_ccm->x_i, 16);
919 #endif
920                     btstack_crypto_ccm_next_block(btstack_crypto_ccm, CCM_CALCULATE_SN);
921                     break;
922                 case CCM_W4_S0:
923                     btstack_crypto_ccm_handle_s0(btstack_crypto_ccm, data);
924                     break;
925                 case CCM_W4_SN:
926                     btstack_crypto_ccm_handle_sn(btstack_crypto_ccm, data);
927                     btstack_crypto_ccm->state = CCM_CALCULATE_XN;
928                     break;
929                 default:
930                     break;
931             }
932             break;
933 		default:
934 			break;
935 	}
936 }
937 
938 static void btstack_crypto_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
939     UNUSED(cid);         // ok: there is no channel
940     UNUSED(size);        // ok: fixed format events read from HCI buffer
941 
942 #ifdef ENABLE_ECC_P256
943 #ifndef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
944     btstack_crypto_ecc_p256_t * btstack_crypto_ec_p192;
945 #endif
946 #endif
947 
948     if (packet_type != HCI_EVENT_PACKET)  return;
949 
950     switch (hci_event_packet_get_type(packet)){
951         case BTSTACK_EVENT_STATE:
952             log_info("BTSTACK_EVENT_STATE");
953             if (btstack_event_state_get_state(packet) != HCI_STATE_HALTING) break;
954             if (!btstack_crypto_wait_for_hci_result) break;
955             // request stack to defer shutdown a bit
956             hci_halting_defer();
957             break;
958 
959         case HCI_EVENT_COMMAND_COMPLETE:
960     	    if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_encrypt)){
961                 if (!btstack_crypto_wait_for_hci_result) return;
962                 btstack_crypto_wait_for_hci_result = 0;
963     	        btstack_crypto_handle_encryption_result(&packet[6]);
964     	    }
965     	    if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_rand)){
966                 if (!btstack_crypto_wait_for_hci_result) return;
967                 btstack_crypto_wait_for_hci_result = 0;
968     	        btstack_crypto_handle_random_data(&packet[6], 8);
969     	    }
970             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_commands)){
971                 int ecdh_operations_supported = (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+34] & 0x06) == 0x06;
972                 log_info("controller supports ECDH operation: %u", ecdh_operations_supported);
973 #ifdef ENABLE_ECC_P256
974 #ifndef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
975                 if (!ecdh_operations_supported){
976                     // mbedTLS can also be used if already available (and malloc is supported)
977                     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");
978                 }
979 #endif
980 #endif
981             }
982             break;
983 
984 #ifdef ENABLE_ECC_P256
985 #ifndef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
986         case HCI_EVENT_LE_META:
987             btstack_crypto_ec_p192 = (btstack_crypto_ecc_p256_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
988             if (!btstack_crypto_ec_p192) break;
989             switch (hci_event_le_meta_get_subevent_code(packet)){
990                 case HCI_SUBEVENT_LE_READ_LOCAL_P256_PUBLIC_KEY_COMPLETE:
991                     if (btstack_crypto_ec_p192->btstack_crypto.operation != BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY) break;
992                     if (!btstack_crypto_wait_for_hci_result) return;
993                     btstack_crypto_wait_for_hci_result = 0;
994                     if (hci_subevent_le_read_local_p256_public_key_complete_get_status(packet)){
995                         log_error("Read Local P256 Public Key failed");
996                     }
997                     hci_subevent_le_read_local_p256_public_key_complete_get_dhkey_x(packet, &btstack_crypto_ecc_p256_public_key[0]);
998                     hci_subevent_le_read_local_p256_public_key_complete_get_dhkey_y(packet, &btstack_crypto_ecc_p256_public_key[32]);
999                     btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_DONE;
1000                     break;
1001                 case HCI_SUBEVENT_LE_GENERATE_DHKEY_COMPLETE:
1002                     if (btstack_crypto_ec_p192->btstack_crypto.operation != BTSTACK_CRYPTO_ECC_P256_CALCULATE_DHKEY) break;
1003                     if (!btstack_crypto_wait_for_hci_result) return;
1004                     btstack_crypto_wait_for_hci_result = 0;
1005                     if (hci_subevent_le_generate_dhkey_complete_get_status(packet)){
1006                         log_error("Generate DHKEY failed -> abort");
1007                     }
1008                     hci_subevent_le_generate_dhkey_complete_get_dhkey(packet, btstack_crypto_ec_p192->dhkey);
1009                     // done
1010                     btstack_linked_list_pop(&btstack_crypto_operations);
1011                     (*btstack_crypto_ec_p192->btstack_crypto.context_callback.callback)(btstack_crypto_ec_p192->btstack_crypto.context_callback.context);
1012                     break;
1013                 default:
1014                     break;
1015             }
1016             break;
1017 #endif
1018 #endif
1019         default:
1020             break;
1021     }
1022 
1023     // try processing
1024 	btstack_crypto_run();
1025 }
1026 
1027 void btstack_crypto_init(void){
1028 	if (btstack_crypto_initialized) return;
1029 	btstack_crypto_initialized = 1;
1030 
1031 	// register with HCI
1032     hci_event_callback_registration.callback = &btstack_crypto_event_handler;
1033     hci_add_event_handler(&hci_event_callback_registration);
1034 
1035 #ifdef USE_MBEDTLS_ECC_P256
1036 	mbedtls_ecp_group_init(&mbedtls_ec_group);
1037 	mbedtls_ecp_group_load(&mbedtls_ec_group, MBEDTLS_ECP_DP_SECP256R1);
1038 #endif
1039 }
1040 
1041 void btstack_crypto_random_generate(btstack_crypto_random_t * request, uint8_t * buffer, uint16_t size, void (* callback)(void * arg), void * callback_arg){
1042 	request->btstack_crypto.context_callback.callback  = callback;
1043 	request->btstack_crypto.context_callback.context   = callback_arg;
1044 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_RANDOM;
1045 	request->buffer = buffer;
1046 	request->size   = size;
1047 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1048 	btstack_crypto_run();
1049 }
1050 
1051 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){
1052 	request->btstack_crypto.context_callback.callback  = callback;
1053 	request->btstack_crypto.context_callback.context   = callback_arg;
1054 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_AES128;
1055 	request->key 									   = key;
1056 	request->plaintext      					       = plaintext;
1057 	request->ciphertext 							   = ciphertext;
1058 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1059 	btstack_crypto_run();
1060 }
1061 
1062 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){
1063 	request->btstack_crypto.context_callback.callback  = callback;
1064 	request->btstack_crypto.context_callback.context   = callback_arg;
1065 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_CMAC_GENERATOR;
1066 	request->key 									   = key;
1067 	request->size 									   = size;
1068 	request->data.get_byte_callback					   = get_byte_callback;
1069 	request->hash 									   = hash;
1070 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1071 	btstack_crypto_run();
1072 }
1073 
1074 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){
1075 	request->btstack_crypto.context_callback.callback  = callback;
1076 	request->btstack_crypto.context_callback.context   = callback_arg;
1077 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_CMAC_MESSAGE;
1078 	request->key 									   = key;
1079 	request->size 									   = size;
1080 	request->data.message      						   = message;
1081 	request->hash 									   = hash;
1082 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1083 	btstack_crypto_run();
1084 }
1085 
1086 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){
1087     request->btstack_crypto.context_callback.callback  = callback;
1088     request->btstack_crypto.context_callback.context   = callback_arg;
1089     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CMAC_MESSAGE;
1090     request->key                                       = zero;
1091     request->size                                      = len;
1092     request->data.message                              = message;
1093     request->hash                                      = hash;
1094     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1095     btstack_crypto_run();
1096 }
1097 
1098 #ifdef ENABLE_ECC_P256
1099 void btstack_crypto_ecc_p256_generate_key(btstack_crypto_ecc_p256_t * request, uint8_t * public_key, void (* callback)(void * arg), void * callback_arg){
1100     // reset key generation
1101     if (btstack_crypto_ecc_p256_key_generation_state == ECC_P256_KEY_GENERATION_DONE){
1102         btstack_crypto_ecc_p256_random_len = 0;
1103         btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_IDLE;
1104     }
1105     request->btstack_crypto.context_callback.callback  = callback;
1106     request->btstack_crypto.context_callback.context   = callback_arg;
1107     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY;
1108     request->public_key                                = public_key;
1109     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1110     btstack_crypto_run();
1111 }
1112 
1113 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){
1114     request->btstack_crypto.context_callback.callback  = callback;
1115     request->btstack_crypto.context_callback.context   = callback_arg;
1116     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_ECC_P256_CALCULATE_DHKEY;
1117     request->public_key                                = (uint8_t *) public_key;
1118     request->dhkey                                     = dhkey;
1119     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1120     btstack_crypto_run();
1121 }
1122 
1123 int btstack_crypto_ecc_p256_validate_public_key(const uint8_t * public_key){
1124 
1125     // validate public key using micro-ecc
1126     int err = 0;
1127 
1128 #ifdef USE_MICRO_ECC_P256
1129 #if uECC_SUPPORTS_secp256r1
1130     // standard version
1131     err = uECC_valid_public_key(public_key, uECC_secp256r1()) == 0;
1132 #else
1133     // static version
1134     err = uECC_valid_public_key(public_key) == 0;
1135 #endif
1136 #endif
1137 
1138 #ifdef USE_MBEDTLS_ECC_P256
1139     mbedtls_ecp_point Q;
1140     mbedtls_ecp_point_init( &Q );
1141     mbedtls_mpi_read_binary(&Q.X, &public_key[0], 32);
1142     mbedtls_mpi_read_binary(&Q.Y, &public_key[32], 32);
1143     mbedtls_mpi_lset(&Q.Z, 1);
1144     err = mbedtls_ecp_check_pubkey(&mbedtls_ec_group, &Q);
1145     mbedtls_ecp_point_free( & Q);
1146 #endif
1147 
1148     if (err){
1149         log_error("public key invalid %x", err);
1150     }
1151     return  err;
1152 }
1153 #endif
1154 
1155 void btstack_crypto_ccm_init(btstack_crypto_ccm_t * request, const uint8_t * key, const uint8_t * nonce, uint16_t message_len, uint16_t additional_authenticated_data_len, uint8_t auth_len){
1156     request->key         = key;
1157     request->nonce       = nonce;
1158     request->message_len = message_len;
1159     request->aad_len     = additional_authenticated_data_len;
1160     request->aad_offset  = 0;
1161     request->auth_len    = auth_len;
1162     request->counter     = 1;
1163     request->state       = CCM_CALCULATE_X1;
1164 }
1165 
1166 void btstack_crypto_ccm_digest(btstack_crypto_ccm_t * request, uint8_t * additional_authenticated_data, uint16_t additional_authenticated_data_len, void (* callback)(void * arg), void * callback_arg){
1167     // not implemented yet
1168     request->btstack_crypto.context_callback.callback  = callback;
1169     request->btstack_crypto.context_callback.context   = callback_arg;
1170     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CCM_DIGEST_BLOCK;
1171     request->block_len                                 = additional_authenticated_data_len;
1172     request->input                                     = additional_authenticated_data;
1173     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1174     btstack_crypto_run();
1175 }
1176 
1177 void btstack_crypto_ccm_get_authentication_value(btstack_crypto_ccm_t * request, uint8_t * authentication_value){
1178     (void)memcpy(authentication_value, request->x_i, request->auth_len);
1179 }
1180 
1181 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){
1182 #ifdef DEBUG_CCM
1183     printf("\nbtstack_crypto_ccm_encrypt_block, len %u\n", block_len);
1184 #endif
1185     request->btstack_crypto.context_callback.callback  = callback;
1186     request->btstack_crypto.context_callback.context   = callback_arg;
1187     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK;
1188     request->block_len                                 = block_len;
1189     request->input                                     = plaintext;
1190     request->output                                    = ciphertext;
1191     if (request->state != CCM_CALCULATE_X1){
1192         request->state  = CCM_CALCULATE_XN;
1193     }
1194     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1195     btstack_crypto_run();
1196 }
1197 
1198 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){
1199     request->btstack_crypto.context_callback.callback  = callback;
1200     request->btstack_crypto.context_callback.context   = callback_arg;
1201     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK;
1202     request->block_len                                 = block_len;
1203     request->input                                     = ciphertext;
1204     request->output                                    = plaintext;
1205     if (request->state != CCM_CALCULATE_X1){
1206         request->state  = CCM_CALCULATE_SN;
1207     }
1208     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1209     btstack_crypto_run();
1210 }
1211 
1212 // PTS only
1213 void btstack_crypto_ecc_p256_set_key(const uint8_t * public_key, const uint8_t * private_key){
1214 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
1215     (void)memcpy(btstack_crypto_ecc_p256_d, private_key, 32);
1216     (void)memcpy(btstack_crypto_ecc_p256_public_key, public_key, 64);
1217     btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_DONE;
1218 #else
1219     UNUSED(public_key);
1220     UNUSED(private_key);
1221 #endif
1222 }
1223 // Unit testing
1224 int btstack_crypto_idle(void){
1225     return btstack_linked_list_empty(&btstack_crypto_operations);
1226 }
1227 void btstack_crypto_reset(void){
1228     btstack_crypto_operations = NULL;
1229     btstack_crypto_wait_for_hci_result = 0;
1230 }
1231