1 /*
2  * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *    http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "hks_get_udid.h"
17 
18 #include "securec.h"
19 
20 #include "hks_log.h"
21 #include "hks_template.h"
22 #include "hks_type.h"
23 
24 #define HKS_HARDWARE_UDID_LEN 32
25 
26 #ifndef _CUT_AUTHENTICATE_
27 
28 #ifdef GET_DEV_UDID_ENABLE
29 #include "hks_crypto_hal.h"
30 #include "parameter.h"
31 
32 #define HKS_HARDWARE_UDID_STRING_LEN    (HKS_HARDWARE_UDID_LEN * 2 + 1)
33 
ComputeHash(const char * data,uint32_t len,struct HksBlob * hash)34 static int32_t ComputeHash(const char *data, uint32_t len, struct HksBlob *hash)
35 {
36     struct HksBlob srcData = { len, (uint8_t *)data };
37     return HksCryptoHalHash(HKS_DIGEST_SHA256, &srcData, hash);
38 }
39 
40 #endif
41 
HksGetHardwareUdid(uint8_t * udid,uint32_t udidLen)42 int32_t HksGetHardwareUdid(uint8_t *udid, uint32_t udidLen)
43 {
44 #ifdef GET_DEV_UDID_ENABLE
45     char devUdidString[HKS_HARDWARE_UDID_STRING_LEN] = {0};
46     int32_t ret = GetDevUdid(devUdidString, sizeof(devUdidString));
47     if (ret != 0) {
48         HKS_LOG_E("Get dev udid error, ret = 0x%" LOG_PUBLIC "x", ret);
49         return HKS_ERROR_NO_PERMISSION;
50     }
51 
52     uint8_t devUdid[HKS_HARDWARE_UDID_LEN] = {0};
53     struct HksBlob hashData = { HKS_HARDWARE_UDID_LEN, devUdid };
54     ret = ComputeHash(devUdidString, sizeof(devUdidString), &hashData);
55     HKS_IF_NOT_SUCC_LOGE_RETURN(ret, ret, "compute udid hash failed")
56 #else
57     /* simulation implementation */
58     const uint8_t devUdid[HKS_HARDWARE_UDID_LEN] = {
59         0xFE, 0xF1, 0xFA, 0xD5, 0xB6, 0x9D, 0x4A, 0xC8,
60         0x52, 0xE7, 0xF5, 0xA3, 0x8F, 0x0D, 0xE1, 0xC0,
61         0x87, 0xA4, 0x40, 0xF2, 0x10, 0x5A, 0xC9, 0x31,
62         0xC4, 0xD7, 0x2E, 0xDE, 0x51, 0xE3, 0x73, 0x11,
63     };
64 #endif
65 
66     if (memcpy_s(udid, udidLen, devUdid, HKS_HARDWARE_UDID_LEN) != EOK) {
67         HKS_LOG_E("Memcpy udid failed!");
68         return HKS_ERROR_BAD_STATE;
69     }
70 
71     return HKS_SUCCESS;
72 }
73 #endif /* _CUT_AUTHENTICATE_ */
74