xref: /btstack/src/btstack_crypto.c (revision b29e92f97ffd81bc8a1057634c8d1552fc963a6a)
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 BLUEKITCHEN GMBH 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 BLUEKITCHEN
21  * GMBH 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     uint16_t remaining_size = size;
499     uint8_t * buffer_ptr = buffer;
500     while (remaining_size) {
501         *buffer_ptr++ = btstack_crypto_ecc_p256_random[btstack_crypto_ecc_p256_random_offset++];
502         remaining_size--;
503     }
504     return 1;
505 }
506 #endif
507 #ifdef USE_MBEDTLS_ECC_P256
508 // @return error - just wrap sm_generate_f_rng
509 static int sm_generate_f_rng_mbedtls(void * context, unsigned char * buffer, size_t size){
510     UNUSED(context);
511     return sm_generate_f_rng(buffer, size) == 0;
512 }
513 #endif /* USE_MBEDTLS_ECC_P256 */
514 
515 static void btstack_crypto_ecc_p256_generate_key_software(void){
516 
517     btstack_crypto_ecc_p256_random_offset = 0;
518 
519     // generate EC key
520 #ifdef USE_MICRO_ECC_P256
521 
522 #ifndef WICED_VERSION
523     log_info("set uECC RNG for initial key generation with 64 random bytes");
524     // micro-ecc from WICED SDK uses its wiced_crypto_get_random by default - no need to set it
525     uECC_set_rng(&sm_generate_f_rng);
526 #endif /* WICED_VERSION */
527 
528 #if uECC_SUPPORTS_secp256r1
529     // standard version
530     uECC_make_key(btstack_crypto_ecc_p256_public_key, btstack_crypto_ecc_p256_d, uECC_secp256r1());
531 
532     // disable RNG again, as returning no randmon data lets shared key generation fail
533     log_info("disable uECC RNG in standard version after key generation");
534     uECC_set_rng(NULL);
535 #else
536     // static version
537     uECC_make_key(btstack_crypto_ecc_p256_public_key, btstack_crypto_ecc_p256_d);
538 #endif
539 #endif /* USE_MICRO_ECC_P256 */
540 
541 #ifdef USE_MBEDTLS_ECC_P256
542     mbedtls_mpi d;
543     mbedtls_ecp_point P;
544     mbedtls_mpi_init(&d);
545     mbedtls_ecp_point_init(&P);
546     int res = mbedtls_ecp_gen_keypair(&mbedtls_ec_group, &d, &P, &sm_generate_f_rng_mbedtls, NULL);
547     log_info("gen keypair %x", res);
548     mbedtls_mpi_write_binary(&P.X, &btstack_crypto_ecc_p256_public_key[0],  32);
549     mbedtls_mpi_write_binary(&P.Y, &btstack_crypto_ecc_p256_public_key[32], 32);
550     mbedtls_mpi_write_binary(&d, btstack_crypto_ecc_p256_d, 32);
551     mbedtls_ecp_point_free(&P);
552     mbedtls_mpi_free(&d);
553 #endif  /* USE_MBEDTLS_ECC_P256 */
554 }
555 
556 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
557 static void btstack_crypto_ecc_p256_calculate_dhkey_software(btstack_crypto_ecc_p256_t * btstack_crypto_ec_p192){
558     memset(btstack_crypto_ec_p192->dhkey, 0, 32);
559 
560 #ifdef USE_MICRO_ECC_P256
561 #if uECC_SUPPORTS_secp256r1
562     // standard version
563     uECC_shared_secret(btstack_crypto_ec_p192->public_key, btstack_crypto_ecc_p256_d, btstack_crypto_ec_p192->dhkey, uECC_secp256r1());
564 #else
565     // static version
566     uECC_shared_secret(btstack_crypto_ec_p192->public_key, btstack_crypto_ecc_p256_d, btstack_crypto_ec_p192->dhkey);
567 #endif
568 #endif
569 
570 #ifdef USE_MBEDTLS_ECC_P256
571     // da * Pb
572     mbedtls_mpi d;
573     mbedtls_ecp_point Q;
574     mbedtls_ecp_point DH;
575     mbedtls_mpi_init(&d);
576     mbedtls_ecp_point_init(&Q);
577     mbedtls_ecp_point_init(&DH);
578     mbedtls_mpi_read_binary(&d, btstack_crypto_ecc_p256_d, 32);
579     mbedtls_mpi_read_binary(&Q.X, &btstack_crypto_ec_p192->public_key[0] , 32);
580     mbedtls_mpi_read_binary(&Q.Y, &btstack_crypto_ec_p192->public_key[32], 32);
581     mbedtls_mpi_lset(&Q.Z, 1);
582     mbedtls_ecp_mul(&mbedtls_ec_group, &DH, &d, &Q, NULL, NULL);
583     mbedtls_mpi_write_binary(&DH.X, btstack_crypto_ec_p192->dhkey, 32);
584     mbedtls_ecp_point_free(&DH);
585     mbedtls_mpi_free(&d);
586     mbedtls_ecp_point_free(&Q);
587 #endif
588 
589     log_info("dhkey");
590     log_info_hexdump(btstack_crypto_ec_p192->dhkey, 32);
591 }
592 #endif
593 
594 #endif
595 
596 static void btstack_crypto_ccm_next_block(btstack_crypto_ccm_t * btstack_crypto_ccm, btstack_crypto_ccm_state_t state_when_done){
597     uint16_t bytes_to_process = btstack_min(btstack_crypto_ccm->block_len, 16);
598     // next block
599     btstack_crypto_ccm->counter++;
600     btstack_crypto_ccm->input       += bytes_to_process;
601     btstack_crypto_ccm->output      += bytes_to_process;
602     btstack_crypto_ccm->block_len   -= bytes_to_process;
603     btstack_crypto_ccm->message_len -= bytes_to_process;
604 #ifdef DEBUG_CCM
605     printf("btstack_crypto_ccm_next_block (message len %u, block_len %u)\n", btstack_crypto_ccm->message_len, btstack_crypto_ccm->block_len);
606 #endif
607     if (btstack_crypto_ccm->message_len == 0u){
608         btstack_crypto_ccm->state = CCM_CALCULATE_S0;
609     } else {
610         btstack_crypto_ccm->state = state_when_done;
611         if (btstack_crypto_ccm->block_len == 0u){
612             btstack_crypto_done(&btstack_crypto_ccm->btstack_crypto);
613         }
614     }
615 }
616 
617 // If Controller is used for AES128, data is little endian
618 static void btstack_crypto_ccm_handle_s0(btstack_crypto_ccm_t * btstack_crypto_ccm, const uint8_t * data){
619     int i;
620     for (i=0;i<16;i++){
621 #ifdef USE_BTSTACK_AES128
622         btstack_crypto_ccm->x_i[i] = btstack_crypto_ccm->x_i[i] ^ data[i];
623 #else
624         btstack_crypto_ccm->x_i[i] = btstack_crypto_ccm->x_i[i] ^ data[15-i];
625 #endif
626     }
627     btstack_crypto_done(&btstack_crypto_ccm->btstack_crypto);
628 }
629 
630 // If Controller is used for AES128, data is little endian
631 static void btstack_crypto_ccm_handle_sn(btstack_crypto_ccm_t * btstack_crypto_ccm, const uint8_t * data){
632     int i;
633     uint16_t bytes_to_process = btstack_min(btstack_crypto_ccm->block_len, 16);
634     for (i=0;i<bytes_to_process;i++){
635 #ifdef USE_BTSTACK_AES128
636         btstack_crypto_ccm->output[i] = btstack_crypto_ccm->input[i] ^ data[i];
637 #else
638         btstack_crypto_ccm->output[i] = btstack_crypto_ccm->input[i] ^ data[15-i];
639 #endif
640     }
641     switch (btstack_crypto_ccm->btstack_crypto.operation){
642         case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK:
643             btstack_crypto_ccm->state = CCM_CALCULATE_XN;
644             break;
645         case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK:
646             btstack_crypto_ccm_next_block(btstack_crypto_ccm, CCM_CALCULATE_XN);
647             break;
648         default:
649             btstack_assert(false);
650             break;
651     }
652 }
653 
654 static void btstack_crypto_ccm_handle_aad_xn(btstack_crypto_ccm_t * btstack_crypto_ccm) {
655 #ifdef DEBUG_CCM
656     printf("%16s: ", "Xn+1 AAD");
657     printf_hexdump(btstack_crypto_ccm->x_i, 16);
658 #endif
659     // more aad?
660     if (btstack_crypto_ccm->aad_offset < (btstack_crypto_ccm->aad_len + 2u)){
661         btstack_crypto_ccm->state = CCM_CALCULATE_AAD_XN;
662     } else {
663         // done
664         btstack_crypto_done((btstack_crypto_t *) btstack_crypto_ccm);
665     }
666 }
667 
668 static void btstack_crypto_ccm_handle_x1(btstack_crypto_ccm_t * btstack_crypto_ccm) {
669 #ifdef DEBUG_CCM
670     printf("%16s: ", "Xi");
671     printf_hexdump(btstack_crypto_ccm->x_i, 16);
672 #endif
673     switch (btstack_crypto_ccm->btstack_crypto.operation){
674         case BTSTACK_CRYPTO_CCM_DIGEST_BLOCK:
675             btstack_crypto_ccm->aad_remainder_len = 0;
676             btstack_crypto_ccm->state = CCM_CALCULATE_AAD_XN;
677             break;
678         case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK:
679             btstack_crypto_ccm->state = CCM_CALCULATE_SN;
680             break;
681         case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK:
682             btstack_crypto_ccm->state = CCM_CALCULATE_XN;
683             break;
684         default:
685         btstack_assert(false);
686             break;
687     }
688 }
689 
690 static void btstack_crypto_ccm_handle_xn(btstack_crypto_ccm_t * btstack_crypto_ccm) {
691 #ifdef DEBUG_CCM
692     printf("%16s: ", "Xn+1");
693     printf_hexdump(btstack_crypto_ccm->x_i, 16);
694 #endif
695     switch (btstack_crypto_ccm->btstack_crypto.operation){
696         case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK:
697             btstack_crypto_ccm_next_block(btstack_crypto_ccm, CCM_CALCULATE_SN);
698             break;
699         case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK:
700             btstack_crypto_ccm->state = CCM_CALCULATE_SN;
701             break;
702         default:
703         btstack_assert(false);
704             break;
705     }
706 }
707 
708 static void btstack_crypto_ccm_calc_s0(btstack_crypto_ccm_t * btstack_crypto_ccm){
709 #ifdef DEBUG_CCM
710     printf("btstack_crypto_ccm_calc_s0\n");
711 #endif
712     btstack_crypto_ccm->state = CCM_W4_S0;
713     btstack_crypto_ccm_setup_a_i(btstack_crypto_ccm, 0);
714 #ifdef USE_BTSTACK_AES128
715     uint8_t data[16];
716     btstack_aes128_calc(btstack_crypto_ccm->key, btstack_crypto_ccm_s, data);
717     btstack_crypto_ccm_handle_s0(btstack_crypto_ccm, data);
718 #else
719     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_s);
720 #endif
721 }
722 
723 static void btstack_crypto_ccm_calc_sn(btstack_crypto_ccm_t * btstack_crypto_ccm){
724 #ifdef DEBUG_CCM
725     printf("btstack_crypto_ccm_calc_s%u\n", btstack_crypto_ccm->counter);
726 #endif
727     btstack_crypto_ccm->state = CCM_W4_SN;
728     btstack_crypto_ccm_setup_a_i(btstack_crypto_ccm, btstack_crypto_ccm->counter);
729 #ifdef USE_BTSTACK_AES128
730     uint8_t data[16];
731     btstack_aes128_calc(btstack_crypto_ccm->key, btstack_crypto_ccm_s, data);
732     btstack_crypto_ccm_handle_sn(btstack_crypto_ccm, data);
733 #else
734     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_s);
735 #endif
736 }
737 
738 static void btstack_crypto_ccm_calc_x1(btstack_crypto_ccm_t * btstack_crypto_ccm){
739     uint8_t btstack_crypto_ccm_buffer[16];
740     btstack_crypto_ccm->state = CCM_W4_X1;
741     btstack_crypto_ccm_setup_b_0(btstack_crypto_ccm, btstack_crypto_ccm_buffer);
742 #ifdef USE_BTSTACK_AES128
743     btstack_aes128_calc(btstack_crypto_ccm->key, btstack_crypto_ccm_buffer, btstack_crypto_ccm->x_i);
744     btstack_crypto_ccm_handle_x1(btstack_crypto_ccm);
745 #else
746     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_buffer);
747 #endif
748 }
749 
750 static void btstack_crypto_ccm_calc_xn(btstack_crypto_ccm_t * btstack_crypto_ccm, const uint8_t * plaintext){
751     uint8_t btstack_crypto_ccm_buffer[16];
752     btstack_crypto_ccm->state = CCM_W4_XN;
753 
754 #ifdef DEBUG_CCM
755     printf("%16s: ", "bn");
756     printf_hexdump(plaintext, 16);
757 #endif
758     uint8_t i;
759     uint16_t bytes_to_decrypt = btstack_crypto_ccm->block_len;
760     // use explicit min implementation as c-stat worried about out-of-bounds-reads
761     if (bytes_to_decrypt > 16u) {
762         bytes_to_decrypt = 16;
763     }
764     for (i = 0; i < bytes_to_decrypt ; i++){
765         btstack_crypto_ccm_buffer[i] =  btstack_crypto_ccm->x_i[i] ^ plaintext[i];
766     }
767     (void)memcpy(&btstack_crypto_ccm_buffer[i], &btstack_crypto_ccm->x_i[i],
768                  16u - bytes_to_decrypt);
769 #ifdef DEBUG_CCM
770     printf("%16s: ", "Xn XOR bn");
771     printf_hexdump(btstack_crypto_ccm_buffer, 16);
772 #endif
773 
774 #ifdef USE_BTSTACK_AES128
775     btstack_aes128_calc(btstack_crypto_ccm->key, btstack_crypto_ccm_buffer, btstack_crypto_ccm->x_i);
776     btstack_crypto_ccm_handle_xn(btstack_crypto_ccm);
777 #else
778     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_buffer);
779 #endif
780 }
781 
782 static void btstack_crypto_ccm_calc_aad_xn(btstack_crypto_ccm_t * btstack_crypto_ccm){
783     // store length
784     if (btstack_crypto_ccm->aad_offset == 0u){
785         uint8_t len_buffer[2];
786         big_endian_store_16(len_buffer, 0, btstack_crypto_ccm->aad_len);
787         btstack_crypto_ccm->x_i[0] ^= len_buffer[0];
788         btstack_crypto_ccm->x_i[1] ^= len_buffer[1];
789         btstack_crypto_ccm->aad_remainder_len += 2u;
790         btstack_crypto_ccm->aad_offset        += 2u;
791     }
792 
793     // fill from input
794     uint16_t bytes_free = 16u - btstack_crypto_ccm->aad_remainder_len;
795     uint16_t bytes_to_copy = btstack_min(bytes_free, btstack_crypto_ccm->block_len);
796     while (bytes_to_copy){
797         btstack_crypto_ccm->x_i[btstack_crypto_ccm->aad_remainder_len++] ^= *btstack_crypto_ccm->input++;
798         btstack_crypto_ccm->aad_offset++;
799         btstack_crypto_ccm->block_len--;
800         bytes_to_copy--;
801         bytes_free--;
802     }
803 
804     // if last block, fill with zeros
805     if (btstack_crypto_ccm->aad_offset == (btstack_crypto_ccm->aad_len + 2u)){
806         btstack_crypto_ccm->aad_remainder_len = 16;
807     }
808     // if not full, notify done
809     if (btstack_crypto_ccm->aad_remainder_len < 16u){
810         btstack_crypto_done(&btstack_crypto_ccm->btstack_crypto);
811         return;
812     }
813 
814     // encrypt block
815 #ifdef DEBUG_CCM
816     printf("%16s: ", "Xn XOR Bn (aad)");
817     printf_hexdump(btstack_crypto_ccm->x_i, 16);
818 #endif
819 
820     btstack_crypto_ccm->aad_remainder_len = 0;
821     btstack_crypto_ccm->state = CCM_W4_AAD_XN;
822 #ifdef USE_BTSTACK_AES128
823     btstack_aes128_calc(btstack_crypto_ccm->key, btstack_crypto_ccm->x_i, btstack_crypto_ccm->x_i);
824     btstack_crypto_ccm_handle_aad_xn(btstack_crypto_ccm);
825 #else
826     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm->x_i);
827 #endif
828 }
829 
830 static void btstack_crypto_run(void){
831 
832     btstack_crypto_aes128_t        * btstack_crypto_aes128;
833     btstack_crypto_ccm_t           * btstack_crypto_ccm;
834     btstack_crypto_aes128_cmac_t   * btstack_crypto_cmac;
835 #ifdef ENABLE_ECC_P256
836     btstack_crypto_ecc_p256_t      * btstack_crypto_ec_p192;
837 #endif
838 
839     // stack up and running?
840     if (hci_get_state() != HCI_STATE_WORKING) return;
841 
842     // try to do as much as possible
843     while (true){
844 
845         // anything to do?
846         if (btstack_linked_list_empty(&btstack_crypto_operations)) return;
847 
848         // already active?
849         if (btstack_crypto_wait_for_hci_result) return;
850 
851         // can send a command?
852         if (!hci_can_send_command_packet_now()) return;
853 
854         // ok, find next task
855     	btstack_crypto_t * btstack_crypto = (btstack_crypto_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
856     	switch (btstack_crypto->operation){
857     		case BTSTACK_CRYPTO_RANDOM:
858     			btstack_crypto_wait_for_hci_result = true;
859     		    hci_send_cmd(&hci_le_rand);
860     		    break;
861     		case BTSTACK_CRYPTO_AES128:
862                 btstack_crypto_aes128 = (btstack_crypto_aes128_t *) btstack_crypto;
863 #ifdef USE_BTSTACK_AES128
864                 btstack_aes128_calc(btstack_crypto_aes128->key, btstack_crypto_aes128->plaintext, btstack_crypto_aes128->ciphertext);
865                 btstack_crypto_done(btstack_crypto);
866 #else
867                 btstack_crypto_aes128_start(btstack_crypto_aes128->key, btstack_crypto_aes128->plaintext);
868 #endif
869     		    break;
870 
871     		case BTSTACK_CRYPTO_CMAC_MESSAGE:
872     		case BTSTACK_CRYPTO_CMAC_GENERATOR:
873                 btstack_crypto_cmac = (btstack_crypto_aes128_cmac_t *) btstack_crypto;
874 #ifdef USE_BTSTACK_AES128
875                 btstack_crypto_cmac_calc( btstack_crypto_cmac );
876                 btstack_crypto_done(btstack_crypto);
877 #else
878     			btstack_crypto_wait_for_hci_result = 1;
879     			if (btstack_crypto_cmac_state == CMAC_IDLE){
880     				btstack_crypto_cmac_start(btstack_crypto_cmac);
881     			} else {
882     				btstack_crypto_cmac_handle_aes_engine_ready(btstack_crypto_cmac);
883     			}
884 #endif
885     			break;
886 
887             case BTSTACK_CRYPTO_CCM_DIGEST_BLOCK:
888             case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK:
889             case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK:
890                 btstack_crypto_ccm = (btstack_crypto_ccm_t *) btstack_crypto;
891                 switch (btstack_crypto_ccm->state){
892                     case CCM_CALCULATE_AAD_XN:
893 #ifdef DEBUG_CCM
894                         printf("CCM_CALCULATE_AAD_XN\n");
895 #endif
896                         btstack_crypto_ccm_calc_aad_xn(btstack_crypto_ccm);
897                         break;
898                     case CCM_CALCULATE_X1:
899 #ifdef DEBUG_CCM
900                         printf("CCM_CALCULATE_X1\n");
901 #endif
902                         btstack_crypto_ccm_calc_x1(btstack_crypto_ccm);
903                         break;
904                     case CCM_CALCULATE_S0:
905 #ifdef DEBUG_CCM
906                         printf("CCM_CALCULATE_S0\n");
907 #endif
908                         btstack_crypto_ccm_calc_s0(btstack_crypto_ccm);
909                         break;
910                     case CCM_CALCULATE_SN:
911 #ifdef DEBUG_CCM
912                         printf("CCM_CALCULATE_SN\n");
913 #endif
914                         btstack_crypto_ccm_calc_sn(btstack_crypto_ccm);
915                         break;
916                     case CCM_CALCULATE_XN:
917 #ifdef DEBUG_CCM
918                         printf("CCM_CALCULATE_XN\n");
919 #endif
920                         btstack_crypto_ccm_calc_xn(btstack_crypto_ccm, (btstack_crypto->operation == BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK) ? btstack_crypto_ccm->input : btstack_crypto_ccm->output);
921                         break;
922                     default:
923                         break;
924                 }
925                 break;
926 
927 #ifdef ENABLE_ECC_P256
928             case BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY:
929                 btstack_crypto_ec_p192 = (btstack_crypto_ecc_p256_t *) btstack_crypto;
930                 switch (btstack_crypto_ecc_p256_key_generation_state){
931                     case ECC_P256_KEY_GENERATION_DONE:
932                         // done
933                         btstack_crypto_log_ec_publickey(btstack_crypto_ecc_p256_public_key);
934                         (void)memcpy(btstack_crypto_ec_p192->public_key,
935                                      btstack_crypto_ecc_p256_public_key, 64);
936                         btstack_linked_list_pop(&btstack_crypto_operations);
937                         (*btstack_crypto_ec_p192->btstack_crypto.context_callback.callback)(btstack_crypto_ec_p192->btstack_crypto.context_callback.context);
938                         break;
939                     case ECC_P256_KEY_GENERATION_IDLE:
940 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
941                         log_info("start ecc random");
942                         btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_GENERATING_RANDOM;
943                         btstack_crypto_ecc_p256_random_offset = 0;
944                         btstack_crypto_wait_for_hci_result = true;
945                         hci_send_cmd(&hci_le_rand);
946 #else
947                         btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_W4_KEY;
948                         btstack_crypto_wait_for_hci_result = 1;
949                         hci_send_cmd(&hci_le_read_local_p256_public_key);
950 #endif
951                         break;
952 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
953                     case ECC_P256_KEY_GENERATION_GENERATING_RANDOM:
954                         log_info("more ecc random");
955                         btstack_crypto_wait_for_hci_result = true;
956                         hci_send_cmd(&hci_le_rand);
957                         break;
958 #endif
959                     default:
960                         break;
961                 }
962                 break;
963             case BTSTACK_CRYPTO_ECC_P256_CALCULATE_DHKEY:
964                 btstack_crypto_ec_p192 = (btstack_crypto_ecc_p256_t *) btstack_crypto;
965 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
966                 btstack_crypto_ecc_p256_calculate_dhkey_software(btstack_crypto_ec_p192);
967                 // done
968                 btstack_linked_list_pop(&btstack_crypto_operations);
969                 (*btstack_crypto_ec_p192->btstack_crypto.context_callback.callback)(btstack_crypto_ec_p192->btstack_crypto.context_callback.context);
970 #else
971                 btstack_crypto_wait_for_hci_result = 1;
972                 hci_send_cmd(&hci_le_generate_dhkey, &btstack_crypto_ec_p192->public_key[0], &btstack_crypto_ec_p192->public_key[32]);
973 #endif
974                 break;
975 
976 #endif /* ENABLE_ECC_P256 */
977 
978             default:
979                 break;
980         }
981     }
982 }
983 
984 static void btstack_crypto_handle_random_data(const uint8_t * data, uint16_t len){
985     btstack_crypto_random_t * btstack_crypto_random;
986     btstack_crypto_t * btstack_crypto = (btstack_crypto_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
987     uint16_t bytes_to_copy;
988 	if (!btstack_crypto) return;
989     switch (btstack_crypto->operation){
990         case BTSTACK_CRYPTO_RANDOM:
991             btstack_crypto_random = (btstack_crypto_random_t*) btstack_crypto;
992             bytes_to_copy = btstack_min(btstack_crypto_random->size, len);
993             (void)memcpy(btstack_crypto_random->buffer, data, bytes_to_copy);
994             btstack_crypto_random->buffer += bytes_to_copy;
995             btstack_crypto_random->size   -= bytes_to_copy;
996             // data processed, more?
997             if (!btstack_crypto_random->size) {
998                 // done
999                 btstack_linked_list_pop(&btstack_crypto_operations);
1000                 (*btstack_crypto_random->btstack_crypto.context_callback.callback)(btstack_crypto_random->btstack_crypto.context_callback.context);
1001             }
1002             break;
1003 #ifdef ENABLE_ECC_P256
1004         case BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY:
1005             (void)memcpy(&btstack_crypto_ecc_p256_random[btstack_crypto_ecc_p256_random_len],
1006 			 data, 8);
1007             btstack_crypto_ecc_p256_random_len += 8u;
1008             if (btstack_crypto_ecc_p256_random_len >= 64u) {
1009                 btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_ACTIVE;
1010                 btstack_crypto_ecc_p256_generate_key_software();
1011                 btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_DONE;
1012             }
1013             break;
1014 #endif
1015         default:
1016             break;
1017     }
1018 	// more work?
1019 	btstack_crypto_run();
1020 }
1021 
1022 #ifndef USE_BTSTACK_AES128
1023 static void btstack_crypto_handle_encryption_result(const uint8_t * data){
1024 	btstack_crypto_aes128_t      * btstack_crypto_aes128;
1025 	btstack_crypto_aes128_cmac_t * btstack_crypto_cmac;
1026     btstack_crypto_ccm_t         * btstack_crypto_ccm;
1027 	uint8_t result[16];
1028 
1029     btstack_crypto_t * btstack_crypto = (btstack_crypto_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
1030 	if (!btstack_crypto) return;
1031 	switch (btstack_crypto->operation){
1032 		case BTSTACK_CRYPTO_AES128:
1033 			btstack_crypto_aes128 = (btstack_crypto_aes128_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
1034 		    reverse_128(data, btstack_crypto_aes128->ciphertext);
1035             btstack_crypto_done(btstack_crypto);
1036 			break;
1037 		case BTSTACK_CRYPTO_CMAC_GENERATOR:
1038 		case BTSTACK_CRYPTO_CMAC_MESSAGE:
1039 			btstack_crypto_cmac = (btstack_crypto_aes128_cmac_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
1040 		    reverse_128(data, result);
1041 		    btstack_crypto_cmac_handle_encryption_result(btstack_crypto_cmac, result);
1042 			break;
1043         case BTSTACK_CRYPTO_CCM_DIGEST_BLOCK:
1044         case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK:
1045         case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK:
1046             btstack_crypto_ccm = (btstack_crypto_ccm_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
1047             switch (btstack_crypto_ccm->state){
1048                 case CCM_W4_X1:
1049                     reverse_128(data, btstack_crypto_ccm->x_i);
1050                     btstack_crypto_ccm_handle_x1(btstack_crypto_ccm);
1051                     break;
1052                 case CCM_W4_XN:
1053                     reverse_128(data, btstack_crypto_ccm->x_i);
1054                     btstack_crypto_ccm_handle_xn(btstack_crypto_ccm);
1055                     break;
1056                 case CCM_W4_AAD_XN:
1057                     reverse_128(data, btstack_crypto_ccm->x_i);
1058                     btstack_crypto_ccm_handle_aad_xn(btstack_crypto_ccm);
1059                     break;
1060                 case CCM_W4_S0:
1061                     btstack_crypto_ccm_handle_s0(btstack_crypto_ccm, data);
1062                     break;
1063                 case CCM_W4_SN:
1064                     btstack_crypto_ccm_handle_sn(btstack_crypto_ccm, data);
1065                     break;
1066                 default:
1067                     break;
1068             }
1069             break;
1070 		default:
1071 			break;
1072 	}
1073 }
1074 #endif
1075 
1076 static void btstack_crypto_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
1077     UNUSED(cid);         // ok: there is no channel
1078     UNUSED(size);        // ok: fixed format events read from HCI buffer
1079 
1080 #ifdef ENABLE_ECC_P256
1081 #ifndef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
1082     btstack_crypto_ecc_p256_t * btstack_crypto_ec_p192;
1083 #endif
1084 #endif
1085     bool ecdh_operations_supported;
1086 
1087     if (packet_type != HCI_EVENT_PACKET)  return;
1088 
1089     switch (hci_event_packet_get_type(packet)){
1090         case BTSTACK_EVENT_STATE:
1091             if (btstack_event_state_get_state(packet) != HCI_STATE_HALTING) break;
1092             if (!btstack_crypto_wait_for_hci_result) break;
1093             // request stack to defer shutdown a bit
1094             hci_halting_defer();
1095             break;
1096 
1097         case HCI_EVENT_COMMAND_COMPLETE:
1098             switch (hci_event_command_complete_get_command_opcode(packet)){
1099 #ifndef USE_BTSTACK_AES128
1100                 case HCI_OPCODE_HCI_LE_ENCRYPT:
1101                     if (!btstack_crypto_wait_for_hci_result) return;
1102                     btstack_crypto_wait_for_hci_result = 0;
1103     	            btstack_crypto_handle_encryption_result(&packet[6]);
1104                     break;
1105 #endif
1106                 case HCI_OPCODE_HCI_LE_RAND:
1107                     if (!btstack_crypto_wait_for_hci_result) return;
1108                     btstack_crypto_wait_for_hci_result = false;
1109                     btstack_crypto_handle_random_data(&packet[6], 8);
1110                     break;
1111                 case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_COMMANDS:
1112                     ecdh_operations_supported = (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+34u] & 0x06u) == 0x06u;
1113                     UNUSED(ecdh_operations_supported);
1114                     log_info("controller supports ECDH operation: %u", ecdh_operations_supported);
1115 #ifdef ENABLE_ECC_P256
1116 #ifndef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
1117                     // Assert controller supports ECDH operation if we don't implement them ourselves
1118                     // Please add ENABLE_MICRO_ECC_FOR_LE_SECURE_CONNECTIONS to btstack_config.h and add 3rd-party/micro-ecc to your port
1119                     btstack_assert(ecdh_operations_supported != 0);
1120 #endif
1121 #endif
1122                     break;
1123                 default:
1124                     break;
1125             }
1126             break;
1127 
1128 #ifdef ENABLE_ECC_P256
1129 #ifndef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
1130         case HCI_EVENT_LE_META:
1131             btstack_crypto_ec_p192 = (btstack_crypto_ecc_p256_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
1132             if (!btstack_crypto_ec_p192) break;
1133             switch (hci_event_le_meta_get_subevent_code(packet)){
1134                 case HCI_SUBEVENT_LE_READ_LOCAL_P256_PUBLIC_KEY_COMPLETE:
1135                     if (btstack_crypto_ec_p192->btstack_crypto.operation != BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY) break;
1136                     if (!btstack_crypto_wait_for_hci_result) return;
1137                     btstack_crypto_wait_for_hci_result = 0;
1138                     if (hci_subevent_le_read_local_p256_public_key_complete_get_status(packet)){
1139                         log_error("Read Local P256 Public Key failed");
1140                     }
1141                     hci_subevent_le_read_local_p256_public_key_complete_get_dhkey_x(packet, &btstack_crypto_ecc_p256_public_key[0]);
1142                     hci_subevent_le_read_local_p256_public_key_complete_get_dhkey_y(packet, &btstack_crypto_ecc_p256_public_key[32]);
1143                     btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_DONE;
1144                     break;
1145                 case HCI_SUBEVENT_LE_GENERATE_DHKEY_COMPLETE:
1146                     if (btstack_crypto_ec_p192->btstack_crypto.operation != BTSTACK_CRYPTO_ECC_P256_CALCULATE_DHKEY) break;
1147                     if (!btstack_crypto_wait_for_hci_result) return;
1148                     btstack_crypto_wait_for_hci_result = 0;
1149                     if (hci_subevent_le_generate_dhkey_complete_get_status(packet)){
1150                         log_error("Generate DHKEY failed -> abort");
1151                     }
1152                     hci_subevent_le_generate_dhkey_complete_get_dhkey(packet, btstack_crypto_ec_p192->dhkey);
1153                     // done
1154                     btstack_linked_list_pop(&btstack_crypto_operations);
1155                     (*btstack_crypto_ec_p192->btstack_crypto.context_callback.callback)(btstack_crypto_ec_p192->btstack_crypto.context_callback.context);
1156                     break;
1157                 default:
1158                     break;
1159             }
1160             break;
1161 #endif
1162 #endif
1163         default:
1164             break;
1165     }
1166 
1167     // try processing
1168 	btstack_crypto_run();
1169 }
1170 
1171 void btstack_crypto_init(void){
1172 	if (btstack_crypto_initialized) return;
1173 	btstack_crypto_initialized = true;
1174 
1175 	// register with HCI
1176     hci_event_callback_registration.callback = &btstack_crypto_event_handler;
1177     hci_add_event_handler(&hci_event_callback_registration);
1178 #ifndef USE_BTSTACK_AES128
1179     btstack_crypto_cmac_state = CMAC_IDLE;
1180 #endif
1181 #ifdef ENABLE_ECC_P256
1182     btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_IDLE;
1183 #endif
1184 #ifdef USE_MBEDTLS_ECC_P256
1185 	mbedtls_ecp_group_init(&mbedtls_ec_group);
1186 	mbedtls_ecp_group_load(&mbedtls_ec_group, MBEDTLS_ECP_DP_SECP256R1);
1187 #endif
1188 }
1189 
1190 void btstack_crypto_random_generate(btstack_crypto_random_t * request, uint8_t * buffer, uint16_t size, void (* callback)(void * arg), void * callback_arg){
1191 	request->btstack_crypto.context_callback.callback  = callback;
1192 	request->btstack_crypto.context_callback.context   = callback_arg;
1193 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_RANDOM;
1194 	request->buffer = buffer;
1195 	request->size   = size;
1196 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1197 	btstack_crypto_run();
1198 }
1199 
1200 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){
1201 	request->btstack_crypto.context_callback.callback  = callback;
1202 	request->btstack_crypto.context_callback.context   = callback_arg;
1203 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_AES128;
1204 	request->key 									   = key;
1205 	request->plaintext      					       = plaintext;
1206 	request->ciphertext 							   = ciphertext;
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_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){
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_GENERATOR;
1215 	request->key 									   = key;
1216 	request->size 									   = size;
1217 	request->data.get_byte_callback					   = get_byte_callback;
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_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){
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 									   = key;
1228 	request->size 									   = size;
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 void btstack_crypto_aes128_cmac_zero(btstack_crypto_aes128_cmac_t * request, uint16_t size, const uint8_t * message,  uint8_t * hash, void (* callback)(void * arg), void * callback_arg){
1236     request->btstack_crypto.context_callback.callback  = callback;
1237     request->btstack_crypto.context_callback.context   = callback_arg;
1238     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CMAC_MESSAGE;
1239     request->key                                       = zero;
1240     request->size                                      = size;
1241     request->data.message                              = message;
1242     request->hash                                      = hash;
1243     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1244     btstack_crypto_run();
1245 }
1246 
1247 #ifdef ENABLE_ECC_P256
1248 void btstack_crypto_ecc_p256_generate_key(btstack_crypto_ecc_p256_t * request, uint8_t * public_key, void (* callback)(void * arg), void * callback_arg){
1249     // reset key generation
1250     if (btstack_crypto_ecc_p256_key_generation_state == ECC_P256_KEY_GENERATION_DONE){
1251         btstack_crypto_ecc_p256_random_len = 0;
1252         btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_IDLE;
1253     }
1254     request->btstack_crypto.context_callback.callback  = callback;
1255     request->btstack_crypto.context_callback.context   = callback_arg;
1256     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY;
1257     request->public_key                                = public_key;
1258     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1259     btstack_crypto_run();
1260 }
1261 
1262 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){
1263     request->btstack_crypto.context_callback.callback  = callback;
1264     request->btstack_crypto.context_callback.context   = callback_arg;
1265     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_ECC_P256_CALCULATE_DHKEY;
1266     request->public_key                                = (uint8_t *) public_key;
1267     request->dhkey                                     = dhkey;
1268     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1269     btstack_crypto_run();
1270 }
1271 
1272 int btstack_crypto_ecc_p256_validate_public_key(const uint8_t * public_key){
1273 
1274     // validate public key using micro-ecc
1275     int err = 0;
1276 
1277 #ifdef USE_MICRO_ECC_P256
1278 #if uECC_SUPPORTS_secp256r1
1279     // standard version
1280     err = uECC_valid_public_key(public_key, uECC_secp256r1()) == 0;
1281 #else
1282     // static version
1283     err = uECC_valid_public_key(public_key) == 0;
1284 #endif
1285 #endif
1286 
1287 #ifdef USE_MBEDTLS_ECC_P256
1288     mbedtls_ecp_point Q;
1289     mbedtls_ecp_point_init( &Q );
1290     mbedtls_mpi_read_binary(&Q.X, &public_key[0], 32);
1291     mbedtls_mpi_read_binary(&Q.Y, &public_key[32], 32);
1292     mbedtls_mpi_lset(&Q.Z, 1);
1293     err = mbedtls_ecp_check_pubkey(&mbedtls_ec_group, &Q);
1294     mbedtls_ecp_point_free( & Q);
1295 #endif
1296 
1297     if (err != 0){
1298         log_error("public key invalid %x", err);
1299     }
1300     return  err;
1301 }
1302 #endif
1303 
1304 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){
1305     request->key         = key;
1306     request->nonce       = nonce;
1307     request->message_len = message_len;
1308     request->aad_len     = additional_authenticated_data_len;
1309     request->aad_offset  = 0;
1310     request->auth_len    = auth_len;
1311     request->counter     = 1;
1312     request->state       = CCM_CALCULATE_X1;
1313 }
1314 
1315 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){
1316     // not implemented yet
1317     request->btstack_crypto.context_callback.callback  = callback;
1318     request->btstack_crypto.context_callback.context   = callback_arg;
1319     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CCM_DIGEST_BLOCK;
1320     request->block_len                                 = additional_authenticated_data_len;
1321     request->input                                     = additional_authenticated_data;
1322     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1323     btstack_crypto_run();
1324 }
1325 
1326 void btstack_crypto_ccm_get_authentication_value(btstack_crypto_ccm_t * request, uint8_t * authentication_value){
1327     (void)memcpy(authentication_value, request->x_i, request->auth_len);
1328 }
1329 
1330 void btstack_crypto_ccm_encrypt_block(btstack_crypto_ccm_t * request, uint16_t len, const uint8_t * plaintext, uint8_t * ciphertext, void (* callback)(void * arg), void * callback_arg){
1331 #ifdef DEBUG_CCM
1332     printf("\nbtstack_crypto_ccm_encrypt_block, len %u\n", len);
1333 #endif
1334     request->btstack_crypto.context_callback.callback  = callback;
1335     request->btstack_crypto.context_callback.context   = callback_arg;
1336     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK;
1337     request->block_len                                 = len;
1338     request->input                                     = plaintext;
1339     request->output                                    = ciphertext;
1340     if (request->state != CCM_CALCULATE_X1){
1341         request->state  = CCM_CALCULATE_XN;
1342     }
1343     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1344     btstack_crypto_run();
1345 }
1346 
1347 void btstack_crypto_ccm_decrypt_block(btstack_crypto_ccm_t * request, uint16_t len, const uint8_t * ciphertext, uint8_t * plaintext, void (* callback)(void * arg), void * callback_arg){
1348     request->btstack_crypto.context_callback.callback  = callback;
1349     request->btstack_crypto.context_callback.context   = callback_arg;
1350     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK;
1351     request->block_len                                 = len;
1352     request->input                                     = ciphertext;
1353     request->output                                    = plaintext;
1354     if (request->state != CCM_CALCULATE_X1){
1355         request->state  = CCM_CALCULATE_SN;
1356     }
1357     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1358     btstack_crypto_run();
1359 }
1360 
1361 // De-Init
1362 void btstack_crypto_deinit(void) {
1363     btstack_crypto_initialized = false;
1364     btstack_crypto_wait_for_hci_result = false;
1365     btstack_crypto_operations = NULL;
1366 }
1367 
1368 // PTS only
1369 void btstack_crypto_ecc_p256_set_key(const uint8_t * public_key, const uint8_t * private_key){
1370 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
1371     (void)memcpy(btstack_crypto_ecc_p256_d, private_key, 32);
1372     (void)memcpy(btstack_crypto_ecc_p256_public_key, public_key, 64);
1373     btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_DONE;
1374 #else
1375     UNUSED(public_key);
1376     UNUSED(private_key);
1377 #endif
1378 }
1379 
1380 // Unit testing
1381 int btstack_crypto_idle(void){
1382     return btstack_linked_list_empty(&btstack_crypto_operations);
1383 }
1384 void btstack_crypto_reset(void){
1385     btstack_crypto_deinit();
1386     btstack_crypto_init();
1387 }
1388