1 /*
2  * Copyright (c) 2021-2022, Arm Limited. All rights reserved.
3  *
4  * SPDX-License-Identifier: BSD-3-Clause
5  *
6  */
7 
8 #include "tfm_plat_crypto_nv_seed.h"
9 #include "tfm_plat_otp.h"
10 #include "psa/internal_trusted_storage.h"
11 
tfm_plat_crypto_provision_entropy_seed(void)12 int tfm_plat_crypto_provision_entropy_seed(void)
13 {
14     enum tfm_plat_err_t plat_err;
15     int err;
16     uint8_t buf[64];
17 
18     /* If the seed is already provisioned, then return successfully */
19     err = tfm_plat_crypto_nv_seed_read(buf, sizeof(buf));
20     if (err == TFM_CRYPTO_NV_SEED_SUCCESS) {
21         return err;
22     }
23 
24     plat_err = tfm_plat_otp_read(PLAT_OTP_ID_ENTROPY_SEED, sizeof(buf), buf);
25     if(plat_err != TFM_PLAT_ERR_SUCCESS) {
26         return TFM_CRYPTO_NV_SEED_FAILED;
27     }
28 
29     err = tfm_plat_crypto_nv_seed_write(buf, sizeof(buf));
30     if (err != TFM_CRYPTO_NV_SEED_SUCCESS) {
31         return err;
32     }
33 
34     return TFM_CRYPTO_NV_SEED_SUCCESS;
35 }
36 
tfm_plat_crypto_nv_seed_read(unsigned char * buf,size_t buf_len)37 int tfm_plat_crypto_nv_seed_read(unsigned char *buf, size_t buf_len)
38 {
39     psa_storage_uid_t uid = NV_SEED_FILE_ID;
40     psa_status_t status;
41     size_t data_length = 0;
42 
43     status = psa_its_get(uid, 0, buf_len, buf, &data_length);
44 
45     if (status == PSA_SUCCESS && data_length == buf_len) {
46         return TFM_CRYPTO_NV_SEED_SUCCESS;
47     } else {
48         return TFM_CRYPTO_NV_SEED_FAILED;
49     }
50 }
51 
tfm_plat_crypto_nv_seed_write(const unsigned char * buf,size_t buf_len)52 int tfm_plat_crypto_nv_seed_write(const unsigned char *buf, size_t buf_len)
53 {
54     psa_storage_uid_t uid = NV_SEED_FILE_ID;
55     psa_status_t status;
56 
57     status = psa_its_set(uid, buf_len, buf, 0);
58 
59     if (status == PSA_SUCCESS) {
60         return TFM_CRYPTO_NV_SEED_SUCCESS;
61     } else {
62         return TFM_CRYPTO_NV_SEED_FAILED;
63     }
64 }
65