xref: /btstack/src/btstack_crypto.c (revision 6a580d1772276b965c7f6ed4aba86036f102ce2f)
1 /*
2  * Copyright (C) 2017 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY MATTHIAS RINGWALD AND CONTRIBUTORS
18  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
21  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
24  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
27  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  */
31 
32 #define __BTSTACK_FILE__ "btstack_crypto.c"
33 
34 /*
35  * btstack_crypto.h
36  *
37  * Central place for all crypto-related functions with completion callbacks to allow
38  * using of MCU crypto peripherals or the Bluetooth controller
39  */
40 
41 #include "btstack_crypto.h"
42 
43 #include "btstack_debug.h"
44 #include "btstack_event.h"
45 #include "btstack_linked_list.h"
46 #include "btstack_util.h"
47 #include "hci.h"
48 
49 // backwards-compatitility ENABLE_MICRO_ECC_FOR_LE_SECURE_CONNECTIONS -> ENABLE_MICRO_ECC_P256
50 #if defined(ENABLE_MICRO_ECC_FOR_LE_SECURE_CONNECTIONS) && !defined(ENABLE_MICRO_ECC_P256)
51 #define ENABLE_MICRO_ECC_P256
52 #endif
53 
54 // configure ECC implementations
55 #if defined(ENABLE_MICRO_ECC_P256) && defined(HAVE_MBEDTLS_ECC_P256)
56 #error "If you have mbedTLS (HAVE_MBEDTLS_ECC_P256), please disable uECC (ENABLE_MICRO_ECC_P256) in bstack_config.h"
57 #endif
58 
59 // Software ECC-P256 implementation provided by micro-ecc
60 #ifdef ENABLE_MICRO_ECC_P256
61 #define ENABLE_ECC_P256
62 #define USE_MICRO_ECC_P256
63 #define USE_SOFTWARE_ECC_P256_IMPLEMENTATION
64 #include "uECC.h"
65 #endif
66 
67 // Software ECC-P256 implementation provided by mbedTLS
68 #ifdef HAVE_MBEDTLS_ECC_P256
69 #define ENABLE_ECC_P256
70 #define USE_MBEDTLS_ECC_P256
71 #define USE_SOFTWARE_ECC_P256_IMPLEMENTATION
72 #include "mbedtls/config.h"
73 #include "mbedtls/platform.h"
74 #include "mbedtls/ecp.h"
75 #endif
76 
77 #if defined(ENABLE_LE_SECURE_CONNECTIONS) && !defined(ENABLE_ECC_P256)
78 #define ENABLE_ECC_P256
79 #endif
80 
81 // Software AES128
82 #ifdef HAVE_AES128
83 #define USE_BTSTACK_AES128
84 void btstack_aes128_calc(const uint8_t * key, const uint8_t * plaintext, uint8_t * result);
85 #endif
86 
87 typedef enum {
88     CMAC_IDLE,
89     CMAC_CALC_SUBKEYS,
90     CMAC_W4_SUBKEYS,
91     CMAC_CALC_MI,
92     CMAC_W4_MI,
93     CMAC_CALC_MLAST,
94     CMAC_W4_MLAST
95 } btstack_crypto_cmac_state_t;
96 
97 typedef enum {
98     ECC_P256_KEY_GENERATION_IDLE,
99     ECC_P256_KEY_GENERATION_GENERATING_RANDOM,
100     ECC_P256_KEY_GENERATION_ACTIVE,
101     ECC_P256_KEY_GENERATION_W4_KEY,
102     ECC_P256_KEY_GENERATION_DONE,
103 } btstack_crypto_ecc_p256_key_generation_state_t;
104 
105 static void btstack_crypto_run(void);
106 
107 const static uint8_t zero[16] = { 0 };
108 
109 static uint8_t btstack_crypto_initialized;
110 static btstack_linked_list_t btstack_crypto_operations;
111 static btstack_packet_callback_registration_t hci_event_callback_registration;
112 static uint8_t btstack_crypto_wait_for_hci_result;
113 
114 // state for AES-CMAC
115 static btstack_crypto_cmac_state_t btstack_crypto_cmac_state;
116 static sm_key_t btstack_crypto_cmac_k;
117 static sm_key_t btstack_crypto_cmac_x;
118 static sm_key_t btstack_crypto_cmac_m_last;
119 static uint8_t  btstack_crypto_cmac_block_current;
120 static uint8_t  btstack_crypto_cmac_block_count;
121 
122 // state for AES-CCM
123 static uint8_t btstack_crypto_ccm_s[16];
124 
125 
126 #ifdef ENABLE_ECC_P256
127 
128 static uint8_t  btstack_crypto_ecc_p256_public_key[64];
129 static uint8_t  btstack_crypto_ecc_p256_random[64];
130 static uint8_t  btstack_crypto_ecc_p256_random_len;
131 static uint8_t  btstack_crypto_ecc_p256_random_offset;
132 static btstack_crypto_ecc_p256_key_generation_state_t btstack_crypto_ecc_p256_key_generation_state;
133 
134 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
135 static uint8_t btstack_crypto_ecc_p256_d[32];
136 #endif
137 
138 #endif /* ENABLE_ECC_P256 */
139 
140 static void btstack_crypto_done(btstack_crypto_t * btstack_crypto){
141     btstack_linked_list_pop(&btstack_crypto_operations);
142     (*btstack_crypto->context_callback.callback)(btstack_crypto->context_callback.context);
143 }
144 
145 static inline void btstack_crypto_cmac_next_state(void){
146     btstack_crypto_cmac_state = (btstack_crypto_cmac_state_t) (((int)btstack_crypto_cmac_state) + 1);
147 }
148 
149 static int btstack_crypto_cmac_last_block_complete(btstack_crypto_aes128_cmac_t * btstack_crypto_cmac){
150 	uint16_t len = btstack_crypto_cmac->size;
151     if (len == 0) return 0;
152     return (len & 0x0f) == 0;
153 }
154 
155 static void btstack_crypto_aes128_start(const sm_key_t key, const sm_key_t plaintext){
156  	uint8_t key_flipped[16];
157  	uint8_t plaintext_flipped[16];
158     reverse_128(key, key_flipped);
159     reverse_128(plaintext, plaintext_flipped);
160  	btstack_crypto_wait_for_hci_result = 1;
161     hci_send_cmd(&hci_le_encrypt, key_flipped, plaintext_flipped);
162 }
163 
164 static uint8_t btstack_crypto_cmac_get_byte(btstack_crypto_aes128_cmac_t * btstack_crypto_cmac, uint16_t pos){
165 	if (btstack_crypto_cmac->btstack_crypto.operation == BTSTACK_CRYPTO_CMAC_GENERATOR){
166 		return (*btstack_crypto_cmac->get_byte_callback)(pos);
167 	} else {
168 		return btstack_crypto_cmac->message[pos];
169 	}
170 }
171 
172 static void btstack_crypto_cmac_handle_aes_engine_ready(btstack_crypto_aes128_cmac_t * btstack_crypto_cmac){
173     switch (btstack_crypto_cmac_state){
174         case CMAC_CALC_SUBKEYS: {
175             sm_key_t const_zero;
176             memset(const_zero, 0, 16);
177             btstack_crypto_cmac_next_state();
178             btstack_crypto_aes128_start(btstack_crypto_cmac_k, const_zero);
179             break;
180         }
181         case CMAC_CALC_MI: {
182             int j;
183             sm_key_t y;
184             for (j=0;j<16;j++){
185                 y[j] = btstack_crypto_cmac_x[j] ^ btstack_crypto_cmac_get_byte(btstack_crypto_cmac, btstack_crypto_cmac_block_current*16 + j);
186             }
187             btstack_crypto_cmac_block_current++;
188             btstack_crypto_cmac_next_state();
189             btstack_crypto_aes128_start(btstack_crypto_cmac_k, y);
190             break;
191         }
192         case CMAC_CALC_MLAST: {
193             int i;
194             sm_key_t y;
195             for (i=0;i<16;i++){
196                 y[i] = btstack_crypto_cmac_x[i] ^ btstack_crypto_cmac_m_last[i];
197             }
198             btstack_crypto_cmac_block_current++;
199             btstack_crypto_cmac_next_state();
200             btstack_crypto_aes128_start(btstack_crypto_cmac_k, y);
201             break;
202         }
203         default:
204             log_info("btstack_crypto_cmac_handle_aes_engine_ready called in state %u", btstack_crypto_cmac_state);
205             break;
206     }
207 }
208 
209 static void btstack_crypto_cmac_shift_left_by_one_bit_inplace(int len, uint8_t * data){
210     int i;
211     int carry = 0;
212     for (i=len-1; i >= 0 ; i--){
213         int new_carry = data[i] >> 7;
214         data[i] = data[i] << 1 | carry;
215         carry = new_carry;
216     }
217 }
218 
219 static void btstack_crypto_cmac_handle_encryption_result(btstack_crypto_aes128_cmac_t * btstack_crypto_cmac, sm_key_t data){
220     switch (btstack_crypto_cmac_state){
221         case CMAC_W4_SUBKEYS: {
222             sm_key_t k1;
223             memcpy(k1, data, 16);
224             btstack_crypto_cmac_shift_left_by_one_bit_inplace(16, k1);
225             if (data[0] & 0x80){
226                 k1[15] ^= 0x87;
227             }
228             sm_key_t k2;
229             memcpy(k2, k1, 16);
230             btstack_crypto_cmac_shift_left_by_one_bit_inplace(16, k2);
231             if (k1[0] & 0x80){
232                 k2[15] ^= 0x87;
233             }
234 
235             log_info_key("k", btstack_crypto_cmac_k);
236             log_info_key("k1", k1);
237             log_info_key("k2", k2);
238 
239             // step 4: set m_last
240             int i;
241             if (btstack_crypto_cmac_last_block_complete(btstack_crypto_cmac)){
242                 for (i=0;i<16;i++){
243                     btstack_crypto_cmac_m_last[i] = btstack_crypto_cmac_get_byte(btstack_crypto_cmac, btstack_crypto_cmac->size - 16 + i) ^ k1[i];
244                 }
245             } else {
246                 int valid_octets_in_last_block = btstack_crypto_cmac->size & 0x0f;
247                 for (i=0;i<16;i++){
248                     if (i < valid_octets_in_last_block){
249                         btstack_crypto_cmac_m_last[i] = btstack_crypto_cmac_get_byte(btstack_crypto_cmac, (btstack_crypto_cmac->size & 0xfff0) + i) ^ k2[i];
250                         continue;
251                     }
252                     if (i == valid_octets_in_last_block){
253                         btstack_crypto_cmac_m_last[i] = 0x80 ^ k2[i];
254                         continue;
255                     }
256                     btstack_crypto_cmac_m_last[i] = k2[i];
257                 }
258             }
259 
260             // next
261             btstack_crypto_cmac_state = btstack_crypto_cmac_block_current < btstack_crypto_cmac_block_count - 1 ? CMAC_CALC_MI : CMAC_CALC_MLAST;
262             break;
263         }
264         case CMAC_W4_MI:
265             memcpy(btstack_crypto_cmac_x, data, 16);
266             btstack_crypto_cmac_state = btstack_crypto_cmac_block_current < btstack_crypto_cmac_block_count - 1 ? CMAC_CALC_MI : CMAC_CALC_MLAST;
267             break;
268         case CMAC_W4_MLAST:
269             // done
270             log_info("Setting CMAC Engine to IDLE");
271             btstack_crypto_cmac_state = CMAC_IDLE;
272             log_info_key("CMAC", data);
273             memcpy(btstack_crypto_cmac->hash, data, 16);
274 			btstack_linked_list_pop(&btstack_crypto_operations);
275 			(*btstack_crypto_cmac->btstack_crypto.context_callback.callback)(btstack_crypto_cmac->btstack_crypto.context_callback.context);
276             break;
277         default:
278             log_info("btstack_crypto_cmac_handle_encryption_result called in state %u", btstack_crypto_cmac_state);
279             break;
280     }
281 }
282 
283 static void btstack_crypto_cmac_start(btstack_crypto_aes128_cmac_t * btstack_crypto_cmac){
284 
285     memcpy(btstack_crypto_cmac_k, btstack_crypto_cmac->key, 16);
286     memset(btstack_crypto_cmac_x, 0, 16);
287     btstack_crypto_cmac_block_current = 0;
288 
289     // step 2: n := ceil(len/const_Bsize);
290     btstack_crypto_cmac_block_count = (btstack_crypto_cmac->size + 15) / 16;
291 
292     // step 3: ..
293     if (btstack_crypto_cmac_block_count==0){
294         btstack_crypto_cmac_block_count = 1;
295     }
296     log_info("btstack_crypto_cmac_start: len %u, block count %u", btstack_crypto_cmac->size, btstack_crypto_cmac_block_count);
297 
298     // first, we need to compute l for k1, k2, and m_last
299     btstack_crypto_cmac_state = CMAC_CALC_SUBKEYS;
300 
301     // let's go
302     btstack_crypto_cmac_handle_aes_engine_ready(btstack_crypto_cmac);
303 }
304 
305 /*
306   To encrypt the message data we use Counter (CTR) mode.  We first
307   define the key stream blocks by:
308 
309       S_i := E( K, A_i )   for i=0, 1, 2, ...
310 
311   The values A_i are formatted as follows, where the Counter field i is
312   encoded in most-significant-byte first order:
313 
314   Octet Number   Contents
315   ------------   ---------
316   0              Flags
317   1 ... 15-L     Nonce N
318   16-L ... 15    Counter i
319 
320   Bit Number   Contents
321   ----------   ----------------------
322   7            Reserved (always zero)
323   6            Reserved (always zero)
324   5 ... 3      Zero
325   2 ... 0      L'
326 */
327 
328 static void btstack_crypto_ccm_setup_a_i(btstack_crypto_ccm_t * btstack_crypto_ccm, uint16_t counter){
329     btstack_crypto_ccm_s[0] = 1;  // L' = L - 1
330     memcpy(&btstack_crypto_ccm_s[1], btstack_crypto_ccm->nonce, 13);
331     big_endian_store_16(btstack_crypto_ccm_s, 14, counter);
332 }
333 
334 /*
335  The first step is to compute the authentication field T.  This is
336    done using CBC-MAC [MAC].  We first define a sequence of blocks B_0,
337    B_1, ..., B_n and then apply CBC-MAC to these blocks.
338 
339    The first block B_0 is formatted as follows, where l(m) is encoded in
340    most-significant-byte first order:
341 
342       Octet Number   Contents
343       ------------   ---------
344       0              Flags
345       1 ... 15-L     Nonce N
346       16-L ... 15    l(m)
347 
348    Within the first block B_0, the Flags field is formatted as follows:
349 
350       Bit Number   Contents
351       ----------   ----------------------
352       7            Reserved (always zero)
353       6            Adata
354       5 ... 3      M'
355       2 ... 0      L'
356  */
357 
358 static void btstack_crypto_ccm_setup_b_0(btstack_crypto_ccm_t * btstack_crypto_ccm, uint8_t * b0){
359     b0[0] = (3 << 3) | 1 ;  // Adata = 0, M' = (M-2)/2, L' = L - 1
360     memcpy(&b0[1], btstack_crypto_ccm->nonce, 13);
361     big_endian_store_16(b0, 14, btstack_crypto_ccm->message_len);
362 }
363 
364 #ifdef ENABLE_ECC_P256
365 
366 static void btstack_crypto_log_ec_publickey(const uint8_t * ec_q){
367     log_info("Elliptic curve: X");
368     log_info_hexdump(&ec_q[0],32);
369     log_info("Elliptic curve: Y");
370     log_info_hexdump(&ec_q[32],32);
371 }
372 
373 #if (defined(USE_MICRO_ECC_P256) && !defined(WICED_VERSION)) || defined(USE_MBEDTLS_ECC_P256)
374 // @return OK
375 static int sm_generate_f_rng(unsigned char * buffer, unsigned size){
376     if (btstack_crypto_ecc_p256_key_generation_state != ECC_P256_KEY_GENERATION_ACTIVE) return 0;
377     log_info("sm_generate_f_rng: size %u - offset %u", (int) size, btstack_crypto_ecc_p256_random_offset);
378     while (size) {
379         *buffer++ = btstack_crypto_ecc_p256_random[btstack_crypto_ecc_p256_random_offset++];
380         size--;
381     }
382     return 1;
383 }
384 #endif
385 #ifdef USE_MBEDTLS_ECC_P256
386 // @return error - just wrap sm_generate_f_rng
387 static int sm_generate_f_rng_mbedtls(void * context, unsigned char * buffer, size_t size){
388     UNUSED(context);
389     return sm_generate_f_rng(buffer, size) == 0;
390 }
391 #endif /* USE_MBEDTLS_ECC_P256 */
392 
393 static void btstack_crypto_ecc_p256_generate_key_software(void){
394 
395     btstack_crypto_ecc_p256_random_offset = 0;
396 
397     // generate EC key
398 #ifdef USE_MICRO_ECC_P256
399 
400 #ifndef WICED_VERSION
401     log_info("set uECC RNG for initial key generation with 64 random bytes");
402     // micro-ecc from WICED SDK uses its wiced_crypto_get_random by default - no need to set it
403     uECC_set_rng(&sm_generate_f_rng);
404 #endif /* WICED_VERSION */
405 
406 #if uECC_SUPPORTS_secp256r1
407     // standard version
408     uECC_make_key(btstack_crypto_ecc_p256_public_key, btstack_crypto_ecc_p256_d, uECC_secp256r1());
409 
410     // disable RNG again, as returning no randmon data lets shared key generation fail
411     log_info("disable uECC RNG in standard version after key generation");
412     uECC_set_rng(NULL);
413 #else
414     // static version
415     uECC_make_key(btstack_crypto_ecc_p256_public_key, btstack_crypto_ecc_p256_d);
416 #endif
417 #endif /* USE_MICRO_ECC_P256 */
418 
419 #ifdef USE_MBEDTLS_ECC_P256
420     mbedtls_mpi d;
421     mbedtls_ecp_point P;
422     mbedtls_mpi_init(&d);
423     mbedtls_ecp_point_init(&P);
424     int res = mbedtls_ecp_gen_keypair(&mbedtls_ec_group, &d, &P, &sm_generate_f_rng_mbedtls, NULL);
425     log_info("gen keypair %x", res);
426     mbedtls_mpi_write_binary(&P.X, &btstack_crypto_ecc_p256_public_key[0],  32);
427     mbedtls_mpi_write_binary(&P.Y, &btstack_crypto_ecc_p256_public_key[32], 32);
428     mbedtls_mpi_write_binary(&d, btstack_crypto_ecc_p256_d, 32);
429     mbedtls_ecp_point_free(&P);
430     mbedtls_mpi_free(&d);
431 #endif  /* USE_MBEDTLS_ECC_P256 */
432 }
433 
434 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
435 static void btstack_crypto_ecc_p256_calculate_dhkey_software(btstack_crypto_ecc_p256_t * btstack_crypto_ec_p192){
436     memset(btstack_crypto_ec_p192->dhkey, 0, 32);
437 
438 #ifdef USE_MICRO_ECC_P256
439 #if uECC_SUPPORTS_secp256r1
440     // standard version
441     uECC_shared_secret(btstack_crypto_ec_p192->public_key, btstack_crypto_ecc_p256_d, btstack_crypto_ec_p192->dhkey, uECC_secp256r1());
442 #else
443     // static version
444     uECC_shared_secret(btstack_crypto_ec_p192->public_key, btstack_crypto_ecc_p256_d, btstack_crypto_ec_p192->dhkey);
445 #endif
446 #endif
447 
448 #ifdef USE_MBEDTLS_ECC_P256
449     // da * Pb
450     mbedtls_mpi d;
451     mbedtls_ecp_point Q;
452     mbedtls_ecp_point DH;
453     mbedtls_mpi_init(&d);
454     mbedtls_ecp_point_init(&Q);
455     mbedtls_ecp_point_init(&DH);
456     mbedtls_mpi_read_binary(&d, btstack_crypto_ecc_p256_d, 32);
457     mbedtls_mpi_read_binary(&Q.X, &btstack_crypto_ec_p192->public_key[0] , 32);
458     mbedtls_mpi_read_binary(&Q.Y, &btstack_crypto_ec_p192->public_key[32], 32);
459     mbedtls_mpi_lset(&Q.Z, 1);
460     mbedtls_ecp_mul(&mbedtls_ec_group, &DH, &d, &Q, NULL, NULL);
461     mbedtls_mpi_write_binary(&DH.X, btstack_crypto_ec_p192->dhkey, 32);
462     mbedtls_ecp_point_free(&DH);
463     mbedtls_mpi_free(&d);
464     mbedtls_ecp_point_free(&Q);
465 #endif
466 
467     log_info("dhkey");
468     log_info_hexdump(btstack_crypto_ec_p192->dhkey, 32);
469 }
470 #endif
471 
472 #endif
473 
474 
475 static void btstack_crypto_ccm_calc_s0(btstack_crypto_ccm_t * btstack_crypto_ccm){
476     btstack_crypto_ccm->state = CCM_W4_S0;
477     btstack_crypto_ccm_setup_a_i(btstack_crypto_ccm, 0);
478     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_s);
479 }
480 
481 static void btstack_crypto_ccm_calc_sn(btstack_crypto_ccm_t * btstack_crypto_ccm){
482     btstack_crypto_ccm->state = CCM_W4_SN;
483     btstack_crypto_ccm_setup_a_i(btstack_crypto_ccm, btstack_crypto_ccm->counter);
484     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_s);
485 }
486 
487 static void btstack_crypto_ccm_calc_x1(btstack_crypto_ccm_t * btstack_crypto_ccm){
488     uint8_t btstack_crypto_ccm_buffer[16];
489     btstack_crypto_ccm->state = CCM_W4_X1;
490     btstack_crypto_ccm_setup_b_0(btstack_crypto_ccm, btstack_crypto_ccm_buffer);
491     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_buffer);
492 }
493 
494 static void btstack_crypto_ccm_calc_xn(btstack_crypto_ccm_t * btstack_crypto_ccm, const uint8_t * plaintext){
495     int i;
496     int bytes_to_decrypt;
497     uint8_t btstack_crypto_ccm_buffer[16];
498     btstack_crypto_ccm->state = CCM_W4_XN;
499     bytes_to_decrypt = btstack_min(btstack_crypto_ccm->block_len, 16);
500     i = 0;
501     while (i < bytes_to_decrypt){
502         btstack_crypto_ccm_buffer[i] =  btstack_crypto_ccm->x_i[i] ^ plaintext[i];
503         i++;
504     }
505     memcpy(&btstack_crypto_ccm_buffer[i], &btstack_crypto_ccm->x_i[i], 16 - bytes_to_decrypt);
506     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_buffer);
507 }
508 
509 static void btstack_crypto_ccm_handle_s0(btstack_crypto_ccm_t * btstack_crypto_ccm, const uint8_t * data){
510     // data is little-endian, flip on the fly
511     int i;
512     for (i=0;i<16;i++){
513         btstack_crypto_ccm->x_i[i] = btstack_crypto_ccm->x_i[i] ^ data[15-i];
514     }
515     btstack_crypto_done(&btstack_crypto_ccm->btstack_crypto);
516 }
517 
518 static void btstack_crypto_ccm_handle_sn(btstack_crypto_ccm_t * btstack_crypto_ccm, const uint8_t * data){
519     // data is little-endian, flip on the fly
520     int i;
521     uint16_t bytes_to_process = btstack_min(btstack_crypto_ccm->block_len, 16);
522     for (i=0;i<bytes_to_process;i++){
523         btstack_crypto_ccm->output[i] = btstack_crypto_ccm->input[i] ^ data[15-i];
524     }
525 }
526 
527 static void btstack_crypto_ccm_next_block(btstack_crypto_ccm_t * btstack_crypto_ccm, btstack_crypto_ccm_state_t state_when_done){
528     uint16_t bytes_to_process = btstack_min(btstack_crypto_ccm->block_len, 16);
529     // next block
530     btstack_crypto_ccm->counter++;
531     btstack_crypto_ccm->input      += bytes_to_process;
532     btstack_crypto_ccm->output     += bytes_to_process;
533     btstack_crypto_ccm->block_len  -= bytes_to_process;
534     if (btstack_crypto_ccm->block_len == 0){
535         btstack_crypto_ccm->state = CCM_CALCULATE_S0;
536     }
537     else {
538         btstack_crypto_ccm->state = state_when_done;
539     }
540 }
541 
542 static void btstack_crypto_run(void){
543 
544     btstack_crypto_aes128_t        * btstack_crypto_aes128;
545     btstack_crypto_ccm_t           * btstack_crypto_ccm;
546     btstack_crypto_aes128_cmac_t   * btstack_crypto_cmac;
547 #ifdef ENABLE_ECC_P256
548     btstack_crypto_ecc_p256_t      * btstack_crypto_ec_p192;
549 #endif
550 
551     // stack up and running?
552     if (hci_get_state() != HCI_STATE_WORKING) return;
553 
554 	// already active?
555 	if (btstack_crypto_wait_for_hci_result) return;
556 
557 	// anything to do?
558 	if (btstack_linked_list_empty(&btstack_crypto_operations)) return;
559 
560     // can send a command?
561     if (!hci_can_send_command_packet_now()) return;
562 
563 	btstack_crypto_t * btstack_crypto = (btstack_crypto_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
564 	switch (btstack_crypto->operation){
565 		case BTSTACK_CRYPTO_RANDOM:
566 			btstack_crypto_wait_for_hci_result = 1;
567 		    hci_send_cmd(&hci_le_rand);
568 		    break;
569 		case BTSTACK_CRYPTO_AES128:
570             btstack_crypto_aes128 = (btstack_crypto_aes128_t *) btstack_crypto;
571 #ifdef USE_BTSTACK_AES128
572             btstack_aes128_calc(btstack_crypto_aes128->key, btstack_crypto_aes128->plaintext, btstack_crypto_aes128->ciphertext);
573             btstack_crypto_done();
574 #else
575             btstack_crypto_aes128_start(btstack_crypto_aes128->key, btstack_crypto_aes128->plaintext);
576 #endif
577 		    break;
578 		case BTSTACK_CRYPTO_CMAC_MESSAGE:
579 		case BTSTACK_CRYPTO_CMAC_GENERATOR:
580 			btstack_crypto_wait_for_hci_result = 1;
581 			btstack_crypto_cmac = (btstack_crypto_aes128_cmac_t *) btstack_crypto;
582 			if (btstack_crypto_cmac_state == CMAC_IDLE){
583 				btstack_crypto_cmac_start(btstack_crypto_cmac);
584 			} else {
585 				btstack_crypto_cmac_handle_aes_engine_ready(btstack_crypto_cmac);
586 			}
587 			break;
588 
589         case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK:
590         case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK:
591 #ifdef USE_BTSTACK_AES128
592             log_error("ccm not implemented for software aes128 yet");
593 #else
594             btstack_crypto_ccm = (btstack_crypto_ccm_t *) btstack_crypto;
595             switch (btstack_crypto_ccm->state){
596                 case CCM_CALCULATE_X1:
597                     btstack_crypto_ccm_calc_x1(btstack_crypto_ccm);
598                     break;
599                 case CCM_CALCULATE_S0:
600                     btstack_crypto_ccm_calc_s0(btstack_crypto_ccm);
601                     break;
602                 case CCM_CALCULATE_SN:
603                     btstack_crypto_ccm_calc_sn(btstack_crypto_ccm);
604                     break;
605                 case CCM_CALCULATE_XN:
606                     btstack_crypto_ccm_calc_xn(btstack_crypto_ccm, btstack_crypto->operation == BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK ? btstack_crypto_ccm->input : btstack_crypto_ccm->output);
607                     break;
608                 default:
609                     break;
610             }
611 #endif
612             break;
613 
614 #ifdef ENABLE_ECC_P256
615         case BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY:
616             btstack_crypto_ec_p192 = (btstack_crypto_ecc_p256_t *) btstack_crypto;
617             switch (btstack_crypto_ecc_p256_key_generation_state){
618                 case ECC_P256_KEY_GENERATION_DONE:
619                     // done
620                     btstack_crypto_log_ec_publickey(btstack_crypto_ecc_p256_public_key);
621                     memcpy(btstack_crypto_ec_p192->public_key, btstack_crypto_ecc_p256_public_key, 64);
622                     btstack_linked_list_pop(&btstack_crypto_operations);
623                     (*btstack_crypto_ec_p192->btstack_crypto.context_callback.callback)(btstack_crypto_ec_p192->btstack_crypto.context_callback.context);
624                     break;
625                 case ECC_P256_KEY_GENERATION_IDLE:
626 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
627                     log_info("start ecc random");
628                     btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_GENERATING_RANDOM;
629                     btstack_crypto_ecc_p256_random_offset = 0;
630                     btstack_crypto_wait_for_hci_result = 1;
631                     hci_send_cmd(&hci_le_rand);
632 #else
633                     btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_W4_KEY;
634                     btstack_crypto_wait_for_hci_result = 1;
635                     hci_send_cmd(&hci_le_read_local_p256_public_key);
636 #endif
637                     break;
638 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
639                 case ECC_P256_KEY_GENERATION_GENERATING_RANDOM:
640                     log_info("more ecc random");
641                     btstack_crypto_wait_for_hci_result = 1;
642                     hci_send_cmd(&hci_le_rand);
643                     break;
644 #endif
645                 default:
646                     break;
647             }
648             break;
649         case BTSTACK_CRYPTO_ECC_P256_CALCULATE_DHKEY:
650             btstack_crypto_ec_p192 = (btstack_crypto_ecc_p256_t *) btstack_crypto;
651 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
652             btstack_crypto_ecc_p256_calculate_dhkey_software(btstack_crypto_ec_p192);
653             // done
654             btstack_linked_list_pop(&btstack_crypto_operations);
655             (*btstack_crypto_ec_p192->btstack_crypto.context_callback.callback)(btstack_crypto_ec_p192->btstack_crypto.context_callback.context);
656 #else
657             btstack_crypto_wait_for_hci_result = 1;
658             hci_send_cmd(&hci_le_generate_dhkey, &btstack_crypto_ec_p192->public_key[0], &btstack_crypto_ec_p192->public_key[32]);
659 #endif
660 #endif
661             break;
662 		default:
663 			break;
664 	}
665 }
666 
667 static void btstack_crypto_handle_random_data(const uint8_t * data, uint16_t len){
668     btstack_crypto_random_t * btstack_crypto_random;
669     btstack_crypto_t * btstack_crypto = (btstack_crypto_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
670     uint16_t bytes_to_copy;
671 	if (!btstack_crypto) return;
672     switch (btstack_crypto->operation){
673         case BTSTACK_CRYPTO_RANDOM:
674             btstack_crypto_random = (btstack_crypto_random_t*) btstack_crypto;
675             bytes_to_copy = btstack_min(btstack_crypto_random->size, len);
676             memcpy(btstack_crypto_random->buffer, data, bytes_to_copy);
677             btstack_crypto_random->buffer += bytes_to_copy;
678             btstack_crypto_random->size   -= bytes_to_copy;
679             // data processed, more?
680             if (!btstack_crypto_random->size) {
681                 // done
682                 btstack_linked_list_pop(&btstack_crypto_operations);
683                 (*btstack_crypto_random->btstack_crypto.context_callback.callback)(btstack_crypto_random->btstack_crypto.context_callback.context);
684             }
685             break;
686 #ifdef ENABLE_ECC_P256
687         case BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY:
688             memcpy(&btstack_crypto_ecc_p256_random[btstack_crypto_ecc_p256_random_len], data, 8);
689             btstack_crypto_ecc_p256_random_len += 8;
690             if (btstack_crypto_ecc_p256_random_len >= 64) {
691                 btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_ACTIVE;
692                 btstack_crypto_ecc_p256_generate_key_software();
693                 btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_DONE;
694             }
695             break;
696 #endif
697         default:
698             break;
699     }
700 	// more work?
701 	btstack_crypto_run();
702 }
703 
704 static void btstack_crypto_handle_encryption_result(const uint8_t * data){
705 	btstack_crypto_aes128_t      * btstack_crypto_aes128;
706 	btstack_crypto_aes128_cmac_t * btstack_crypto_cmac;
707     btstack_crypto_ccm_t         * btstack_crypto_ccm;
708 	uint8_t result[16];
709 
710     btstack_crypto_t * btstack_crypto = (btstack_crypto_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
711 	if (!btstack_crypto) return;
712 	switch (btstack_crypto->operation){
713 		case BTSTACK_CRYPTO_AES128:
714 			btstack_crypto_aes128 = (btstack_crypto_aes128_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
715 		    reverse_128(data, btstack_crypto_aes128->ciphertext);
716             btstack_crypto_done(btstack_crypto);
717 			break;
718 		case BTSTACK_CRYPTO_CMAC_GENERATOR:
719 		case BTSTACK_CRYPTO_CMAC_MESSAGE:
720 			btstack_crypto_cmac = (btstack_crypto_aes128_cmac_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
721 		    reverse_128(data, result);
722 		    btstack_crypto_cmac_handle_encryption_result(btstack_crypto_cmac, result);
723 			break;
724         case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK:
725             btstack_crypto_ccm = (btstack_crypto_ccm_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
726             switch (btstack_crypto_ccm->state){
727                 case CCM_W4_X1:
728                     reverse_128(data, btstack_crypto_ccm->x_i);
729                     btstack_crypto_ccm->state = CCM_CALCULATE_XN;
730                     break;
731                 case CCM_W4_XN:
732                     reverse_128(data, btstack_crypto_ccm->x_i);
733                     btstack_crypto_ccm->state = CCM_CALCULATE_SN;
734                     break;
735                 case CCM_W4_S0:
736                     btstack_crypto_ccm_handle_s0(btstack_crypto_ccm, data);
737                     break;
738                 case CCM_W4_SN:
739                     btstack_crypto_ccm_handle_sn(btstack_crypto_ccm, data);
740                     btstack_crypto_ccm_next_block(btstack_crypto_ccm, CCM_CALCULATE_XN);
741                     break;
742                 default:
743                     break;
744             }
745             break;
746         case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK:
747             btstack_crypto_ccm = (btstack_crypto_ccm_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
748             switch (btstack_crypto_ccm->state){
749                 case CCM_W4_X1:
750                     reverse_128(data, btstack_crypto_ccm->x_i);
751                     btstack_crypto_ccm->state = CCM_CALCULATE_SN;
752                     break;
753                 case CCM_W4_XN:
754                     reverse_128(data, btstack_crypto_ccm->x_i);
755                     btstack_crypto_ccm_next_block(btstack_crypto_ccm, CCM_CALCULATE_SN);
756                     break;
757                 case CCM_W4_S0:
758                     btstack_crypto_ccm_handle_s0(btstack_crypto_ccm, data);
759                     break;
760                 case CCM_W4_SN:
761                     btstack_crypto_ccm_handle_sn(btstack_crypto_ccm, data);
762                     btstack_crypto_ccm->state = CCM_CALCULATE_XN;
763                     break;
764                 default:
765                     break;
766             }
767             break;
768 		default:
769 			break;
770 	}
771 }
772 
773 static void btstack_crypto_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
774     UNUSED(cid);         // ok: there is no channel
775     UNUSED(size);        // ok: fixed format events read from HCI buffer
776 
777 #ifdef ENABLE_ECC_P256
778 #ifndef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
779     btstack_crypto_ecc_p256_t * btstack_crypto_ec_p192;
780 #endif
781 #endif
782 
783     if (packet_type != HCI_EVENT_PACKET)  return;
784 
785     switch (hci_event_packet_get_type(packet)){
786         case HCI_EVENT_COMMAND_COMPLETE:
787     	    if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_encrypt)){
788                 if (hci_get_state() != HCI_STATE_WORKING) return;
789                 if (!btstack_crypto_wait_for_hci_result) return;
790                 btstack_crypto_wait_for_hci_result = 0;
791     	        btstack_crypto_handle_encryption_result(&packet[6]);
792     	    }
793     	    if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_rand)){
794                 if (hci_get_state() != HCI_STATE_WORKING) return;
795                 if (!btstack_crypto_wait_for_hci_result) return;
796                 btstack_crypto_wait_for_hci_result = 0;
797     	        btstack_crypto_handle_random_data(&packet[6], 8);
798     	    }
799             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_commands)){
800                 int ecdh_operations_supported = (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+34] & 0x06) == 0x06;
801                 log_info("controller supports ECDH operation: %u", ecdh_operations_supported);
802 #ifdef ENABLE_ECC_P256
803 #ifndef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
804                 if (!ecdh_operations_supported){
805                     // mbedTLS can also be used if already available (and malloc is supported)
806                     log_error("ECC-P256 support enabled, but HCI Controller doesn't support it. Please add USE_MICRO_ECC_P256 to btstack_config.h");
807                 }
808 #endif
809 #endif
810             }
811             break;
812 
813 #ifdef ENABLE_ECC_P256
814 #ifndef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
815         case HCI_EVENT_LE_META:
816             btstack_crypto_ec_p192 = (btstack_crypto_ecc_p256_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
817             if (!btstack_crypto_ec_p192) break;
818             switch (hci_event_le_meta_get_subevent_code(packet)){
819                 case HCI_SUBEVENT_LE_READ_LOCAL_P256_PUBLIC_KEY_COMPLETE:
820                     if (btstack_crypto_ec_p192->btstack_crypto.operation != BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY) break;
821                     if (!btstack_crypto_wait_for_hci_result) return;
822                     btstack_crypto_wait_for_hci_result = 0;
823                     if (hci_subevent_le_read_local_p256_public_key_complete_get_status(packet)){
824                         log_error("Read Local P256 Public Key failed");
825                     }
826                     hci_subevent_le_read_local_p256_public_key_complete_get_dhkey_x(packet, &btstack_crypto_ecc_p256_public_key[0]);
827                     hci_subevent_le_read_local_p256_public_key_complete_get_dhkey_y(packet, &btstack_crypto_ecc_p256_public_key[32]);
828                     btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_DONE;
829                     break;
830                 case HCI_SUBEVENT_LE_GENERATE_DHKEY_COMPLETE:
831                     if (btstack_crypto_ec_p192->btstack_crypto.operation != BTSTACK_CRYPTO_ECC_P256_CALCULATE_DHKEY) break;
832                     if (!btstack_crypto_wait_for_hci_result) return;
833                     btstack_crypto_wait_for_hci_result = 0;
834                     if (hci_subevent_le_generate_dhkey_complete_get_status(packet)){
835                         log_error("Generate DHKEY failed -> abort");
836                     }
837                     hci_subevent_le_generate_dhkey_complete_get_dhkey(packet, btstack_crypto_ec_p192->dhkey);
838                     // done
839                     btstack_linked_list_pop(&btstack_crypto_operations);
840                     (*btstack_crypto_ec_p192->btstack_crypto.context_callback.callback)(btstack_crypto_ec_p192->btstack_crypto.context_callback.context);
841                     break;
842                 default:
843                     break;
844             }
845             break;
846 #endif
847 #endif
848         default:
849             break;
850     }
851 
852     // try processing
853 	btstack_crypto_run();
854 }
855 
856 void btstack_crypto_init(void){
857 	if (btstack_crypto_initialized) return;
858 	btstack_crypto_initialized = 1;
859 	// register with HCI
860     hci_event_callback_registration.callback = &btstack_crypto_event_handler;
861     hci_add_event_handler(&hci_event_callback_registration);
862 }
863 
864 void btstack_crypto_random_generate(btstack_crypto_random_t * request, uint8_t * buffer, uint16_t size, void (* callback)(void * arg), void * callback_arg){
865 	request->btstack_crypto.context_callback.callback  = callback;
866 	request->btstack_crypto.context_callback.context   = callback_arg;
867 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_RANDOM;
868 	request->buffer = buffer;
869 	request->size   = size;
870 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
871 	btstack_crypto_run();
872 }
873 
874 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){
875 	request->btstack_crypto.context_callback.callback  = callback;
876 	request->btstack_crypto.context_callback.context   = callback_arg;
877 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_AES128;
878 	request->key 									   = key;
879 	request->plaintext      					       = plaintext;
880 	request->ciphertext 							   = ciphertext;
881 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
882 	btstack_crypto_run();
883 }
884 
885 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){
886 	request->btstack_crypto.context_callback.callback  = callback;
887 	request->btstack_crypto.context_callback.context   = callback_arg;
888 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_CMAC_GENERATOR;
889 	request->key 									   = key;
890 	request->size 									   = size;
891 	request->get_byte_callback 						   = get_byte_callback;
892 	request->hash 									   = hash;
893 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
894 	btstack_crypto_run();
895 }
896 
897 void btstack_crypto_aes128_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){
898 	request->btstack_crypto.context_callback.callback  = callback;
899 	request->btstack_crypto.context_callback.context   = callback_arg;
900 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_CMAC_MESSAGE;
901 	request->key 									   = key;
902 	request->size 									   = size;
903 	request->message        						   = message;
904 	request->hash 									   = hash;
905 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
906 	btstack_crypto_run();
907 }
908 
909 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){
910     request->btstack_crypto.context_callback.callback  = callback;
911     request->btstack_crypto.context_callback.context   = callback_arg;
912     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CMAC_MESSAGE;
913     request->key                                       = zero;
914     request->size                                      = len;
915     request->message                                   = message;
916     request->hash                                      = hash;
917     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
918     btstack_crypto_run();
919 }
920 
921 #ifdef ENABLE_ECC_P256
922 void btstack_crypto_ecc_p256_generate_key(btstack_crypto_ecc_p256_t * request, uint8_t * public_key, void (* callback)(void * arg), void * callback_arg){
923     request->btstack_crypto.context_callback.callback  = callback;
924     request->btstack_crypto.context_callback.context   = callback_arg;
925     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY;
926     request->public_key                                = public_key;
927     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
928     btstack_crypto_run();
929 }
930 
931 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){
932     request->btstack_crypto.context_callback.callback  = callback;
933     request->btstack_crypto.context_callback.context   = callback_arg;
934     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_ECC_P256_CALCULATE_DHKEY;
935     request->public_key                                = (uint8_t *) public_key;
936     request->dhkey                                     = dhkey;
937     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
938     btstack_crypto_run();
939 }
940 
941 int btstack_crypto_ecc_p256_validate_public_key(const uint8_t * public_key){
942 
943     // validate public key using micro-ecc
944     int err = 0;
945 
946 #ifdef USE_MICRO_ECC_P256
947 #if uECC_SUPPORTS_secp256r1
948     // standard version
949     err = uECC_valid_public_key(public_key, uECC_secp256r1()) == 0;
950 #else
951     // static version
952     err = uECC_valid_public_key(public_key) == 0;
953 #endif
954 #endif
955 
956 #ifdef USE_MBEDTLS_ECC_P256
957     mbedtls_ecp_point Q;
958     mbedtls_ecp_point_init( &Q );
959     mbedtls_mpi_read_binary(&Q.X, &public_key[0], 32);
960     mbedtls_mpi_read_binary(&Q.Y, &public_key[32], 32);
961     mbedtls_mpi_lset(&Q.Z, 1);
962     err = mbedtls_ecp_check_pubkey(&mbedtls_ec_group, &Q);
963     mbedtls_ecp_point_free( & Q);
964 #endif
965 
966     if (err){
967         log_error("public key invalid %x", err);
968     }
969     return  err;
970 }
971 #endif
972 
973 void btstack_crypo_ccm_init(btstack_crypto_ccm_t * request, const uint8_t * key, const uint8_t * nonce, uint16_t message_len){
974     request->key         = key;
975     request->nonce       = nonce;
976     request->message_len = message_len;
977     request->counter     = 1;
978 }
979 
980 void btstack_crypo_ccm_get_authentication_value(btstack_crypto_ccm_t * request, uint8_t * authentication_value){
981     memcpy(authentication_value, request->x_i, 8);
982 }
983 
984 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){
985     request->btstack_crypto.context_callback.callback  = callback;
986     request->btstack_crypto.context_callback.context   = callback_arg;
987     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK;
988     request->state                                     = CCM_CALCULATE_X1;
989     request->block_len                                 = block_len;
990     request->input                                     = plaintext;
991     request->output                                    = ciphertext;
992     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
993     btstack_crypto_run();
994 }
995 
996 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){
997     request->btstack_crypto.context_callback.callback  = callback;
998     request->btstack_crypto.context_callback.context   = callback_arg;
999     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK;
1000     request->state                                     = CCM_CALCULATE_X1;
1001     request->block_len                                 = block_len;
1002     request->input                                     = ciphertext;
1003     request->output                                    = plaintext;
1004     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1005     btstack_crypto_run();
1006 }
1007 
1008