1 /*
2 * Copyright (C) 2024 BayLibre SAS
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include <string.h>
8 #include <zephyr/types.h>
9 #include <errno.h>
10
11 #include <zephyr/data/jwt.h>
12 #include <zephyr/data/json.h>
13
14 #include <mbedtls/pk.h>
15 #include <mbedtls/rsa.h>
16 #include <mbedtls/sha256.h>
17 #include <zephyr/random/random.h>
18
19 #include "jwt.h"
20
csprng_wrapper(void * ctx,unsigned char * dest,size_t size)21 static int csprng_wrapper(void *ctx, unsigned char *dest, size_t size)
22 {
23 ARG_UNUSED(ctx);
24
25 return sys_csrand_get((void *)dest, size);
26 }
27
jwt_sign_impl(struct jwt_builder * builder,const unsigned char * der_key,size_t der_key_len,unsigned char * sig,size_t sig_size)28 int jwt_sign_impl(struct jwt_builder *builder, const unsigned char *der_key, size_t der_key_len,
29 unsigned char *sig, size_t sig_size)
30 {
31 int res;
32 mbedtls_pk_context ctx;
33 size_t sig_len_out;
34
35 mbedtls_pk_init(&ctx);
36
37 res = mbedtls_pk_parse_key(&ctx, der_key, der_key_len, NULL, 0, csprng_wrapper, NULL);
38 if (res != 0) {
39 return res;
40 }
41
42 uint8_t hash[32];
43
44 /*
45 * The '0' indicates to mbedtls to do a SHA256, instead of
46 * 224.
47 */
48 res = mbedtls_sha256(builder->base, builder->buf - builder->base, hash, 0);
49 if (res != 0) {
50 return res;
51 }
52
53 res = mbedtls_pk_sign(&ctx, MBEDTLS_MD_SHA256, hash, sizeof(hash), sig, sig_size,
54 &sig_len_out, csprng_wrapper, NULL);
55 return res;
56 }
57