xref: /btstack/src/btstack_crypto.c (revision cd5f23a3250874824c01a2b3326a9522fea3f99f)
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 "btstack_bool.h"
48 #include "hci.h"
49 
50 //
51 // AES128 Configuration
52 //
53 
54 // By default, AES128 is computed by Bluetooth Controller using HCI Command/Event asynchronously
55 // as fallback/alternative, a software implementation can be used
56 // configure ECC implementations
57 #if defined(HAVE_AES128) && defined(ENABLE_SOFTWARE_AES128)
58 #error "If you have custom AES128 implementation (HAVE_AES128), please disable software AES128 (ENABLE_SOFTWARE_AES128) in bstack_config.h"
59 #endif
60 
61 #ifdef ENABLE_SOFTWARE_AES128
62 #define HAVE_AES128
63 #include "rijndael.h"
64 #endif
65 
66 #ifdef HAVE_AES128
67 #define USE_BTSTACK_AES128
68 #endif
69 
70 //
71 // ECC Configuration
72 //
73 
74 // backwards-compatitility ENABLE_MICRO_ECC_FOR_LE_SECURE_CONNECTIONS -> ENABLE_MICRO_ECC_P256
75 #if defined(ENABLE_MICRO_ECC_FOR_LE_SECURE_CONNECTIONS) && !defined(ENABLE_MICRO_ECC_P256)
76 #define ENABLE_MICRO_ECC_P256
77 #endif
78 
79 // configure ECC implementations
80 #if defined(ENABLE_MICRO_ECC_P256) && defined(HAVE_MBEDTLS_ECC_P256)
81 #error "If you have mbedTLS (HAVE_MBEDTLS_ECC_P256), please disable uECC (ENABLE_MICRO_ECC_P256) in bstack_config.h"
82 #endif
83 
84 // Software ECC-P256 implementation provided by micro-ecc
85 #ifdef ENABLE_MICRO_ECC_P256
86 #define ENABLE_ECC_P256
87 #define USE_MICRO_ECC_P256
88 #define USE_SOFTWARE_ECC_P256_IMPLEMENTATION
89 #include "uECC.h"
90 #endif
91 
92 // Software ECC-P256 implementation provided by mbedTLS
93 #ifdef HAVE_MBEDTLS_ECC_P256
94 #define ENABLE_ECC_P256
95 #define USE_MBEDTLS_ECC_P256
96 #define USE_SOFTWARE_ECC_P256_IMPLEMENTATION
97 #include "mbedtls/config.h"
98 #include "mbedtls/platform.h"
99 #include "mbedtls/ecp.h"
100 #endif
101 
102 #if defined(ENABLE_LE_SECURE_CONNECTIONS) && !defined(ENABLE_ECC_P256)
103 #define ENABLE_ECC_P256
104 #endif
105 
106 // debugging
107 // #define DEBUG_CCM
108 
109 typedef enum {
110     CMAC_IDLE,
111     CMAC_CALC_SUBKEYS,
112     CMAC_W4_SUBKEYS,
113     CMAC_CALC_MI,
114     CMAC_W4_MI,
115     CMAC_CALC_MLAST,
116     CMAC_W4_MLAST
117 } btstack_crypto_cmac_state_t;
118 
119 typedef enum {
120     ECC_P256_KEY_GENERATION_IDLE,
121     ECC_P256_KEY_GENERATION_GENERATING_RANDOM,
122     ECC_P256_KEY_GENERATION_ACTIVE,
123     ECC_P256_KEY_GENERATION_W4_KEY,
124     ECC_P256_KEY_GENERATION_DONE,
125 } btstack_crypto_ecc_p256_key_generation_state_t;
126 
127 static void btstack_crypto_run(void);
128 
129 static const uint8_t zero[16] = { 0 };
130 
131 static bool btstack_crypto_initialized;
132 static bool btstack_crypto_wait_for_hci_result;
133 static btstack_linked_list_t btstack_crypto_operations;
134 static btstack_packet_callback_registration_t hci_event_callback_registration;
135 
136 // state for AES-CMAC
137 #ifndef USE_BTSTACK_AES128
138 static btstack_crypto_cmac_state_t btstack_crypto_cmac_state;
139 static sm_key_t btstack_crypto_cmac_k;
140 static sm_key_t btstack_crypto_cmac_x;
141 static sm_key_t btstack_crypto_cmac_subkey;
142 static uint8_t  btstack_crypto_cmac_block_current;
143 static uint8_t  btstack_crypto_cmac_block_count;
144 #endif
145 
146 // state for AES-CCM
147 static uint8_t btstack_crypto_ccm_s[16];
148 
149 #ifdef ENABLE_ECC_P256
150 
151 static uint8_t  btstack_crypto_ecc_p256_public_key[64];
152 static uint8_t  btstack_crypto_ecc_p256_random[64];
153 static uint8_t  btstack_crypto_ecc_p256_random_len;
154 static uint8_t  btstack_crypto_ecc_p256_random_offset;
155 static btstack_crypto_ecc_p256_key_generation_state_t btstack_crypto_ecc_p256_key_generation_state;
156 
157 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
158 static uint8_t btstack_crypto_ecc_p256_d[32];
159 #endif
160 
161 // Software ECDH implementation provided by mbedtls
162 #ifdef USE_MBEDTLS_ECC_P256
163 static mbedtls_ecp_group   mbedtls_ec_group;
164 #endif
165 
166 #endif /* ENABLE_ECC_P256 */
167 
168 #ifdef ENABLE_SOFTWARE_AES128
169 // AES128 using public domain rijndael implementation
170 void btstack_aes128_calc(const uint8_t * key, const uint8_t * plaintext, uint8_t * ciphertext){
171     uint32_t rk[RKLENGTH(KEYBITS)];
172     int nrounds = rijndaelSetupEncrypt(rk, &key[0], KEYBITS);
173     rijndaelEncrypt(rk, nrounds, plaintext, ciphertext);
174 }
175 #endif
176 
177 static void btstack_crypto_done(btstack_crypto_t * btstack_crypto){
178     btstack_linked_list_pop(&btstack_crypto_operations);
179     (*btstack_crypto->context_callback.callback)(btstack_crypto->context_callback.context);
180 }
181 
182 static void btstack_crypto_cmac_shift_left_by_one_bit_inplace(int len, uint8_t * data){
183     int i;
184     int carry = 0;
185     for (i=len-1; i >= 0 ; i--){
186         int new_carry = data[i] >> 7;
187         data[i] = (data[i] << 1) | carry;
188         carry = new_carry;
189     }
190 }
191 
192 static uint8_t btstack_crypto_cmac_get_byte(btstack_crypto_aes128_cmac_t * btstack_crypto_cmac, uint16_t pos){
193     if (btstack_crypto_cmac->btstack_crypto.operation == BTSTACK_CRYPTO_CMAC_GENERATOR){
194         return (*btstack_crypto_cmac->data.get_byte_callback)(pos);
195     } else {
196         return btstack_crypto_cmac->data.message[pos];
197     }
198 }
199 
200 #ifdef USE_BTSTACK_AES128
201 
202 static void btstack_crypto_cmac_calc_subkeys(sm_key_t k0, sm_key_t k1, sm_key_t k2){
203     memcpy(k1, k0, 16);
204     btstack_crypto_cmac_shift_left_by_one_bit_inplace(16, k1);
205     if (k0[0] & 0x80){
206         k1[15] ^= 0x87;
207     }
208     memcpy(k2, k1, 16);
209     btstack_crypto_cmac_shift_left_by_one_bit_inplace(16, k2);
210     if (k1[0] & 0x80){
211         k2[15] ^= 0x87;
212     }
213 }
214 
215 static void btstack_crypto_cmac_calc(btstack_crypto_aes128_cmac_t * btstack_crypto_cmac) {
216     sm_key_t k0, k1, k2;
217     uint16_t i;
218 
219     btstack_aes128_calc(btstack_crypto_cmac->key, zero, k0);
220     btstack_crypto_cmac_calc_subkeys(k0, k1, k2);
221 
222     uint16_t cmac_block_count = (btstack_crypto_cmac->size + 15) / 16;
223 
224     // step 3: ..
225     if (cmac_block_count==0){
226         cmac_block_count = 1;
227     }
228 
229     // Step 5
230     sm_key_t cmac_x;
231     memset(cmac_x, 0, 16);
232 
233     // Step 6
234     sm_key_t cmac_y;
235     int block;
236     for (block = 0 ; block < cmac_block_count-1 ; block++){
237         for (i=0;i<16;i++){
238             cmac_y[i] = cmac_x[i] ^ btstack_crypto_cmac_get_byte(btstack_crypto_cmac, (block*16) + i);
239         }
240         btstack_aes128_calc(btstack_crypto_cmac->key, cmac_y, cmac_x);
241     }
242 
243     // step 4: set m_last
244     sm_key_t cmac_m_last;
245     bool last_block_complete = btstack_crypto_cmac->size != 0 && (btstack_crypto_cmac->size & 0x0f) == 0;
246     if (last_block_complete){
247         for (i=0;i<16;i++){
248             cmac_m_last[i] = btstack_crypto_cmac_get_byte(btstack_crypto_cmac, btstack_crypto_cmac->size - 16 + i) ^ k1[i];
249         }
250     } else {
251         uint16_t valid_octets_in_last_block = btstack_crypto_cmac->size & 0x0f;
252         for (i=0;i<16;i++){
253             if (i < valid_octets_in_last_block){
254                 cmac_m_last[i] = btstack_crypto_cmac_get_byte(btstack_crypto_cmac, (btstack_crypto_cmac->size & 0xfff0) + i) ^ k2[i];
255                 continue;
256             }
257             if (i == valid_octets_in_last_block){
258                 cmac_m_last[i] = 0x80 ^ k2[i];
259                 continue;
260             }
261             cmac_m_last[i] = k2[i];
262         }
263     }
264 
265     for (i=0;i<16;i++){
266         cmac_y[i] = cmac_x[i] ^ cmac_m_last[i];
267     }
268 
269     // Step 7
270     btstack_aes128_calc(btstack_crypto_cmac->key, cmac_y, btstack_crypto_cmac->hash);
271 }
272 #else
273 
274 static void btstack_crypto_aes128_start(const sm_key_t key, const sm_key_t plaintext){
275     uint8_t key_flipped[16];
276     uint8_t plaintext_flipped[16];
277     reverse_128(key, key_flipped);
278     reverse_128(plaintext, plaintext_flipped);
279     btstack_crypto_wait_for_hci_result = 1;
280     hci_send_cmd(&hci_le_encrypt, key_flipped, plaintext_flipped);
281 }
282 
283 static inline void btstack_crypto_cmac_next_state(void){
284     btstack_crypto_cmac_state = (btstack_crypto_cmac_state_t) (((int)btstack_crypto_cmac_state) + 1);
285 }
286 
287 static int btstack_crypto_cmac_last_block_complete(btstack_crypto_aes128_cmac_t * btstack_crypto_cmac){
288 	uint16_t len = btstack_crypto_cmac->size;
289     if (len == 0u) return 0u;
290     return (len & 0x0fu) == 0u;
291 }
292 
293 static void btstack_crypto_cmac_handle_aes_engine_ready(btstack_crypto_aes128_cmac_t * btstack_crypto_cmac){
294     switch (btstack_crypto_cmac_state){
295         case CMAC_CALC_SUBKEYS: {
296             btstack_crypto_cmac_next_state();
297             btstack_crypto_aes128_start(btstack_crypto_cmac_k, zero);
298             break;
299         }
300         case CMAC_CALC_MI: {
301             int j;
302             sm_key_t y;
303             for (j=0;j<16;j++){
304                 y[j] = btstack_crypto_cmac_x[j] ^ btstack_crypto_cmac_get_byte(btstack_crypto_cmac, (btstack_crypto_cmac_block_current*16u) + j);
305             }
306             btstack_crypto_cmac_block_current++;
307             btstack_crypto_cmac_next_state();
308             btstack_crypto_aes128_start(btstack_crypto_cmac_k, y);
309             break;
310         }
311         case CMAC_CALC_MLAST: {
312             sm_key_t k1;
313             (void)memcpy(k1, btstack_crypto_cmac_subkey, 16);
314             btstack_crypto_cmac_shift_left_by_one_bit_inplace(16, k1);
315             if (btstack_crypto_cmac_subkey[0u] & 0x80u){
316                 k1[15u] ^= 0x87u;
317             }
318             sm_key_t k2;
319             (void)memcpy(k2, k1, 16);
320             btstack_crypto_cmac_shift_left_by_one_bit_inplace(16, k2);
321             if (k1[0u] & 0x80u){
322                 k2[15u] ^= 0x87u;
323             }
324 
325             log_info_key("k", btstack_crypto_cmac_k);
326             log_info_key("k1", k1);
327             log_info_key("k2", k2);
328 
329             // step 4: set m_last
330             int i;
331             sm_key_t btstack_crypto_cmac_m_last;
332             if (btstack_crypto_cmac_last_block_complete(btstack_crypto_cmac)){
333                 for (i=0;i<16;i++){
334                     btstack_crypto_cmac_m_last[i] = btstack_crypto_cmac_get_byte(btstack_crypto_cmac, btstack_crypto_cmac->size - 16u + i) ^ k1[i];
335                 }
336             } else {
337                 int valid_octets_in_last_block = btstack_crypto_cmac->size & 0x0fu;
338                 for (i=0;i<16;i++){
339                     if (i < valid_octets_in_last_block){
340                         btstack_crypto_cmac_m_last[i] = btstack_crypto_cmac_get_byte(btstack_crypto_cmac, (btstack_crypto_cmac->size & 0xfff0u) + i) ^ k2[i];
341                         continue;
342                     }
343                     if (i == valid_octets_in_last_block){
344                         btstack_crypto_cmac_m_last[i] = 0x80u ^ k2[i];
345                         continue;
346                     }
347                     btstack_crypto_cmac_m_last[i] = k2[i];
348                 }
349             }
350             sm_key_t y;
351             for (i=0;i<16;i++){
352                 y[i] = btstack_crypto_cmac_x[i] ^ btstack_crypto_cmac_m_last[i];
353             }
354             btstack_crypto_cmac_block_current++;
355             btstack_crypto_cmac_next_state();
356             btstack_crypto_aes128_start(btstack_crypto_cmac_k, y);
357             break;
358         }
359         default:
360             log_info("btstack_crypto_cmac_handle_aes_engine_ready called in state %u", btstack_crypto_cmac_state);
361             break;
362     }
363 }
364 
365 static void btstack_crypto_cmac_handle_encryption_result(btstack_crypto_aes128_cmac_t * btstack_crypto_cmac, sm_key_t data){
366     switch (btstack_crypto_cmac_state){
367         case CMAC_W4_SUBKEYS:
368             (void)memcpy(btstack_crypto_cmac_subkey, data, 16);
369             // next
370             btstack_crypto_cmac_state = (btstack_crypto_cmac_block_current < (btstack_crypto_cmac_block_count - 1u)) ? CMAC_CALC_MI : CMAC_CALC_MLAST;
371             break;
372         case CMAC_W4_MI:
373             (void)memcpy(btstack_crypto_cmac_x, data, 16);
374             btstack_crypto_cmac_state = (btstack_crypto_cmac_block_current < (btstack_crypto_cmac_block_count - 1u)) ? CMAC_CALC_MI : CMAC_CALC_MLAST;
375             break;
376         case CMAC_W4_MLAST:
377             // done
378             log_info("Setting CMAC Engine to IDLE");
379             btstack_crypto_cmac_state = CMAC_IDLE;
380             log_info_key("CMAC", data);
381             (void)memcpy(btstack_crypto_cmac->hash, data, 16);
382 			btstack_linked_list_pop(&btstack_crypto_operations);
383 			(*btstack_crypto_cmac->btstack_crypto.context_callback.callback)(btstack_crypto_cmac->btstack_crypto.context_callback.context);
384             break;
385         default:
386             log_info("btstack_crypto_cmac_handle_encryption_result called in state %u", btstack_crypto_cmac_state);
387             break;
388     }
389 }
390 
391 static void btstack_crypto_cmac_start(btstack_crypto_aes128_cmac_t * btstack_crypto_cmac){
392 
393     (void)memcpy(btstack_crypto_cmac_k, btstack_crypto_cmac->key, 16);
394     memset(btstack_crypto_cmac_x, 0, 16);
395     btstack_crypto_cmac_block_current = 0;
396 
397     // step 2: n := ceil(len/const_Bsize);
398     btstack_crypto_cmac_block_count = (btstack_crypto_cmac->size + 15u) / 16u;
399 
400     // step 3: ..
401     if (btstack_crypto_cmac_block_count==0u){
402         btstack_crypto_cmac_block_count = 1;
403     }
404     log_info("btstack_crypto_cmac_start: len %u, block count %u", btstack_crypto_cmac->size, btstack_crypto_cmac_block_count);
405 
406     // first, we need to compute l for k1, k2, and m_last
407     btstack_crypto_cmac_state = CMAC_CALC_SUBKEYS;
408 
409     // let's go
410     btstack_crypto_cmac_handle_aes_engine_ready(btstack_crypto_cmac);
411 }
412 #endif
413 
414 /*
415   To encrypt the message data we use Counter (CTR) mode.  We first
416   define the key stream blocks by:
417 
418       S_i := E( K, A_i )   for i=0, 1, 2, ...
419 
420   The values A_i are formatted as follows, where the Counter field i is
421   encoded in most-significant-byte first order:
422 
423   Octet Number   Contents
424   ------------   ---------
425   0              Flags
426   1 ... 15-L     Nonce N
427   16-L ... 15    Counter i
428 
429   Bit Number   Contents
430   ----------   ----------------------
431   7            Reserved (always zero)
432   6            Reserved (always zero)
433   5 ... 3      Zero
434   2 ... 0      L'
435 */
436 
437 static void btstack_crypto_ccm_setup_a_i(btstack_crypto_ccm_t * btstack_crypto_ccm, uint16_t counter){
438     btstack_crypto_ccm_s[0] = 1;  // L' = L - 1
439     (void)memcpy(&btstack_crypto_ccm_s[1], btstack_crypto_ccm->nonce, 13);
440     big_endian_store_16(btstack_crypto_ccm_s, 14, counter);
441 #ifdef DEBUG_CCM
442     printf("btstack_crypto_ccm_setup_a_%u\n", counter);
443     printf("%16s: ", "ai");
444     printf_hexdump(btstack_crypto_ccm_s, 16);
445 #endif
446 }
447 
448 /*
449  The first step is to compute the authentication field T.  This is
450    done using CBC-MAC [MAC].  We first define a sequence of blocks B_0,
451    B_1, ..., B_n and then apply CBC-MAC to these blocks.
452 
453    The first block B_0 is formatted as follows, where l(m) is encoded in
454    most-significant-byte first order:
455 
456       Octet Number   Contents
457       ------------   ---------
458       0              Flags
459       1 ... 15-L     Nonce N
460       16-L ... 15    l(m)
461 
462    Within the first block B_0, the Flags field is formatted as follows:
463 
464       Bit Number   Contents
465       ----------   ----------------------
466       7            Reserved (always zero)
467       6            Adata
468       5 ... 3      M'
469       2 ... 0      L'
470  */
471 
472 static void btstack_crypto_ccm_setup_b_0(btstack_crypto_ccm_t * btstack_crypto_ccm, uint8_t * b0){
473     uint8_t m_prime = (btstack_crypto_ccm->auth_len - 2u) / 2u;
474     uint8_t Adata   = btstack_crypto_ccm->aad_len ? 1 : 0;
475     b0[0u] = (Adata << 6u) | (m_prime << 3u) | 1u ;  // Adata, M', L' = L - 1
476     (void)memcpy(&b0[1], btstack_crypto_ccm->nonce, 13);
477     big_endian_store_16(b0, 14, btstack_crypto_ccm->message_len);
478 #ifdef DEBUG_CCM
479     printf("%16s: ", "B0");
480     printf_hexdump(b0, 16);
481 #endif
482 }
483 
484 #ifdef ENABLE_ECC_P256
485 
486 static void btstack_crypto_log_ec_publickey(const uint8_t * ec_q){
487     log_info("Elliptic curve: X");
488     log_info_hexdump(&ec_q[0],32);
489     log_info("Elliptic curve: Y");
490     log_info_hexdump(&ec_q[32],32);
491 }
492 
493 #if (defined(USE_MICRO_ECC_P256) && !defined(WICED_VERSION)) || defined(USE_MBEDTLS_ECC_P256)
494 // @return OK
495 static int sm_generate_f_rng(unsigned char * buffer, unsigned size){
496     if (btstack_crypto_ecc_p256_key_generation_state != ECC_P256_KEY_GENERATION_ACTIVE) return 0;
497     log_info("sm_generate_f_rng: size %u - offset %u", (int) size, btstack_crypto_ecc_p256_random_offset);
498     while (size) {
499         *buffer++ = btstack_crypto_ecc_p256_random[btstack_crypto_ecc_p256_random_offset++];
500         size--;
501     }
502     return 1;
503 }
504 #endif
505 #ifdef USE_MBEDTLS_ECC_P256
506 // @return error - just wrap sm_generate_f_rng
507 static int sm_generate_f_rng_mbedtls(void * context, unsigned char * buffer, size_t size){
508     UNUSED(context);
509     return sm_generate_f_rng(buffer, size) == 0;
510 }
511 #endif /* USE_MBEDTLS_ECC_P256 */
512 
513 static void btstack_crypto_ecc_p256_generate_key_software(void){
514 
515     btstack_crypto_ecc_p256_random_offset = 0;
516 
517     // generate EC key
518 #ifdef USE_MICRO_ECC_P256
519 
520 #ifndef WICED_VERSION
521     log_info("set uECC RNG for initial key generation with 64 random bytes");
522     // micro-ecc from WICED SDK uses its wiced_crypto_get_random by default - no need to set it
523     uECC_set_rng(&sm_generate_f_rng);
524 #endif /* WICED_VERSION */
525 
526 #if uECC_SUPPORTS_secp256r1
527     // standard version
528     uECC_make_key(btstack_crypto_ecc_p256_public_key, btstack_crypto_ecc_p256_d, uECC_secp256r1());
529 
530     // disable RNG again, as returning no randmon data lets shared key generation fail
531     log_info("disable uECC RNG in standard version after key generation");
532     uECC_set_rng(NULL);
533 #else
534     // static version
535     uECC_make_key(btstack_crypto_ecc_p256_public_key, btstack_crypto_ecc_p256_d);
536 #endif
537 #endif /* USE_MICRO_ECC_P256 */
538 
539 #ifdef USE_MBEDTLS_ECC_P256
540     mbedtls_mpi d;
541     mbedtls_ecp_point P;
542     mbedtls_mpi_init(&d);
543     mbedtls_ecp_point_init(&P);
544     int res = mbedtls_ecp_gen_keypair(&mbedtls_ec_group, &d, &P, &sm_generate_f_rng_mbedtls, NULL);
545     log_info("gen keypair %x", res);
546     mbedtls_mpi_write_binary(&P.X, &btstack_crypto_ecc_p256_public_key[0],  32);
547     mbedtls_mpi_write_binary(&P.Y, &btstack_crypto_ecc_p256_public_key[32], 32);
548     mbedtls_mpi_write_binary(&d, btstack_crypto_ecc_p256_d, 32);
549     mbedtls_ecp_point_free(&P);
550     mbedtls_mpi_free(&d);
551 #endif  /* USE_MBEDTLS_ECC_P256 */
552 }
553 
554 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
555 static void btstack_crypto_ecc_p256_calculate_dhkey_software(btstack_crypto_ecc_p256_t * btstack_crypto_ec_p192){
556     memset(btstack_crypto_ec_p192->dhkey, 0, 32);
557 
558 #ifdef USE_MICRO_ECC_P256
559 #if uECC_SUPPORTS_secp256r1
560     // standard version
561     uECC_shared_secret(btstack_crypto_ec_p192->public_key, btstack_crypto_ecc_p256_d, btstack_crypto_ec_p192->dhkey, uECC_secp256r1());
562 #else
563     // static version
564     uECC_shared_secret(btstack_crypto_ec_p192->public_key, btstack_crypto_ecc_p256_d, btstack_crypto_ec_p192->dhkey);
565 #endif
566 #endif
567 
568 #ifdef USE_MBEDTLS_ECC_P256
569     // da * Pb
570     mbedtls_mpi d;
571     mbedtls_ecp_point Q;
572     mbedtls_ecp_point DH;
573     mbedtls_mpi_init(&d);
574     mbedtls_ecp_point_init(&Q);
575     mbedtls_ecp_point_init(&DH);
576     mbedtls_mpi_read_binary(&d, btstack_crypto_ecc_p256_d, 32);
577     mbedtls_mpi_read_binary(&Q.X, &btstack_crypto_ec_p192->public_key[0] , 32);
578     mbedtls_mpi_read_binary(&Q.Y, &btstack_crypto_ec_p192->public_key[32], 32);
579     mbedtls_mpi_lset(&Q.Z, 1);
580     mbedtls_ecp_mul(&mbedtls_ec_group, &DH, &d, &Q, NULL, NULL);
581     mbedtls_mpi_write_binary(&DH.X, btstack_crypto_ec_p192->dhkey, 32);
582     mbedtls_ecp_point_free(&DH);
583     mbedtls_mpi_free(&d);
584     mbedtls_ecp_point_free(&Q);
585 #endif
586 
587     log_info("dhkey");
588     log_info_hexdump(btstack_crypto_ec_p192->dhkey, 32);
589 }
590 #endif
591 
592 #endif
593 
594 static void btstack_crypto_ccm_next_block(btstack_crypto_ccm_t * btstack_crypto_ccm, btstack_crypto_ccm_state_t state_when_done){
595     uint16_t bytes_to_process = btstack_min(btstack_crypto_ccm->block_len, 16);
596     // next block
597     btstack_crypto_ccm->counter++;
598     btstack_crypto_ccm->input       += bytes_to_process;
599     btstack_crypto_ccm->output      += bytes_to_process;
600     btstack_crypto_ccm->block_len   -= bytes_to_process;
601     btstack_crypto_ccm->message_len -= bytes_to_process;
602 #ifdef DEBUG_CCM
603     printf("btstack_crypto_ccm_next_block (message len %u, block_len %u)\n", btstack_crypto_ccm->message_len, btstack_crypto_ccm->block_len);
604 #endif
605     if (btstack_crypto_ccm->message_len == 0u){
606         btstack_crypto_ccm->state = CCM_CALCULATE_S0;
607     } else {
608         btstack_crypto_ccm->state = state_when_done;
609         if (btstack_crypto_ccm->block_len == 0u){
610             btstack_crypto_done(&btstack_crypto_ccm->btstack_crypto);
611         }
612     }
613 }
614 
615 // If Controller is used for AES128, data is little endian
616 static void btstack_crypto_ccm_handle_s0(btstack_crypto_ccm_t * btstack_crypto_ccm, const uint8_t * data){
617     int i;
618     for (i=0;i<16;i++){
619 #ifdef USE_BTSTACK_AES128
620         btstack_crypto_ccm->x_i[i] = btstack_crypto_ccm->x_i[i] ^ data[i];
621 #else
622         btstack_crypto_ccm->x_i[i] = btstack_crypto_ccm->x_i[i] ^ data[15-i];
623 #endif
624     }
625     btstack_crypto_done(&btstack_crypto_ccm->btstack_crypto);
626 }
627 
628 // If Controller is used for AES128, data is little endian
629 static void btstack_crypto_ccm_handle_sn(btstack_crypto_ccm_t * btstack_crypto_ccm, const uint8_t * data){
630     int i;
631     uint16_t bytes_to_process = btstack_min(btstack_crypto_ccm->block_len, 16);
632     for (i=0;i<bytes_to_process;i++){
633 #ifdef USE_BTSTACK_AES128
634         btstack_crypto_ccm->output[i] = btstack_crypto_ccm->input[i] ^ data[i];
635 #else
636         btstack_crypto_ccm->output[i] = btstack_crypto_ccm->input[i] ^ data[15-i];
637 #endif
638     }
639     switch (btstack_crypto_ccm->btstack_crypto.operation){
640         case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK:
641             btstack_crypto_ccm->state = CCM_CALCULATE_XN;
642             break;
643         case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK:
644             btstack_crypto_ccm_next_block(btstack_crypto_ccm, CCM_CALCULATE_XN);
645             break;
646         default:
647             btstack_assert(false);
648             break;
649     }
650 }
651 
652 static void btstack_crypto_ccm_handle_aad_xn(btstack_crypto_ccm_t * btstack_crypto_ccm) {
653 #ifdef DEBUG_CCM
654     printf("%16s: ", "Xn+1 AAD");
655     printf_hexdump(btstack_crypto_ccm->x_i, 16);
656 #endif
657     // more aad?
658     if (btstack_crypto_ccm->aad_offset < (btstack_crypto_ccm->aad_len + 2u)){
659         btstack_crypto_ccm->state = CCM_CALCULATE_AAD_XN;
660     } else {
661         // done
662         btstack_crypto_done((btstack_crypto_t *) btstack_crypto_ccm);
663     }
664 }
665 
666 static void btstack_crypto_ccm_handle_x1(btstack_crypto_ccm_t * btstack_crypto_ccm) {
667 #ifdef DEBUG_CCM
668     printf("%16s: ", "Xi");
669     printf_hexdump(btstack_crypto_ccm->x_i, 16);
670 #endif
671     switch (btstack_crypto_ccm->btstack_crypto.operation){
672         case BTSTACK_CRYPTO_CCM_DIGEST_BLOCK:
673             btstack_crypto_ccm->aad_remainder_len = 0;
674             btstack_crypto_ccm->state = CCM_CALCULATE_AAD_XN;
675             break;
676         case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK:
677             btstack_crypto_ccm->state = CCM_CALCULATE_SN;
678             break;
679         case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK:
680             btstack_crypto_ccm->state = CCM_CALCULATE_XN;
681             break;
682         default:
683         btstack_assert(false);
684             break;
685     }
686 }
687 
688 static void btstack_crypto_ccm_handle_xn(btstack_crypto_ccm_t * btstack_crypto_ccm) {
689 #ifdef DEBUG_CCM
690     printf("%16s: ", "Xn+1");
691     printf_hexdump(btstack_crypto_ccm->x_i, 16);
692 #endif
693     switch (btstack_crypto_ccm->btstack_crypto.operation){
694         case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK:
695             btstack_crypto_ccm_next_block(btstack_crypto_ccm, CCM_CALCULATE_SN);
696             break;
697         case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK:
698             btstack_crypto_ccm->state = CCM_CALCULATE_SN;
699             break;
700         default:
701         btstack_assert(false);
702             break;
703     }
704 }
705 
706 static void btstack_crypto_ccm_calc_s0(btstack_crypto_ccm_t * btstack_crypto_ccm){
707 #ifdef DEBUG_CCM
708     printf("btstack_crypto_ccm_calc_s0\n");
709 #endif
710     btstack_crypto_ccm->state = CCM_W4_S0;
711     btstack_crypto_ccm_setup_a_i(btstack_crypto_ccm, 0);
712 #ifdef USE_BTSTACK_AES128
713     uint8_t data[16];
714     btstack_aes128_calc(btstack_crypto_ccm->key, btstack_crypto_ccm_s, data);
715     btstack_crypto_ccm_handle_s0(btstack_crypto_ccm, data);
716 #else
717     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_s);
718 #endif
719 }
720 
721 static void btstack_crypto_ccm_calc_sn(btstack_crypto_ccm_t * btstack_crypto_ccm){
722 #ifdef DEBUG_CCM
723     printf("btstack_crypto_ccm_calc_s%u\n", btstack_crypto_ccm->counter);
724 #endif
725     btstack_crypto_ccm->state = CCM_W4_SN;
726     btstack_crypto_ccm_setup_a_i(btstack_crypto_ccm, btstack_crypto_ccm->counter);
727 #ifdef USE_BTSTACK_AES128
728     uint8_t data[16];
729     btstack_aes128_calc(btstack_crypto_ccm->key, btstack_crypto_ccm_s, data);
730     btstack_crypto_ccm_handle_sn(btstack_crypto_ccm, data);
731 #else
732     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_s);
733 #endif
734 }
735 
736 static void btstack_crypto_ccm_calc_x1(btstack_crypto_ccm_t * btstack_crypto_ccm){
737     uint8_t btstack_crypto_ccm_buffer[16];
738     btstack_crypto_ccm->state = CCM_W4_X1;
739     btstack_crypto_ccm_setup_b_0(btstack_crypto_ccm, btstack_crypto_ccm_buffer);
740 #ifdef USE_BTSTACK_AES128
741     btstack_aes128_calc(btstack_crypto_ccm->key, btstack_crypto_ccm_buffer, btstack_crypto_ccm->x_i);
742     btstack_crypto_ccm_handle_x1(btstack_crypto_ccm);
743 #else
744     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_buffer);
745 #endif
746 }
747 
748 static void btstack_crypto_ccm_calc_xn(btstack_crypto_ccm_t * btstack_crypto_ccm, const uint8_t * plaintext){
749     uint8_t btstack_crypto_ccm_buffer[16];
750     btstack_crypto_ccm->state = CCM_W4_XN;
751 
752 #ifdef DEBUG_CCM
753     printf("%16s: ", "bn");
754     printf_hexdump(plaintext, 16);
755 #endif
756     uint8_t i;
757     uint8_t bytes_to_decrypt = btstack_crypto_ccm->block_len;
758     // use explicit min implementation as c-stat worried about out-of-bounds-reads
759     if (bytes_to_decrypt > 16u) {
760         bytes_to_decrypt = 16;
761     }
762     for (i = 0; i < bytes_to_decrypt ; i++){
763         btstack_crypto_ccm_buffer[i] =  btstack_crypto_ccm->x_i[i] ^ plaintext[i];
764     }
765     (void)memcpy(&btstack_crypto_ccm_buffer[i], &btstack_crypto_ccm->x_i[i],
766                  16u - bytes_to_decrypt);
767 #ifdef DEBUG_CCM
768     printf("%16s: ", "Xn XOR bn");
769     printf_hexdump(btstack_crypto_ccm_buffer, 16);
770 #endif
771 
772 #ifdef USE_BTSTACK_AES128
773     btstack_aes128_calc(btstack_crypto_ccm->key, btstack_crypto_ccm_buffer, btstack_crypto_ccm->x_i);
774     btstack_crypto_ccm_handle_xn(btstack_crypto_ccm);
775 #else
776     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_buffer);
777 #endif
778 }
779 
780 static void btstack_crypto_ccm_calc_aad_xn(btstack_crypto_ccm_t * btstack_crypto_ccm){
781     // store length
782     if (btstack_crypto_ccm->aad_offset == 0u){
783         uint8_t len_buffer[2];
784         big_endian_store_16(len_buffer, 0, btstack_crypto_ccm->aad_len);
785         btstack_crypto_ccm->x_i[0] ^= len_buffer[0];
786         btstack_crypto_ccm->x_i[1] ^= len_buffer[1];
787         btstack_crypto_ccm->aad_remainder_len += 2u;
788         btstack_crypto_ccm->aad_offset        += 2u;
789     }
790 
791     // fill from input
792     uint16_t bytes_free = 16u - btstack_crypto_ccm->aad_remainder_len;
793     uint16_t bytes_to_copy = btstack_min(bytes_free, btstack_crypto_ccm->block_len);
794     while (bytes_to_copy){
795         btstack_crypto_ccm->x_i[btstack_crypto_ccm->aad_remainder_len++] ^= *btstack_crypto_ccm->input++;
796         btstack_crypto_ccm->aad_offset++;
797         btstack_crypto_ccm->block_len--;
798         bytes_to_copy--;
799         bytes_free--;
800     }
801 
802     // if last block, fill with zeros
803     if (btstack_crypto_ccm->aad_offset == (btstack_crypto_ccm->aad_len + 2u)){
804         btstack_crypto_ccm->aad_remainder_len = 16;
805     }
806     // if not full, notify done
807     if (btstack_crypto_ccm->aad_remainder_len < 16u){
808         btstack_crypto_done(&btstack_crypto_ccm->btstack_crypto);
809         return;
810     }
811 
812     // encrypt block
813 #ifdef DEBUG_CCM
814     printf("%16s: ", "Xn XOR Bn (aad)");
815     printf_hexdump(btstack_crypto_ccm->x_i, 16);
816 #endif
817 
818     btstack_crypto_ccm->aad_remainder_len = 0;
819     btstack_crypto_ccm->state = CCM_W4_AAD_XN;
820 #ifdef USE_BTSTACK_AES128
821     btstack_aes128_calc(btstack_crypto_ccm->key, btstack_crypto_ccm->x_i, btstack_crypto_ccm->x_i);
822     btstack_crypto_ccm_handle_aad_xn(btstack_crypto_ccm);
823 #else
824     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm->x_i);
825 #endif
826 }
827 
828 static void btstack_crypto_run(void){
829 
830     btstack_crypto_aes128_t        * btstack_crypto_aes128;
831     btstack_crypto_ccm_t           * btstack_crypto_ccm;
832     btstack_crypto_aes128_cmac_t   * btstack_crypto_cmac;
833 #ifdef ENABLE_ECC_P256
834     btstack_crypto_ecc_p256_t      * btstack_crypto_ec_p192;
835 #endif
836 
837     // stack up and running?
838     if (hci_get_state() != HCI_STATE_WORKING) return;
839 
840     // try to do as much as possible
841     while (true){
842 
843         // anything to do?
844         if (btstack_linked_list_empty(&btstack_crypto_operations)) return;
845 
846         // already active?
847         if (btstack_crypto_wait_for_hci_result) return;
848 
849         // can send a command?
850         if (!hci_can_send_command_packet_now()) return;
851 
852         // ok, find next task
853     	btstack_crypto_t * btstack_crypto = (btstack_crypto_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
854     	switch (btstack_crypto->operation){
855     		case BTSTACK_CRYPTO_RANDOM:
856     			btstack_crypto_wait_for_hci_result = true;
857     		    hci_send_cmd(&hci_le_rand);
858     		    break;
859     		case BTSTACK_CRYPTO_AES128:
860                 btstack_crypto_aes128 = (btstack_crypto_aes128_t *) btstack_crypto;
861 #ifdef USE_BTSTACK_AES128
862                 btstack_aes128_calc(btstack_crypto_aes128->key, btstack_crypto_aes128->plaintext, btstack_crypto_aes128->ciphertext);
863                 btstack_crypto_done(btstack_crypto);
864 #else
865                 btstack_crypto_aes128_start(btstack_crypto_aes128->key, btstack_crypto_aes128->plaintext);
866 #endif
867     		    break;
868 
869     		case BTSTACK_CRYPTO_CMAC_MESSAGE:
870     		case BTSTACK_CRYPTO_CMAC_GENERATOR:
871                 btstack_crypto_cmac = (btstack_crypto_aes128_cmac_t *) btstack_crypto;
872 #ifdef USE_BTSTACK_AES128
873                 btstack_crypto_cmac_calc( btstack_crypto_cmac );
874                 btstack_crypto_done(btstack_crypto);
875 #else
876     			btstack_crypto_wait_for_hci_result = 1;
877     			if (btstack_crypto_cmac_state == CMAC_IDLE){
878     				btstack_crypto_cmac_start(btstack_crypto_cmac);
879     			} else {
880     				btstack_crypto_cmac_handle_aes_engine_ready(btstack_crypto_cmac);
881     			}
882 #endif
883     			break;
884 
885             case BTSTACK_CRYPTO_CCM_DIGEST_BLOCK:
886             case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK:
887             case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK:
888                 btstack_crypto_ccm = (btstack_crypto_ccm_t *) btstack_crypto;
889                 switch (btstack_crypto_ccm->state){
890                     case CCM_CALCULATE_AAD_XN:
891 #ifdef DEBUG_CCM
892                         printf("CCM_CALCULATE_AAD_XN\n");
893 #endif
894                         btstack_crypto_ccm_calc_aad_xn(btstack_crypto_ccm);
895                         break;
896                     case CCM_CALCULATE_X1:
897 #ifdef DEBUG_CCM
898                         printf("CCM_CALCULATE_X1\n");
899 #endif
900                         btstack_crypto_ccm_calc_x1(btstack_crypto_ccm);
901                         break;
902                     case CCM_CALCULATE_S0:
903 #ifdef DEBUG_CCM
904                         printf("CCM_CALCULATE_S0\n");
905 #endif
906                         btstack_crypto_ccm_calc_s0(btstack_crypto_ccm);
907                         break;
908                     case CCM_CALCULATE_SN:
909 #ifdef DEBUG_CCM
910                         printf("CCM_CALCULATE_SN\n");
911 #endif
912                         btstack_crypto_ccm_calc_sn(btstack_crypto_ccm);
913                         break;
914                     case CCM_CALCULATE_XN:
915 #ifdef DEBUG_CCM
916                         printf("CCM_CALCULATE_XN\n");
917 #endif
918                         btstack_crypto_ccm_calc_xn(btstack_crypto_ccm, (btstack_crypto->operation == BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK) ? btstack_crypto_ccm->input : btstack_crypto_ccm->output);
919                         break;
920                     default:
921                         break;
922                 }
923                 break;
924 
925 #ifdef ENABLE_ECC_P256
926             case BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY:
927                 btstack_crypto_ec_p192 = (btstack_crypto_ecc_p256_t *) btstack_crypto;
928                 switch (btstack_crypto_ecc_p256_key_generation_state){
929                     case ECC_P256_KEY_GENERATION_DONE:
930                         // done
931                         btstack_crypto_log_ec_publickey(btstack_crypto_ecc_p256_public_key);
932                         (void)memcpy(btstack_crypto_ec_p192->public_key,
933                                      btstack_crypto_ecc_p256_public_key, 64);
934                         btstack_linked_list_pop(&btstack_crypto_operations);
935                         (*btstack_crypto_ec_p192->btstack_crypto.context_callback.callback)(btstack_crypto_ec_p192->btstack_crypto.context_callback.context);
936                         break;
937                     case ECC_P256_KEY_GENERATION_IDLE:
938 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
939                         log_info("start ecc random");
940                         btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_GENERATING_RANDOM;
941                         btstack_crypto_ecc_p256_random_offset = 0;
942                         btstack_crypto_wait_for_hci_result = true;
943                         hci_send_cmd(&hci_le_rand);
944 #else
945                         btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_W4_KEY;
946                         btstack_crypto_wait_for_hci_result = 1;
947                         hci_send_cmd(&hci_le_read_local_p256_public_key);
948 #endif
949                         break;
950 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
951                     case ECC_P256_KEY_GENERATION_GENERATING_RANDOM:
952                         log_info("more ecc random");
953                         btstack_crypto_wait_for_hci_result = true;
954                         hci_send_cmd(&hci_le_rand);
955                         break;
956 #endif
957                     default:
958                         break;
959                 }
960                 break;
961             case BTSTACK_CRYPTO_ECC_P256_CALCULATE_DHKEY:
962                 btstack_crypto_ec_p192 = (btstack_crypto_ecc_p256_t *) btstack_crypto;
963 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
964                 btstack_crypto_ecc_p256_calculate_dhkey_software(btstack_crypto_ec_p192);
965                 // done
966                 btstack_linked_list_pop(&btstack_crypto_operations);
967                 (*btstack_crypto_ec_p192->btstack_crypto.context_callback.callback)(btstack_crypto_ec_p192->btstack_crypto.context_callback.context);
968 #else
969                 btstack_crypto_wait_for_hci_result = 1;
970                 hci_send_cmd(&hci_le_generate_dhkey, &btstack_crypto_ec_p192->public_key[0], &btstack_crypto_ec_p192->public_key[32]);
971 #endif
972                 break;
973 
974 #endif /* ENABLE_ECC_P256 */
975 
976             default:
977                 break;
978         }
979     }
980 }
981 
982 static void btstack_crypto_handle_random_data(const uint8_t * data, uint16_t len){
983     btstack_crypto_random_t * btstack_crypto_random;
984     btstack_crypto_t * btstack_crypto = (btstack_crypto_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
985     uint16_t bytes_to_copy;
986 	if (!btstack_crypto) return;
987     switch (btstack_crypto->operation){
988         case BTSTACK_CRYPTO_RANDOM:
989             btstack_crypto_random = (btstack_crypto_random_t*) btstack_crypto;
990             bytes_to_copy = btstack_min(btstack_crypto_random->size, len);
991             (void)memcpy(btstack_crypto_random->buffer, data, bytes_to_copy);
992             btstack_crypto_random->buffer += bytes_to_copy;
993             btstack_crypto_random->size   -= bytes_to_copy;
994             // data processed, more?
995             if (!btstack_crypto_random->size) {
996                 // done
997                 btstack_linked_list_pop(&btstack_crypto_operations);
998                 (*btstack_crypto_random->btstack_crypto.context_callback.callback)(btstack_crypto_random->btstack_crypto.context_callback.context);
999             }
1000             break;
1001 #ifdef ENABLE_ECC_P256
1002         case BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY:
1003             (void)memcpy(&btstack_crypto_ecc_p256_random[btstack_crypto_ecc_p256_random_len],
1004 			 data, 8);
1005             btstack_crypto_ecc_p256_random_len += 8u;
1006             if (btstack_crypto_ecc_p256_random_len >= 64u) {
1007                 btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_ACTIVE;
1008                 btstack_crypto_ecc_p256_generate_key_software();
1009                 btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_DONE;
1010             }
1011             break;
1012 #endif
1013         default:
1014             break;
1015     }
1016 	// more work?
1017 	btstack_crypto_run();
1018 }
1019 
1020 #ifndef USE_BTSTACK_AES128
1021 static void btstack_crypto_handle_encryption_result(const uint8_t * data){
1022 	btstack_crypto_aes128_t      * btstack_crypto_aes128;
1023 	btstack_crypto_aes128_cmac_t * btstack_crypto_cmac;
1024     btstack_crypto_ccm_t         * btstack_crypto_ccm;
1025 	uint8_t result[16];
1026 
1027     btstack_crypto_t * btstack_crypto = (btstack_crypto_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
1028 	if (!btstack_crypto) return;
1029 	switch (btstack_crypto->operation){
1030 		case BTSTACK_CRYPTO_AES128:
1031 			btstack_crypto_aes128 = (btstack_crypto_aes128_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
1032 		    reverse_128(data, btstack_crypto_aes128->ciphertext);
1033             btstack_crypto_done(btstack_crypto);
1034 			break;
1035 		case BTSTACK_CRYPTO_CMAC_GENERATOR:
1036 		case BTSTACK_CRYPTO_CMAC_MESSAGE:
1037 			btstack_crypto_cmac = (btstack_crypto_aes128_cmac_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
1038 		    reverse_128(data, result);
1039 		    btstack_crypto_cmac_handle_encryption_result(btstack_crypto_cmac, result);
1040 			break;
1041         case BTSTACK_CRYPTO_CCM_DIGEST_BLOCK:
1042         case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK:
1043         case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK:
1044             btstack_crypto_ccm = (btstack_crypto_ccm_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
1045             switch (btstack_crypto_ccm->state){
1046                 case CCM_W4_X1:
1047                     reverse_128(data, btstack_crypto_ccm->x_i);
1048                     btstack_crypto_ccm_handle_x1(btstack_crypto_ccm);
1049                     break;
1050                 case CCM_W4_XN:
1051                     reverse_128(data, btstack_crypto_ccm->x_i);
1052                     btstack_crypto_ccm_handle_xn(btstack_crypto_ccm);
1053                     break;
1054                 case CCM_W4_AAD_XN:
1055                     reverse_128(data, btstack_crypto_ccm->x_i);
1056                     btstack_crypto_ccm_handle_aad_xn(btstack_crypto_ccm);
1057                     break;
1058                 case CCM_W4_S0:
1059                     btstack_crypto_ccm_handle_s0(btstack_crypto_ccm, data);
1060                     break;
1061                 case CCM_W4_SN:
1062                     btstack_crypto_ccm_handle_sn(btstack_crypto_ccm, data);
1063                     break;
1064                 default:
1065                     break;
1066             }
1067             break;
1068 		default:
1069 			break;
1070 	}
1071 }
1072 #endif
1073 
1074 static void btstack_crypto_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
1075     UNUSED(cid);         // ok: there is no channel
1076     UNUSED(size);        // ok: fixed format events read from HCI buffer
1077 
1078 #ifdef ENABLE_ECC_P256
1079 #ifndef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
1080     btstack_crypto_ecc_p256_t * btstack_crypto_ec_p192;
1081 #endif
1082 #endif
1083 
1084     if (packet_type != HCI_EVENT_PACKET)  return;
1085 
1086     switch (hci_event_packet_get_type(packet)){
1087         case BTSTACK_EVENT_STATE:
1088             if (btstack_event_state_get_state(packet) != HCI_STATE_HALTING) break;
1089             if (!btstack_crypto_wait_for_hci_result) break;
1090             // request stack to defer shutdown a bit
1091             hci_halting_defer();
1092             break;
1093 
1094         case HCI_EVENT_COMMAND_COMPLETE:
1095 #ifndef USE_BTSTACK_AES128
1096     	    if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_encrypt)){
1097                 if (!btstack_crypto_wait_for_hci_result) return;
1098                 btstack_crypto_wait_for_hci_result = 0;
1099     	        btstack_crypto_handle_encryption_result(&packet[6]);
1100     	    }
1101 #endif
1102     	    if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_rand)){
1103                 if (!btstack_crypto_wait_for_hci_result) return;
1104                 btstack_crypto_wait_for_hci_result = false;
1105                 btstack_crypto_handle_random_data(&packet[6], 8);
1106     	    }
1107             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_commands)){
1108                 int ecdh_operations_supported = (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+34u] & 0x06u) == 0x06u;
1109                 UNUSED(ecdh_operations_supported);
1110                 log_info("controller supports ECDH operation: %u", ecdh_operations_supported);
1111 #ifdef ENABLE_ECC_P256
1112 #ifndef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
1113                 // Assert controller supports ECDH operation if we don't implement them ourselves
1114                 // Please add ENABLE_MICRO_ECC_FOR_LE_SECURE_CONNECTIONS to btstack_config.h and add 3rd-party/micro-ecc to your port
1115                 btstack_assert(ecdh_operations_supported != 0);
1116 #endif
1117 #endif
1118             }
1119             break;
1120 
1121 #ifdef ENABLE_ECC_P256
1122 #ifndef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
1123         case HCI_EVENT_LE_META:
1124             btstack_crypto_ec_p192 = (btstack_crypto_ecc_p256_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
1125             if (!btstack_crypto_ec_p192) break;
1126             switch (hci_event_le_meta_get_subevent_code(packet)){
1127                 case HCI_SUBEVENT_LE_READ_LOCAL_P256_PUBLIC_KEY_COMPLETE:
1128                     if (btstack_crypto_ec_p192->btstack_crypto.operation != BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY) break;
1129                     if (!btstack_crypto_wait_for_hci_result) return;
1130                     btstack_crypto_wait_for_hci_result = 0;
1131                     if (hci_subevent_le_read_local_p256_public_key_complete_get_status(packet)){
1132                         log_error("Read Local P256 Public Key failed");
1133                     }
1134                     hci_subevent_le_read_local_p256_public_key_complete_get_dhkey_x(packet, &btstack_crypto_ecc_p256_public_key[0]);
1135                     hci_subevent_le_read_local_p256_public_key_complete_get_dhkey_y(packet, &btstack_crypto_ecc_p256_public_key[32]);
1136                     btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_DONE;
1137                     break;
1138                 case HCI_SUBEVENT_LE_GENERATE_DHKEY_COMPLETE:
1139                     if (btstack_crypto_ec_p192->btstack_crypto.operation != BTSTACK_CRYPTO_ECC_P256_CALCULATE_DHKEY) break;
1140                     if (!btstack_crypto_wait_for_hci_result) return;
1141                     btstack_crypto_wait_for_hci_result = 0;
1142                     if (hci_subevent_le_generate_dhkey_complete_get_status(packet)){
1143                         log_error("Generate DHKEY failed -> abort");
1144                     }
1145                     hci_subevent_le_generate_dhkey_complete_get_dhkey(packet, btstack_crypto_ec_p192->dhkey);
1146                     // done
1147                     btstack_linked_list_pop(&btstack_crypto_operations);
1148                     (*btstack_crypto_ec_p192->btstack_crypto.context_callback.callback)(btstack_crypto_ec_p192->btstack_crypto.context_callback.context);
1149                     break;
1150                 default:
1151                     break;
1152             }
1153             break;
1154 #endif
1155 #endif
1156         default:
1157             break;
1158     }
1159 
1160     // try processing
1161 	btstack_crypto_run();
1162 }
1163 
1164 void btstack_crypto_init(void){
1165 	if (btstack_crypto_initialized) return;
1166 	btstack_crypto_initialized = true;
1167 
1168 	// register with HCI
1169     hci_event_callback_registration.callback = &btstack_crypto_event_handler;
1170     hci_add_event_handler(&hci_event_callback_registration);
1171 
1172 #ifdef USE_MBEDTLS_ECC_P256
1173 	mbedtls_ecp_group_init(&mbedtls_ec_group);
1174 	mbedtls_ecp_group_load(&mbedtls_ec_group, MBEDTLS_ECP_DP_SECP256R1);
1175 #endif
1176 }
1177 
1178 void btstack_crypto_random_generate(btstack_crypto_random_t * request, uint8_t * buffer, uint16_t size, void (* callback)(void * arg), void * callback_arg){
1179 	request->btstack_crypto.context_callback.callback  = callback;
1180 	request->btstack_crypto.context_callback.context   = callback_arg;
1181 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_RANDOM;
1182 	request->buffer = buffer;
1183 	request->size   = size;
1184 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1185 	btstack_crypto_run();
1186 }
1187 
1188 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){
1189 	request->btstack_crypto.context_callback.callback  = callback;
1190 	request->btstack_crypto.context_callback.context   = callback_arg;
1191 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_AES128;
1192 	request->key 									   = key;
1193 	request->plaintext      					       = plaintext;
1194 	request->ciphertext 							   = ciphertext;
1195 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1196 	btstack_crypto_run();
1197 }
1198 
1199 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){
1200 	request->btstack_crypto.context_callback.callback  = callback;
1201 	request->btstack_crypto.context_callback.context   = callback_arg;
1202 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_CMAC_GENERATOR;
1203 	request->key 									   = key;
1204 	request->size 									   = size;
1205 	request->data.get_byte_callback					   = get_byte_callback;
1206 	request->hash 									   = hash;
1207 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1208 	btstack_crypto_run();
1209 }
1210 
1211 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){
1212 	request->btstack_crypto.context_callback.callback  = callback;
1213 	request->btstack_crypto.context_callback.context   = callback_arg;
1214 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_CMAC_MESSAGE;
1215 	request->key 									   = key;
1216 	request->size 									   = size;
1217 	request->data.message      						   = message;
1218 	request->hash 									   = hash;
1219 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1220 	btstack_crypto_run();
1221 }
1222 
1223 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){
1224     request->btstack_crypto.context_callback.callback  = callback;
1225     request->btstack_crypto.context_callback.context   = callback_arg;
1226     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CMAC_MESSAGE;
1227     request->key                                       = zero;
1228     request->size                                      = len;
1229     request->data.message                              = message;
1230     request->hash                                      = hash;
1231     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1232     btstack_crypto_run();
1233 }
1234 
1235 #ifdef ENABLE_ECC_P256
1236 void btstack_crypto_ecc_p256_generate_key(btstack_crypto_ecc_p256_t * request, uint8_t * public_key, void (* callback)(void * arg), void * callback_arg){
1237     // reset key generation
1238     if (btstack_crypto_ecc_p256_key_generation_state == ECC_P256_KEY_GENERATION_DONE){
1239         btstack_crypto_ecc_p256_random_len = 0;
1240         btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_IDLE;
1241     }
1242     request->btstack_crypto.context_callback.callback  = callback;
1243     request->btstack_crypto.context_callback.context   = callback_arg;
1244     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY;
1245     request->public_key                                = public_key;
1246     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1247     btstack_crypto_run();
1248 }
1249 
1250 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){
1251     request->btstack_crypto.context_callback.callback  = callback;
1252     request->btstack_crypto.context_callback.context   = callback_arg;
1253     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_ECC_P256_CALCULATE_DHKEY;
1254     request->public_key                                = (uint8_t *) public_key;
1255     request->dhkey                                     = dhkey;
1256     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1257     btstack_crypto_run();
1258 }
1259 
1260 int btstack_crypto_ecc_p256_validate_public_key(const uint8_t * public_key){
1261 
1262     // validate public key using micro-ecc
1263     int err = 0;
1264 
1265 #ifdef USE_MICRO_ECC_P256
1266 #if uECC_SUPPORTS_secp256r1
1267     // standard version
1268     err = uECC_valid_public_key(public_key, uECC_secp256r1()) == 0;
1269 #else
1270     // static version
1271     err = uECC_valid_public_key(public_key) == 0;
1272 #endif
1273 #endif
1274 
1275 #ifdef USE_MBEDTLS_ECC_P256
1276     mbedtls_ecp_point Q;
1277     mbedtls_ecp_point_init( &Q );
1278     mbedtls_mpi_read_binary(&Q.X, &public_key[0], 32);
1279     mbedtls_mpi_read_binary(&Q.Y, &public_key[32], 32);
1280     mbedtls_mpi_lset(&Q.Z, 1);
1281     err = mbedtls_ecp_check_pubkey(&mbedtls_ec_group, &Q);
1282     mbedtls_ecp_point_free( & Q);
1283 #endif
1284 
1285     if (err != 0){
1286         log_error("public key invalid %x", err);
1287     }
1288     return  err;
1289 }
1290 #endif
1291 
1292 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){
1293     request->key         = key;
1294     request->nonce       = nonce;
1295     request->message_len = message_len;
1296     request->aad_len     = additional_authenticated_data_len;
1297     request->aad_offset  = 0;
1298     request->auth_len    = auth_len;
1299     request->counter     = 1;
1300     request->state       = CCM_CALCULATE_X1;
1301 }
1302 
1303 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){
1304     // not implemented yet
1305     request->btstack_crypto.context_callback.callback  = callback;
1306     request->btstack_crypto.context_callback.context   = callback_arg;
1307     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CCM_DIGEST_BLOCK;
1308     request->block_len                                 = additional_authenticated_data_len;
1309     request->input                                     = additional_authenticated_data;
1310     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1311     btstack_crypto_run();
1312 }
1313 
1314 void btstack_crypto_ccm_get_authentication_value(btstack_crypto_ccm_t * request, uint8_t * authentication_value){
1315     (void)memcpy(authentication_value, request->x_i, request->auth_len);
1316 }
1317 
1318 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){
1319 #ifdef DEBUG_CCM
1320     printf("\nbtstack_crypto_ccm_encrypt_block, len %u\n", block_len);
1321 #endif
1322     request->btstack_crypto.context_callback.callback  = callback;
1323     request->btstack_crypto.context_callback.context   = callback_arg;
1324     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK;
1325     request->block_len                                 = block_len;
1326     request->input                                     = plaintext;
1327     request->output                                    = ciphertext;
1328     if (request->state != CCM_CALCULATE_X1){
1329         request->state  = CCM_CALCULATE_XN;
1330     }
1331     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1332     btstack_crypto_run();
1333 }
1334 
1335 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){
1336     request->btstack_crypto.context_callback.callback  = callback;
1337     request->btstack_crypto.context_callback.context   = callback_arg;
1338     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK;
1339     request->block_len                                 = block_len;
1340     request->input                                     = ciphertext;
1341     request->output                                    = plaintext;
1342     if (request->state != CCM_CALCULATE_X1){
1343         request->state  = CCM_CALCULATE_SN;
1344     }
1345     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1346     btstack_crypto_run();
1347 }
1348 
1349 // De-Init
1350 void btstack_crypto_deinit(void) {
1351     btstack_crypto_initialized = false;
1352     btstack_crypto_wait_for_hci_result = false;
1353     btstack_crypto_operations = NULL;
1354 }
1355 
1356 // PTS only
1357 void btstack_crypto_ecc_p256_set_key(const uint8_t * public_key, const uint8_t * private_key){
1358 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
1359     (void)memcpy(btstack_crypto_ecc_p256_d, private_key, 32);
1360     (void)memcpy(btstack_crypto_ecc_p256_public_key, public_key, 64);
1361     btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_DONE;
1362 #else
1363     UNUSED(public_key);
1364     UNUSED(private_key);
1365 #endif
1366 }
1367 
1368 // Unit testing
1369 int btstack_crypto_idle(void){
1370     return btstack_linked_list_empty(&btstack_crypto_operations);
1371 }
1372 void btstack_crypto_reset(void){
1373     btstack_crypto_deinit();
1374     btstack_crypto_init();
1375 }
1376