1 /*
2  * Copyright (c) 2024 Raspberry Pi (Trading) Ltd.
3  *
4  * SPDX-License-Identifier: BSD-3-Clause
5  */
6 
7 #include <string.h>
8 #include "pico.h"
9 #include "pico/rand.h"
10 #include "mbedtls/sha256.h"
11 #include "common.h"
12 
13 /* Function to feed mbedtls entropy. */
mbedtls_hardware_poll(void * data __unused,unsigned char * output,size_t len,size_t * olen)14 int mbedtls_hardware_poll(void *data __unused, unsigned char *output, size_t len, size_t *olen) {
15     *olen = 0;
16     while(*olen < len) {
17         uint64_t rand_data = get_rand_64();
18         size_t to_copy = MIN(len, sizeof(rand_data));
19         memcpy(output + *olen, &rand_data, to_copy);
20         *olen += to_copy;
21     }
22     return 0;
23 }
24 
25 #ifdef MBEDTLS_SHA256_ALT
26 #if !LIB_PICO_SHA256
27 #error SHA256 hardware acceleration not supported
28 #endif
29 
30 // PICO_CONFIG: PICO_MBEDTLS_SHA256_ALT_USE_DMA, Whether to use DMA for writing to hardware for the mbedtls SHA-256 hardware acceleration, type=int, default=1, group=pico_stdlib
31 #ifndef PICO_MBEDTLS_SHA256_ALT_USE_DMA
32 #define PICO_MBEDTLS_SHA256_ALT_USE_DMA 1
33 #endif
34 
mbedtls_sha256_init(__unused mbedtls_sha256_context * ctx)35 void mbedtls_sha256_init(__unused mbedtls_sha256_context *ctx) {
36 }
37 
mbedtls_sha256_free(__unused mbedtls_sha256_context * ctx)38 void mbedtls_sha256_free(__unused mbedtls_sha256_context *ctx) {
39 }
40 
mbedtls_sha256_starts_ret(mbedtls_sha256_context * ctx,int is224)41 int mbedtls_sha256_starts_ret(mbedtls_sha256_context *ctx, int is224) {
42     hard_assert(!is224); // that's annoying
43     return pico_sha256_start_blocking(ctx, SHA256_BIG_ENDIAN, PICO_MBEDTLS_SHA256_ALT_USE_DMA);
44 }
45 
mbedtls_sha256_update_ret(mbedtls_sha256_context * ctx,const unsigned char * input,size_t ilen)46 int mbedtls_sha256_update_ret(mbedtls_sha256_context *ctx, const unsigned char *input, size_t ilen) {
47     pico_sha256_update_blocking(ctx, input, ilen);
48     return 0;
49 }
50 
mbedtls_sha256_finish_ret(mbedtls_sha256_context * ctx,unsigned char output[32])51 int mbedtls_sha256_finish_ret( mbedtls_sha256_context *ctx, unsigned char output[32]) {
52     sha256_result_t result;
53     pico_sha256_finish(ctx, &result);
54     memcpy(output, result.bytes, 32);
55     return 0;
56 }
57 #endif // MBEDTLS_SHA256_ALT
58