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 #include <psa/crypto.h>
14
15 #include "jwt.h"
16
jwt_sign_impl(struct jwt_builder * builder,const unsigned char * der_key,size_t der_key_len,unsigned char * sig,size_t sig_size)17 int jwt_sign_impl(struct jwt_builder *builder, const unsigned char *der_key, size_t der_key_len,
18 unsigned char *sig, size_t sig_size)
19 {
20 psa_status_t status;
21 psa_key_attributes_t attr = PSA_KEY_ATTRIBUTES_INIT;
22 psa_key_id_t key_id;
23 size_t sig_len_out;
24 psa_algorithm_t alg;
25 int ret;
26
27 #if defined(CONFIG_JWT_SIGN_ECDSA_PSA)
28 psa_set_key_type(&attr, PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1));
29 psa_set_key_algorithm(&attr, PSA_ALG_ECDSA(PSA_ALG_SHA_256));
30 alg = PSA_ALG_ECDSA(PSA_ALG_SHA_256);
31 #else
32 psa_set_key_type(&attr, PSA_KEY_TYPE_RSA_KEY_PAIR);
33 psa_set_key_algorithm(&attr, PSA_ALG_RSA_PKCS1V15_SIGN(PSA_ALG_SHA_256));
34 alg = PSA_ALG_RSA_PKCS1V15_SIGN(PSA_ALG_SHA_256);
35 #endif
36 psa_set_key_usage_flags(&attr, PSA_KEY_USAGE_SIGN_MESSAGE);
37
38 status = psa_import_key(&attr, der_key, der_key_len, &key_id);
39 if (status != PSA_SUCCESS) {
40 return -EINVAL;
41 }
42
43 status = psa_sign_message(key_id, alg,
44 builder->base, builder->buf - builder->base,
45 sig, sig_size, &sig_len_out);
46 ret = (status == PSA_SUCCESS) ? 0 : -EINVAL;
47
48 psa_destroy_key(key_id);
49
50 return ret;
51 }
52