1 /*
2  * Copyright (C) 2021-2023 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 "huks_adapter.h"
17 #include "huks_adapter_diff_impl.h"
18 #include "hc_log.h"
19 #include "hks_api.h"
20 #include "hks_param.h"
21 #include "hks_type.h"
22 #include "mbedtls_ec_adapter.h"
23 #include "string_util.h"
24 
25 #define BASE_IMPORT_PARAMS_LEN 7
26 #define EXT_IMPORT_PARAMS_LEN 2
27 #define ECDH_COMMON_SIZE_P256 512
28 #define BASE_HMAC_PARAMS_LEN 3
29 #define BASE_HMAC_DERIVE_PARAMS_LEN 5
30 #define BASE_HMAC_FINISH_PARAMS_LEN 3
31 #define BASE_AGREE_WITH_STORAGE_PARAMS_LEN 9
32 #define BASE_HKDF_PARAMS_LEN 6
33 #define BASE_COMPUTE_PSEUDONYM_PSK_PARAMS_LEN 11
34 #define BASE_SIGN_PARAMS_LEN 3
35 #define BASE_ENCRYPT_PARAMS_LEN 7
36 #define BASE_DECRYPT_PARAMS_LEN 7
37 #define BASE_AGREE_INIT_PARAMS_LEN 3
38 #define BASE_AGREE_FINISH_PARAMS_LEN 7
39 #define BASE_AGREE_PARAMS_LEN 3
40 #define BASE_GENERATE_KEY_PAIR_PARAMS_LEN 6
41 #define BASE_VERIFY_PARAMS_LEN 4
42 #define BASE_IMPORT_PUB_KEY_PARAMS_LEN 8
43 #define EXT_DE_PARAMS_LEN 1
44 #define EXT_CE_PARAMS_LEN 2
45 #define PSEUDONYM_KEY_FACTOR "hichain_pseudonym_psk_key"
46 #define PSEUDONYM_KEY_LEBEL "hichain_pseudonym_psk_label"
47 
48 static uint32_t g_purposeToHksKeyPurpose[] = {
49     HKS_KEY_PURPOSE_MAC,
50     HKS_KEY_PURPOSE_DERIVE,
51     HKS_KEY_PURPOSE_SIGN | HKS_KEY_PURPOSE_VERIFY,
52     HKS_KEY_PURPOSE_AGREE
53 };
54 
55 static enum HksKeyAlg g_algToHksAlgorithm[] = {
56     HKS_ALG_ED25519,
57     HKS_ALG_X25519,
58     HKS_ALG_ECC
59 };
60 
CheckKeyParams(const KeyParams * keyParams)61 static int32_t CheckKeyParams(const KeyParams *keyParams)
62 {
63     CHECK_PTR_RETURN_HAL_ERROR_CODE(keyParams, "keyParams");
64     CHECK_PTR_RETURN_HAL_ERROR_CODE(keyParams->keyBuff.key, "keyParams->keyBuff.key");
65     CHECK_LEN_ZERO_RETURN_ERROR_CODE(keyParams->keyBuff.keyLen, "keyParams->keyBuff.keyLen");
66     return HAL_SUCCESS;
67 }
68 
BaseCheckParams(const Uint8Buff ** inParams,const char ** paramTags,uint32_t len)69 static int32_t BaseCheckParams(const Uint8Buff **inParams, const char **paramTags, uint32_t len)
70 {
71     for (uint32_t i = 0; i < len; i++) {
72         CHECK_PTR_RETURN_HAL_ERROR_CODE(inParams[i], paramTags[i]);
73         CHECK_PTR_RETURN_HAL_ERROR_CODE(inParams[i]->val, paramTags[i]);
74         CHECK_LEN_ZERO_RETURN_ERROR_CODE(inParams[i]->length, paramTags[i]);
75     }
76     return HAL_SUCCESS;
77 }
78 
FreeParamSet(struct HksParamSet * paramSet)79 static void FreeParamSet(struct HksParamSet *paramSet)
80 {
81     if (paramSet == NULL) {
82         return;
83     }
84     HksFreeParamSet(&paramSet);
85 }
86 
ConstructParamSet(struct HksParamSet ** out,const struct HksParam * inParam,const uint32_t inParamNum)87 static int32_t ConstructParamSet(struct HksParamSet **out, const struct HksParam *inParam,
88     const uint32_t inParamNum)
89 {
90     struct HksParamSet *paramSet = NULL;
91     int32_t res = HksInitParamSet(&paramSet);
92     if (res != HKS_SUCCESS) {
93         LOGE("init param set failed, res = %d", res);
94         return HAL_ERR_INIT_PARAM_SET_FAILED;
95     }
96 
97     res = HksAddParams(paramSet, inParam, inParamNum);
98     if (res != HKS_SUCCESS) {
99         LOGE("add param failed, res = %d", res);
100         FreeParamSet(paramSet);
101         return HAL_ERR_ADD_PARAM_FAILED;
102     }
103 
104     res = HksBuildParamSet(&paramSet);
105     if (res != HKS_SUCCESS) {
106         LOGE("build param set failed, res = %d", res);
107         FreeParamSet(paramSet);
108         return HAL_ERR_BUILD_PARAM_SET_FAILED;
109     }
110 
111     *out = paramSet;
112     return HAL_SUCCESS;
113 }
114 
Sha256(const Uint8Buff * message,Uint8Buff * hash)115 static int32_t Sha256(const Uint8Buff *message, Uint8Buff *hash)
116 {
117     CHECK_PTR_RETURN_HAL_ERROR_CODE(message, "message");
118     CHECK_PTR_RETURN_HAL_ERROR_CODE(message->val, "message->val");
119     CHECK_LEN_ZERO_RETURN_ERROR_CODE(message->length, "message->length");
120 
121     CHECK_PTR_RETURN_HAL_ERROR_CODE(hash, "hash");
122     CHECK_PTR_RETURN_HAL_ERROR_CODE(hash->val, "hash->val");
123     CHECK_LEN_EQUAL_RETURN(hash->length, SHA256_LEN, "hash->length");
124 
125     struct HksBlob srcBlob = { message->length, message->val };
126     struct HksBlob hashBlob = { hash->length, hash->val };
127     struct HksParamSet *paramSet = NULL;
128     struct HksParam digestParam[] = {
129         {
130             .tag = HKS_TAG_DIGEST,
131             .uint32Param = HKS_DIGEST_SHA256
132         }
133     };
134     int32_t res = ConstructParamSet(&paramSet, digestParam, CAL_ARRAY_SIZE(digestParam));
135     if (res != HAL_SUCCESS) {
136         LOGE("construct param set failed, res = %d", res);
137         return res;
138     }
139 
140     res = HksHash(paramSet, &srcBlob, &hashBlob);
141     if (res != HKS_SUCCESS || hashBlob.size != SHA256_LEN) {
142         LOGE("[HUKS]: HksHash fail. [Res]: %d", res);
143         FreeParamSet(paramSet);
144         return HAL_FAILED;
145     }
146 
147     FreeParamSet(paramSet);
148     return HAL_SUCCESS;
149 }
150 
GenerateRandom(Uint8Buff * rand)151 static int32_t GenerateRandom(Uint8Buff *rand)
152 {
153     CHECK_PTR_RETURN_HAL_ERROR_CODE(rand, "rand");
154     CHECK_PTR_RETURN_HAL_ERROR_CODE(rand->val, "rand->val");
155     CHECK_LEN_ZERO_RETURN_ERROR_CODE(rand->length, "rand->length");
156 
157     struct HksBlob randBlob = { rand->length, rand->val };
158     int32_t res = HksGenerateRandom(NULL, &randBlob);
159     if (res != HKS_SUCCESS) {
160         LOGE("[HUKS]: HksGenerateRandom fail. [Res]: %d", res);
161         return HAL_FAILED;
162     }
163 
164     return HAL_SUCCESS;
165 }
166 
GetParamLen(bool isDeStorage,uint32_t baseLen)167 static uint32_t GetParamLen(bool isDeStorage, uint32_t baseLen)
168 {
169 #ifdef DEV_AUTH_ENABLE_CE
170     if (isDeStorage) {
171         return baseLen + EXT_DE_PARAMS_LEN;
172     } else {
173         return baseLen + EXT_CE_PARAMS_LEN;
174     }
175 #else
176     (void)isDeStorage;
177     return baseLen;
178 #endif
179 }
180 
AddStorageExtParams(struct HksParam * params,bool isDeStorage,uint32_t * idx,int32_t osAccountId)181 static void AddStorageExtParams(struct HksParam *params, bool isDeStorage, uint32_t *idx, int32_t osAccountId)
182 {
183 #ifdef DEV_AUTH_ENABLE_CE
184     if (isDeStorage) {
185         params[*idx].tag = HKS_TAG_AUTH_STORAGE_LEVEL;
186         params[(*idx)++].uint32Param = HKS_AUTH_STORAGE_LEVEL_DE;
187     } else {
188         params[*idx].tag = HKS_TAG_AUTH_STORAGE_LEVEL;
189         params[(*idx)++].uint32Param = HKS_AUTH_STORAGE_LEVEL_CE;
190         params[*idx].tag = HKS_TAG_SPECIFIC_USER_ID;
191         params[(*idx)++].uint32Param = osAccountId;
192     }
193 #else
194     (void)params;
195     (void)isDeStorage;
196     (void)idx;
197     (void)osAccountId;
198 #endif
199 }
200 
ConstructDeParamSet(struct HksParamSet ** paramSet)201 static int32_t ConstructDeParamSet(struct HksParamSet **paramSet)
202 {
203     struct HksParam keyParam[] = {
204         {
205             .tag = HKS_TAG_AUTH_STORAGE_LEVEL,
206             .uint32Param = HKS_AUTH_STORAGE_LEVEL_DE
207         }
208     };
209 
210     int32_t res = ConstructParamSet(paramSet, keyParam, CAL_ARRAY_SIZE(keyParam));
211     if (res != HAL_SUCCESS) {
212         LOGE("Construct de param set failed, res = %d", res);
213     }
214     return res;
215 }
216 
ConstructCeParamSet(int32_t osAccountId,struct HksParamSet ** paramSet)217 static int32_t ConstructCeParamSet(int32_t osAccountId, struct HksParamSet **paramSet)
218 {
219     struct HksParam keyParam[] = {
220         {
221             .tag = HKS_TAG_AUTH_STORAGE_LEVEL,
222             .uint32Param = HKS_AUTH_STORAGE_LEVEL_CE
223         }, {
224             .tag = HKS_TAG_SPECIFIC_USER_ID,
225             .uint32Param = osAccountId
226         }
227     };
228 
229     int32_t res = ConstructParamSet(paramSet, keyParam, CAL_ARRAY_SIZE(keyParam));
230     if (res != HAL_SUCCESS) {
231         LOGE("Construct ce param set failed, res = %d", res);
232     }
233     return res;
234 }
235 
ChangeStorageLevel(const struct HksBlob * keyAliasBlob,const struct HksParamSet * deParamSet,const struct HksParamSet * ceParamSet)236 static int32_t ChangeStorageLevel(const struct HksBlob *keyAliasBlob, const struct HksParamSet *deParamSet,
237     const struct HksParamSet *ceParamSet)
238 {
239 #ifdef DEV_AUTH_ENABLE_CE
240     return HksChangeStorageLevel(keyAliasBlob, deParamSet, ceParamSet);
241 #else
242     (void)keyAliasBlob;
243     (void)deParamSet;
244     (void)ceParamSet;
245     return HKS_SUCCESS;
246 #endif
247 }
248 
MoveDeKeyToCe(bool isKeyAlias,int32_t osAccountId,const struct HksBlob * keyAliasBlob)249 static void MoveDeKeyToCe(bool isKeyAlias, int32_t osAccountId, const struct HksBlob *keyAliasBlob)
250 {
251     if (!isKeyAlias) {
252         return;
253     }
254     struct HksParamSet *deParamSet = NULL;
255     if (ConstructDeParamSet(&deParamSet) != HAL_SUCCESS) {
256         return;
257     }
258     struct HksParamSet *ceParamSet = NULL;
259     if (ConstructCeParamSet(osAccountId, &ceParamSet) != HAL_SUCCESS) {
260         return;
261     }
262     int32_t res = ChangeStorageLevel(keyAliasBlob, deParamSet, ceParamSet);
263     if (res != HKS_SUCCESS) {
264         LOGE("Failed to move de key to ce!");
265     }
266 }
267 
ConstructCheckParamSet(bool isDeStorage,int32_t osAccountId,struct HksParamSet ** paramSet)268 static int32_t ConstructCheckParamSet(bool isDeStorage, int32_t osAccountId, struct HksParamSet **paramSet)
269 {
270     uint32_t len = GetParamLen(isDeStorage, 0);
271     if (len == 0) {
272         return HAL_SUCCESS;
273     }
274     struct HksParam *checkParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0);
275     if (checkParams == NULL) {
276         LOGE("Malloc for checkParams failed.");
277         return HAL_ERR_BAD_ALLOC;
278     }
279     uint32_t idx = 0;
280     AddStorageExtParams(checkParams, isDeStorage, &idx, osAccountId);
281     int32_t res = ConstructParamSet(paramSet, checkParams, idx);
282     HcFree(checkParams);
283     if (res != HAL_SUCCESS) {
284         LOGE("Failed to construct check param set, res: %d", res);
285     }
286     return res;
287 }
288 
CheckKeyExist(const Uint8Buff * keyAlias,bool isDeStorage,int32_t osAccountId)289 static int32_t CheckKeyExist(const Uint8Buff *keyAlias, bool isDeStorage, int32_t osAccountId)
290 {
291     CHECK_PTR_RETURN_HAL_ERROR_CODE(keyAlias, "keyAlias");
292     CHECK_PTR_RETURN_HAL_ERROR_CODE(keyAlias->val, "keyAlias->val");
293     CHECK_LEN_ZERO_RETURN_ERROR_CODE(keyAlias->length, "keyAlias->length");
294 
295     struct HksParamSet *deParamSet = NULL;
296     int32_t res = ConstructCheckParamSet(true, osAccountId, &deParamSet);
297     if (res != HAL_SUCCESS) {
298         return res;
299     }
300     struct HksParamSet *ceParamSet = NULL;
301     res = ConstructCheckParamSet(false, osAccountId, &ceParamSet);
302     if (res != HAL_SUCCESS) {
303         FreeParamSet(deParamSet);
304         return res;
305     }
306     struct HksBlob keyAliasBlob = { keyAlias->length, keyAlias->val };
307     if (isDeStorage) {
308         res = HksKeyExist(&keyAliasBlob, deParamSet);
309         if (res == HKS_SUCCESS) {
310             MoveDeKeyToCe(true, osAccountId, &keyAliasBlob);
311         } else {
312             res = HksKeyExist(&keyAliasBlob, ceParamSet);
313         }
314     } else {
315         res = HksKeyExist(&keyAliasBlob, ceParamSet);
316         if (res != HKS_SUCCESS) {
317             res = HksKeyExist(&keyAliasBlob, deParamSet);
318         }
319     }
320     FreeParamSet(deParamSet);
321     FreeParamSet(ceParamSet);
322     if (res != HKS_SUCCESS) {
323         LOGI("[HUKS]: HksKeyExist fail. [Res]: %d", res);
324         return HAL_FAILED;
325     }
326 
327     return HAL_SUCCESS;
328 }
329 
ConstructDeleteParamSet(bool isDeStorage,int32_t osAccountId,struct HksParamSet ** paramSet)330 static int32_t ConstructDeleteParamSet(bool isDeStorage, int32_t osAccountId, struct HksParamSet **paramSet)
331 {
332     uint32_t len = GetParamLen(isDeStorage, 0);
333     if (len == 0) {
334         return HAL_SUCCESS;
335     }
336     struct HksParam *deleteParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0);
337     if (deleteParams == NULL) {
338         LOGE("Malloc for deleteParams failed.");
339         return HAL_ERR_BAD_ALLOC;
340     }
341     uint32_t idx = 0;
342     AddStorageExtParams(deleteParams, isDeStorage, &idx, osAccountId);
343     int32_t res = ConstructParamSet(paramSet, deleteParams, idx);
344     HcFree(deleteParams);
345     if (res != HAL_SUCCESS) {
346         LOGE("Failed to construct delete param set, res: %d", res);
347     }
348     return res;
349 }
350 
DeleteKey(const Uint8Buff * keyAlias,bool isDeStorage,int32_t osAccountId)351 static int32_t DeleteKey(const Uint8Buff *keyAlias, bool isDeStorage, int32_t osAccountId)
352 {
353     CHECK_PTR_RETURN_HAL_ERROR_CODE(keyAlias, "keyAlias");
354     CHECK_PTR_RETURN_HAL_ERROR_CODE(keyAlias->val, "keyAlias->val");
355     CHECK_LEN_ZERO_RETURN_ERROR_CODE(keyAlias->length, "keyAlias->length");
356 
357     struct HksParamSet *deParamSet = NULL;
358     int32_t res = ConstructDeleteParamSet(true, osAccountId, &deParamSet);
359     if (res != HAL_SUCCESS) {
360         return res;
361     }
362     struct HksParamSet *ceParamSet = NULL;
363     res = ConstructDeleteParamSet(false, osAccountId, &ceParamSet);
364     if (res != HAL_SUCCESS) {
365         FreeParamSet(deParamSet);
366         return res;
367     }
368     struct HksBlob keyAliasBlob = { keyAlias->length, keyAlias->val };
369 
370     LOGI("[HUKS]: HksDeleteKey enter.");
371     if (isDeStorage) {
372         res = HksDeleteKey(&keyAliasBlob, deParamSet);
373         if (res != HKS_SUCCESS) {
374             res = HksDeleteKey(&keyAliasBlob, ceParamSet);
375         }
376     } else {
377         res = HksDeleteKey(&keyAliasBlob, ceParamSet);
378         if (res != HKS_SUCCESS) {
379             res = HksDeleteKey(&keyAliasBlob, deParamSet);
380         }
381     }
382     LOGI("[HUKS]: HksDeleteKey quit. [Res]: %d", res);
383 
384     FreeParamSet(deParamSet);
385     FreeParamSet(ceParamSet);
386     if (res == HKS_ERROR_NOT_EXIST) {
387         LOGI("Key not exists.");
388         return HAL_SUCCESS;
389     }
390     if (res != HKS_SUCCESS) {
391         LOGE("[HUKS]: HksDeleteKey fail. [Res]: %d", res);
392         return HAL_FAILED;
393     }
394     return HAL_SUCCESS;
395 }
396 
ConstructHmacParamSet(bool isDeStorage,int32_t osAccountId,bool isAlias,struct HksParamSet ** hmacParamSet)397 static int32_t ConstructHmacParamSet(bool isDeStorage, int32_t osAccountId, bool isAlias,
398     struct HksParamSet **hmacParamSet)
399 {
400     uint32_t len = GetParamLen(isDeStorage, BASE_HMAC_PARAMS_LEN);
401     struct HksParam *hmacParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0);
402     if (hmacParams == NULL) {
403         LOGE("Malloc for hmacParams failed.");
404         return HAL_ERR_BAD_ALLOC;
405     }
406     uint32_t idx = 0;
407     hmacParams[idx].tag = HKS_TAG_PURPOSE;
408     hmacParams[idx++].uint32Param = HKS_KEY_PURPOSE_MAC;
409     hmacParams[idx].tag = HKS_TAG_DIGEST;
410     hmacParams[idx++].uint32Param = HKS_DIGEST_SHA256;
411     hmacParams[idx].tag = HKS_TAG_IS_KEY_ALIAS;
412     hmacParams[idx++].boolParam = isAlias;
413     AddStorageExtParams(hmacParams, isDeStorage, &idx, osAccountId);
414     int32_t res = ConstructParamSet(hmacParamSet, hmacParams, idx);
415     HcFree(hmacParams);
416     if (res != HAL_SUCCESS) {
417         LOGE("Construct hmac param set failed, res = %d", res);
418     }
419     return res;
420 }
421 
CheckHmacParams(const KeyParams * keyParams,const Uint8Buff * message,const Uint8Buff * outHmac)422 static int32_t CheckHmacParams(const KeyParams *keyParams, const Uint8Buff *message, const Uint8Buff *outHmac)
423 {
424     int32_t res = CheckKeyParams(keyParams);
425     if (res != HAL_SUCCESS) {
426         return res;
427     }
428     const Uint8Buff *inParams[] = { message, outHmac };
429     const char *paramTags[] = { "message", "outHmac" };
430     res = BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams));
431     if (res != HAL_SUCCESS) {
432         return res;
433     }
434     CHECK_LEN_EQUAL_RETURN(outHmac->length, HMAC_LEN, "outHmac->length");
435     return HAL_SUCCESS;
436 }
437 
ComputeHmac(const KeyParams * keyParams,const Uint8Buff * message,Uint8Buff * outHmac)438 static int32_t ComputeHmac(const KeyParams *keyParams, const Uint8Buff *message, Uint8Buff *outHmac)
439 {
440     int32_t res = CheckHmacParams(keyParams, message, outHmac);
441     if (res != HAL_SUCCESS) {
442         return res;
443     }
444 
445     struct HksParamSet *deParamSet = NULL;
446     res = ConstructHmacParamSet(true, keyParams->osAccountId, keyParams->keyBuff.isAlias, &deParamSet);
447     if (res != HAL_SUCCESS) {
448         return res;
449     }
450     struct HksParamSet *ceParamSet = NULL;
451     res = ConstructHmacParamSet(false, keyParams->osAccountId, keyParams->keyBuff.isAlias, &ceParamSet);
452     if (res != HAL_SUCCESS) {
453         FreeParamSet(deParamSet);
454         return res;
455     }
456     struct HksBlob keyBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
457     struct HksBlob srcBlob = { message->length, message->val };
458     struct HksBlob hmacBlob = { outHmac->length, outHmac->val };
459 
460     LOGI("[HUKS]: HksMac enter.");
461     if (keyParams->isDeStorage) {
462         res = HksMac(&keyBlob, deParamSet, &srcBlob, &hmacBlob);
463     } else {
464         res = HksMac(&keyBlob, ceParamSet, &srcBlob, &hmacBlob);
465         if (res != HKS_SUCCESS  || hmacBlob.size != HMAC_LEN) {
466             res = HksMac(&keyBlob, deParamSet, &srcBlob, &hmacBlob);
467         }
468     }
469     LOGI("[HUKS]: HksMac quit. [Res]: %d", res);
470     FreeParamSet(deParamSet);
471     FreeParamSet(ceParamSet);
472     if (res != HKS_SUCCESS  || hmacBlob.size != HMAC_LEN) {
473         LOGE("[HUKS]: HksMac fail. [Res]: %d", res);
474         return HAL_FAILED;
475     }
476     return HAL_SUCCESS;
477 }
478 
ConstructDeriveParamSet(const KeyParams * keyParams,const Uint8Buff * message,struct HksParamSet ** deriveParamSet)479 static int32_t ConstructDeriveParamSet(const KeyParams *keyParams, const Uint8Buff *message,
480     struct HksParamSet **deriveParamSet)
481 {
482     struct HksBlob srcBlob = { message->length, message->val };
483     uint32_t len = GetParamLen(keyParams->isDeStorage, BASE_HMAC_DERIVE_PARAMS_LEN);
484     struct HksParam *hmacDeriveParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0);
485     if (hmacDeriveParams == NULL) {
486         LOGE("Malloc for hmacDeriveParams failed.");
487         return HAL_ERR_BAD_ALLOC;
488     }
489     uint32_t idx = 0;
490     hmacDeriveParams[idx].tag = HKS_TAG_ALGORITHM;
491     hmacDeriveParams[idx++].uint32Param = HKS_ALG_HMAC;
492     hmacDeriveParams[idx].tag = HKS_TAG_PURPOSE;
493     hmacDeriveParams[idx++].uint32Param = HKS_KEY_PURPOSE_DERIVE;
494     hmacDeriveParams[idx].tag = HKS_TAG_DIGEST;
495     hmacDeriveParams[idx++].uint32Param = HKS_DIGEST_SHA256;
496     hmacDeriveParams[idx].tag = HKS_TAG_DERIVE_KEY_SIZE;
497     hmacDeriveParams[idx++].uint32Param = HMAC_LEN;
498     hmacDeriveParams[idx].tag = HKS_TAG_INFO;
499     hmacDeriveParams[idx++].blob = srcBlob;
500     AddStorageExtParams(hmacDeriveParams, keyParams->isDeStorage, &idx, keyParams->osAccountId);
501     int32_t res = ConstructParamSet(deriveParamSet, hmacDeriveParams, idx);
502     HcFree(hmacDeriveParams);
503     if (res != HAL_SUCCESS) {
504         LOGE("Construct derive param set failed, res = %d", res);
505     }
506     return res;
507 }
508 
ConstructFinishParamSet(const KeyParams * keyParams,struct HksParamSet ** finishParamSet)509 static int32_t ConstructFinishParamSet(const KeyParams *keyParams, struct HksParamSet **finishParamSet)
510 {
511     uint32_t len = GetParamLen(keyParams->isDeStorage, BASE_HMAC_FINISH_PARAMS_LEN);
512     struct HksParam *hmacFinishParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0);
513     if (hmacFinishParams == NULL) {
514         LOGE("Malloc for hmacFinishParams failed.");
515         return HAL_ERR_BAD_ALLOC;
516     }
517     uint32_t idx = 0;
518     hmacFinishParams[idx].tag = HKS_TAG_ALGORITHM;
519     hmacFinishParams[idx++].uint32Param = HKS_ALG_AES;
520     hmacFinishParams[idx].tag = HKS_TAG_KEY_SIZE;
521     hmacFinishParams[idx++].uint32Param = HKS_AES_KEY_SIZE_256;
522     hmacFinishParams[idx].tag = HKS_TAG_PURPOSE;
523     hmacFinishParams[idx++].uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT;
524     AddStorageExtParams(hmacFinishParams, keyParams->isDeStorage, &idx, keyParams->osAccountId);
525     int32_t res = ConstructParamSet(finishParamSet, hmacFinishParams, idx);
526     HcFree(hmacFinishParams);
527     if (res != HAL_SUCCESS) {
528         LOGE("Construct finish param set failed, res = %d", res);
529     }
530     return res;
531 }
532 
CheckHmacWithThreeStageParams(const KeyParams * keyParams,const Uint8Buff * message,const Uint8Buff * outHmac)533 static int32_t CheckHmacWithThreeStageParams(const KeyParams *keyParams, const Uint8Buff *message,
534     const Uint8Buff *outHmac)
535 {
536     int32_t res = CheckKeyParams(keyParams);
537     if (res != HAL_SUCCESS) {
538         return res;
539     }
540     const Uint8Buff *inParams[] = { message, outHmac };
541     const char *paramTags[] = { "message", "outHmac" };
542     res = BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams));
543     if (res != HAL_SUCCESS) {
544         return res;
545     }
546     CHECK_LEN_EQUAL_RETURN(outHmac->length, HMAC_LEN, "outHmac->length");
547     return HAL_SUCCESS;
548 }
549 
ComputeHmacWithThreeStageInner(const KeyParams * keyParams,const Uint8Buff * message,Uint8Buff * outHmac)550 static int32_t ComputeHmacWithThreeStageInner(const KeyParams *keyParams, const Uint8Buff *message, Uint8Buff *outHmac)
551 {
552     struct HksParamSet *deriveParamSet = NULL;
553     int32_t res = ConstructDeriveParamSet(keyParams, message, &deriveParamSet);
554     if (res != HAL_SUCCESS) {
555         return res;
556     }
557 
558     struct HksParamSet *finishParamSet = NULL;
559     res = ConstructFinishParamSet(keyParams, &finishParamSet);
560     if (res != HAL_SUCCESS) {
561         FreeParamSet(deriveParamSet);
562         return res;
563     }
564     uint8_t handle[sizeof(uint64_t)] = { 0 };
565     struct HksBlob handleDerive = { sizeof(uint64_t), handle };
566     struct HksBlob keyAliasBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
567     res = HksInit(&keyAliasBlob, deriveParamSet, &handleDerive, NULL);
568     if (res != HKS_SUCCESS) {
569         LOGE("Failed to init derive params!");
570         FreeParamSet(deriveParamSet);
571         FreeParamSet(finishParamSet);
572         return HAL_FAILED;
573     }
574     uint8_t tmpOut[2048] = { 0 };
575     struct HksBlob outData = { 2048, tmpOut };
576     struct HksBlob inData = { 0, NULL };
577     res = HksUpdate(&handleDerive, deriveParamSet, &inData, &outData);
578     FreeParamSet(deriveParamSet);
579     if (res != HKS_SUCCESS) {
580         LOGE("Failed to update derive params!");
581         FreeParamSet(finishParamSet);
582         return HAL_FAILED;
583     }
584     struct HksBlob hmacBlob = { outHmac->length, outHmac->val };
585     res = HksFinish(&handleDerive, finishParamSet, &inData, &hmacBlob);
586     FreeParamSet(finishParamSet);
587     if (res != HKS_SUCCESS || hmacBlob.size != HMAC_LEN) {
588         LOGE("Compute hmac with three stage failed! [Res]: %d, [size]: %d", res, hmacBlob.size);
589         return HAL_FAILED;
590     }
591     return HAL_SUCCESS;
592 }
593 
ComputeHmacWithThreeStage(const KeyParams * keyParams,const Uint8Buff * message,Uint8Buff * outHmac)594 static int32_t ComputeHmacWithThreeStage(const KeyParams *keyParams, const Uint8Buff *message, Uint8Buff *outHmac)
595 {
596     int32_t res = CheckHmacWithThreeStageParams(keyParams, message, outHmac);
597     if (res != HAL_SUCCESS) {
598         return res;
599     }
600 
601     res = ComputeHmacWithThreeStageInner(keyParams, message, outHmac);
602     if (!keyParams->isDeStorage) {
603         return res;
604     }
605     if (res == HAL_SUCCESS) {
606         struct HksBlob keyAliasBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
607         MoveDeKeyToCe(keyParams->keyBuff.isAlias, keyParams->osAccountId, &keyAliasBlob);
608     } else {
609         KeyParams ceParams = {
610             .keyBuff = { keyParams->keyBuff.key, keyParams->keyBuff.keyLen, keyParams->keyBuff.isAlias },
611             .isDeStorage = false,
612             .osAccountId = keyParams->osAccountId
613         };
614         res = ComputeHmacWithThreeStageInner(&ceParams, message, outHmac);
615     }
616     return res;
617 }
618 
ConstructHkdfParamSet(bool isDeStorage,const KeyParams * keyParams,const Uint8Buff * salt,const Uint8Buff * keyInfo,struct HksParamSet ** paramSet)619 static int32_t ConstructHkdfParamSet(bool isDeStorage, const KeyParams *keyParams, const Uint8Buff *salt,
620     const Uint8Buff *keyInfo, struct HksParamSet **paramSet)
621 {
622     struct HksBlob saltBlob = { salt->length, salt->val };
623     struct HksBlob keyInfoBlob = { 0, NULL };
624     if (keyInfo != NULL) {
625         keyInfoBlob.size = keyInfo->length;
626         keyInfoBlob.data = keyInfo->val;
627     }
628     uint32_t len = GetParamLen(isDeStorage, BASE_HKDF_PARAMS_LEN);
629     struct HksParam *hkdfParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0);
630     if (hkdfParams == NULL) {
631         LOGE("Malloc for hkdfParams failed.");
632         return HAL_ERR_BAD_ALLOC;
633     }
634     uint32_t idx = 0;
635     hkdfParams[idx].tag = HKS_TAG_PURPOSE;
636     hkdfParams[idx++].uint32Param = HKS_KEY_PURPOSE_DERIVE;
637     hkdfParams[idx].tag = HKS_TAG_ALGORITHM;
638     hkdfParams[idx++].uint32Param = HKS_ALG_HKDF;
639     hkdfParams[idx].tag = HKS_TAG_DIGEST;
640     hkdfParams[idx++].uint32Param = HKS_DIGEST_SHA256;
641     hkdfParams[idx].tag = HKS_TAG_SALT;
642     hkdfParams[idx++].blob = saltBlob;
643     hkdfParams[idx].tag = HKS_TAG_INFO;
644     hkdfParams[idx++].blob = keyInfoBlob;
645     hkdfParams[idx].tag = HKS_TAG_IS_KEY_ALIAS;
646     hkdfParams[idx++].boolParam = keyParams->keyBuff.isAlias;
647     AddStorageExtParams(hkdfParams, isDeStorage, &idx, keyParams->osAccountId);
648     int32_t res = ConstructParamSet(paramSet, hkdfParams, idx);
649     HcFree(hkdfParams);
650     if (res != HAL_SUCCESS) {
651         LOGE("Failed to construct hkdf param set, res: %d", res);
652     }
653     return res;
654 }
655 
CheckHkdfParams(const KeyParams * keyParams,const Uint8Buff * salt,const Uint8Buff * outHkdf)656 static int32_t CheckHkdfParams(const KeyParams *keyParams, const Uint8Buff *salt, const Uint8Buff *outHkdf)
657 {
658     int32_t res = CheckKeyParams(keyParams);
659     if (res != HAL_SUCCESS) {
660         return res;
661     }
662     const Uint8Buff *inParams[] = { salt, outHkdf };
663     const char *paramTags[] = { "salt", "outHkdf" };
664     return BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams));
665 }
666 
ComputeHkdf(const KeyParams * keyParams,const Uint8Buff * salt,const Uint8Buff * keyInfo,Uint8Buff * outHkdf)667 static int32_t ComputeHkdf(const KeyParams *keyParams, const Uint8Buff *salt, const Uint8Buff *keyInfo,
668     Uint8Buff *outHkdf)
669 {
670     int32_t res = CheckHkdfParams(keyParams, salt, outHkdf);
671     if (res != HAL_SUCCESS) {
672         return res;
673     }
674 
675     struct HksBlob srcKeyBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
676     struct HksBlob derivedKeyBlob = { outHkdf->length, outHkdf->val };
677 
678     struct HksParamSet *deParamSet = NULL;
679     res = ConstructHkdfParamSet(true, keyParams, salt, keyInfo, &deParamSet);
680     if (res != HAL_SUCCESS) {
681         return res;
682     }
683     struct HksParamSet *ceParamSet = NULL;
684     res = ConstructHkdfParamSet(false, keyParams, salt, keyInfo, &ceParamSet);
685     if (res != HAL_SUCCESS) {
686         FreeParamSet(deParamSet);
687         return res;
688     }
689 
690     LOGI("[HUKS]: HksDeriveKey enter.");
691     if (keyParams->isDeStorage) {
692         res = HksDeriveKey(deParamSet, &srcKeyBlob, &derivedKeyBlob);
693         if (res == HKS_SUCCESS) {
694             MoveDeKeyToCe(keyParams->keyBuff.isAlias, keyParams->osAccountId, &srcKeyBlob);
695         } else {
696             res = HksDeriveKey(ceParamSet, &srcKeyBlob, &derivedKeyBlob);
697         }
698     } else {
699         res = HksDeriveKey(ceParamSet, &srcKeyBlob, &derivedKeyBlob);
700         if (res != HKS_SUCCESS) {
701             res = HksDeriveKey(deParamSet, &srcKeyBlob, &derivedKeyBlob);
702         }
703     }
704     LOGI("[HUKS]: HksDeriveKey quit. [Res]: %d", res);
705     FreeParamSet(deParamSet);
706     FreeParamSet(ceParamSet);
707     if (res != HKS_SUCCESS) {
708         LOGE("[HUKS]: HksDeriveKey fail. [Res]: %d", res);
709         return HAL_FAILED;
710     }
711     return HAL_SUCCESS;
712 }
713 
ConstructPseudonymParamSet(const KeyParams * keyParams,const Uint8Buff * pskKeyAlias,const struct HksBlob * extInfoBlob,uint32_t outLen,struct HksParamSet ** paramSet)714 static int32_t ConstructPseudonymParamSet(const KeyParams *keyParams, const Uint8Buff *pskKeyAlias,
715     const struct HksBlob *extInfoBlob, uint32_t outLen, struct HksParamSet **paramSet)
716 {
717     struct HksBlob saltBlob = { HcStrlen(PSEUDONYM_KEY_FACTOR), (uint8_t *)PSEUDONYM_KEY_FACTOR };
718     struct HksBlob keyInfoBlob = { HcStrlen(PSEUDONYM_KEY_LEBEL), (uint8_t *)PSEUDONYM_KEY_LEBEL };
719     struct HksBlob pskAliasBlob = { pskKeyAlias->length, pskKeyAlias->val };
720     uint32_t len = GetParamLen(keyParams->isDeStorage, BASE_COMPUTE_PSEUDONYM_PSK_PARAMS_LEN);
721     struct HksParam *hkdfParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0);
722     if (hkdfParams == NULL) {
723         LOGE("Malloc for hkdfParams failed.");
724         return HAL_ERR_BAD_ALLOC;
725     }
726     uint32_t idx = 0;
727     hkdfParams[idx].tag = HKS_TAG_PURPOSE;
728     hkdfParams[idx++].uint32Param = HKS_KEY_PURPOSE_DERIVE;
729     hkdfParams[idx].tag = HKS_TAG_ALGORITHM;
730     hkdfParams[idx++].uint32Param = HKS_ALG_HKDF;
731     hkdfParams[idx].tag = HKS_TAG_DIGEST;
732     hkdfParams[idx++].uint32Param = HKS_DIGEST_SHA256;
733     hkdfParams[idx].tag = HKS_TAG_SALT;
734     hkdfParams[idx++].blob = saltBlob;
735     hkdfParams[idx].tag = HKS_TAG_INFO;
736     hkdfParams[idx++].blob = keyInfoBlob;
737     hkdfParams[idx].tag = HKS_TAG_IS_KEY_ALIAS;
738     hkdfParams[idx++].boolParam = true;
739     hkdfParams[idx].tag = HKS_TAG_KEY_STORAGE_FLAG;
740     hkdfParams[idx++].uint32Param = HKS_STORAGE_ONLY_USED_IN_HUKS;
741     hkdfParams[idx].tag = HKS_TAG_DERIVE_AGREE_KEY_STORAGE_FLAG;
742     hkdfParams[idx++].uint32Param = HKS_STORAGE_ONLY_USED_IN_HUKS;
743     hkdfParams[idx].tag = HKS_TAG_KEY_SIZE;
744     hkdfParams[idx++].uint32Param = outLen * BITS_PER_BYTE;
745     hkdfParams[idx].tag = HKS_TAG_KEY_ALIAS;
746     hkdfParams[idx++].blob = pskAliasBlob;
747     hkdfParams[idx].tag = HKS_TAG_EXT_INFO;
748     hkdfParams[idx++].blob = *extInfoBlob;
749     AddStorageExtParams(hkdfParams, keyParams->isDeStorage, &idx, keyParams->osAccountId);
750     int32_t res = ConstructParamSet(paramSet, hkdfParams, idx);
751     HcFree(hkdfParams);
752     return res;
753 }
754 
CheckPskParams(const KeyParams * keyParams,const Uint8Buff * pskKeyAlias,const Uint8Buff * outPsk)755 static int32_t CheckPskParams(const KeyParams *keyParams, const Uint8Buff *pskKeyAlias, const Uint8Buff *outPsk)
756 {
757     int32_t res = CheckKeyParams(keyParams);
758     if (res != HAL_SUCCESS) {
759         return res;
760     }
761     const Uint8Buff *inParams[] = { pskKeyAlias, outPsk };
762     const char *paramTags[] = { "pskKeyAlias", "outPsk" };
763     return BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams));
764 }
765 
ComputePseudonymPskInner(const KeyParams * keyParams,const Uint8Buff * pskKeyAlias,const Uint8Buff * extInfo,Uint8Buff * outPsk)766 static int32_t ComputePseudonymPskInner(const KeyParams *keyParams, const Uint8Buff *pskKeyAlias,
767     const Uint8Buff *extInfo, Uint8Buff *outPsk)
768 {
769     struct HksBlob srcKeyBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
770     struct HksBlob derivedKeyBlob = { outPsk->length, outPsk->val };
771     struct HksBlob extInfoBlob = { 0, NULL };
772     if (extInfo != NULL) {
773         extInfoBlob.data = extInfo->val;
774         extInfoBlob.size = extInfo->length;
775     }
776     struct HksParamSet *paramSet = NULL;
777     int32_t res = ConstructPseudonymParamSet(keyParams, pskKeyAlias, &extInfoBlob, outPsk->length, &paramSet);
778     if (res != HAL_SUCCESS) {
779         LOGE("Construct param set failed!");
780         return res;
781     }
782 
783     LOGI("[HUKS]: HksDeriveKey enter.");
784     res = HksDeriveKey(paramSet, &srcKeyBlob, &derivedKeyBlob);
785     FreeParamSet(paramSet);
786     LOGI("[HUKS]: HksDeriveKey quit. [Res]: %d", res);
787     if (res != HKS_SUCCESS) {
788         LOGE("[HUKS]: HksDeriveKey fail. [Res]: %d", res);
789         return HAL_FAILED;
790     }
791     return HAL_SUCCESS;
792 }
793 
794 // pseudonym psk alias:sha256(serviceType bytes+peerAuthId bytes+{0x00, 0x07})
ComputePseudonymPsk(const KeyParams * keyParams,const Uint8Buff * pskKeyAlias,const Uint8Buff * extInfo,Uint8Buff * outPsk)795 static int32_t ComputePseudonymPsk(const KeyParams *keyParams, const Uint8Buff *pskKeyAlias,
796     const Uint8Buff *extInfo, Uint8Buff *outPsk)
797 {
798     int32_t res = CheckPskParams(keyParams, pskKeyAlias, outPsk);
799     if (res != HAL_SUCCESS) {
800         return res;
801     }
802 
803     res = ComputePseudonymPskInner(keyParams, pskKeyAlias, extInfo, outPsk);
804     if (!keyParams->isDeStorage) {
805         return res;
806     }
807     if (res == HAL_SUCCESS) {
808         struct HksBlob keyAliasBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
809         MoveDeKeyToCe(keyParams->keyBuff.isAlias, keyParams->osAccountId, &keyAliasBlob);
810     } else {
811         KeyParams ceParams = {
812             .keyBuff = { keyParams->keyBuff.key, keyParams->keyBuff.keyLen, keyParams->keyBuff.isAlias },
813             .isDeStorage = false,
814             .osAccountId = keyParams->osAccountId
815         };
816         res = ComputePseudonymPskInner(&ceParams, pskKeyAlias, extInfo, outPsk);
817     }
818     return res;
819 }
820 
ConstructOutParamSet(struct HksParamSet ** outParamSet)821 static int32_t ConstructOutParamSet(struct HksParamSet **outParamSet)
822 {
823     int32_t res = HksInitParamSet(outParamSet);
824     if (res != HKS_SUCCESS) {
825         LOGE("init out param set failed, res = %d", res);
826         return HAL_ERR_INIT_PARAM_SET_FAILED;
827     }
828 
829     uint32_t outParamSetSize = 2048;
830     uint8_t *blobVal = (uint8_t *)HcMalloc(outParamSetSize, 0);
831     if (blobVal == NULL) {
832         LOGE("Failed to alloc memory for out blob value!");
833         HksFreeParamSet(outParamSet);
834         return HAL_ERR_BAD_ALLOC;
835     }
836     struct HksParam getParam = {
837         .tag = HKS_TAG_SYMMETRIC_KEY_DATA,
838         .blob = { .size = outParamSetSize, .data = blobVal }
839     };
840 
841     res = HksAddParams(*outParamSet, &getParam, 1);
842     if (res != HKS_SUCCESS) {
843         LOGE("Failed to add param!");
844         HksFreeParamSet(outParamSet);
845         HcFree(blobVal);
846         return HAL_ERR_ADD_PARAM_FAILED;
847     }
848 
849     res = HksBuildParamSet(outParamSet);
850     HcFree(blobVal);
851     if (res != HKS_SUCCESS) {
852         LOGE("build param set failed, res = %d", res);
853         HksFreeParamSet(outParamSet);
854         return HAL_ERR_BUILD_PARAM_SET_FAILED;
855     }
856     return HAL_SUCCESS;
857 }
858 
GetExtInfoByParamSet(const struct HksParamSet * outParamSet,Uint8Buff * outExtInfo)859 static int32_t GetExtInfoByParamSet(const struct HksParamSet *outParamSet, Uint8Buff *outExtInfo)
860 {
861     struct HksParam *extInfoParam = NULL;
862     int32_t res = HksGetParam(outParamSet, HKS_TAG_EXT_INFO, &extInfoParam);
863     if (res != HKS_SUCCESS) {
864         LOGE("Failed to get extInfoParam!");
865         return HAL_FAILED;
866     }
867     if (extInfoParam->blob.data == NULL || extInfoParam->blob.size == 0) {
868         LOGE("Extra info blob is null!");
869         return HAL_FAILED;
870     }
871     uint8_t *tmpExtInfoVal = (uint8_t *)HcMalloc(extInfoParam->blob.size, 0);
872     if (tmpExtInfoVal == NULL) {
873         LOGE("Failed to alloc memory for extInfo value!");
874         return HAL_ERR_BAD_ALLOC;
875     }
876     if (memcpy_s(tmpExtInfoVal, extInfoParam->blob.size, extInfoParam->blob.data, extInfoParam->blob.size) != EOK) {
877         LOGE("Failed to copy extInfo!");
878         HcFree(tmpExtInfoVal);
879         return HAL_ERR_MEMORY_COPY;
880     }
881     outExtInfo->val = tmpExtInfoVal;
882     outExtInfo->length = extInfoParam->blob.size;
883     return HAL_SUCCESS;
884 }
885 
ConstructGetKeyExtInfoParamSet(const KeyParams * keyParams,struct HksParamSet ** paramSet)886 static int32_t ConstructGetKeyExtInfoParamSet(const KeyParams *keyParams, struct HksParamSet **paramSet)
887 {
888     uint32_t len = GetParamLen(keyParams->isDeStorage, 0);
889     if (len == 0) {
890         return HAL_SUCCESS;
891     }
892     struct HksParam *getParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0);
893     if (getParams == NULL) {
894         LOGE("Malloc for getParams failed.");
895         return HAL_ERR_BAD_ALLOC;
896     }
897     uint32_t idx = 0;
898     AddStorageExtParams(getParams, keyParams->isDeStorage, &idx, keyParams->osAccountId);
899     int32_t res = ConstructParamSet(paramSet, getParams, idx);
900     HcFree(getParams);
901     if (res != HAL_SUCCESS) {
902         LOGE("Failed to construct get param set, res: %d", res);
903     }
904     return res;
905 }
906 
GetKeyExtInfoInner(const KeyParams * keyParams,Uint8Buff * outExtInfo)907 static int32_t GetKeyExtInfoInner(const KeyParams *keyParams, Uint8Buff *outExtInfo)
908 {
909     struct HksParamSet *paramSet = NULL;
910     int32_t res = ConstructGetKeyExtInfoParamSet(keyParams, &paramSet);
911     if (res != HAL_SUCCESS) {
912         return res;
913     }
914     struct HksParamSet *outParamSet = NULL;
915     res = ConstructOutParamSet(&outParamSet);
916     if (res != HAL_SUCCESS) {
917         FreeParamSet(paramSet);
918         return res;
919     }
920     struct HksBlob keyAliasBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
921     res = HksGetKeyParamSet(&keyAliasBlob, paramSet, outParamSet);
922     FreeParamSet(paramSet);
923     if (res != HKS_SUCCESS) {
924         LOGE("Failed to get key param set!");
925         FreeParamSet(outParamSet);
926         return HAL_FAILED;
927     }
928     res = GetExtInfoByParamSet(outParamSet, outExtInfo);
929     FreeParamSet(outParamSet);
930     return res;
931 }
932 
GetKeyExtInfo(const KeyParams * keyParams,Uint8Buff * outExtInfo)933 static int32_t GetKeyExtInfo(const KeyParams *keyParams, Uint8Buff *outExtInfo)
934 {
935     int32_t res = CheckKeyParams(keyParams);
936     if (res != HAL_SUCCESS) {
937         return res;
938     }
939     if (outExtInfo == NULL) {
940         LOGE("outExtInfo is null!");
941         return HAL_ERR_NULL_PTR;
942     }
943 
944     res = GetKeyExtInfoInner(keyParams, outExtInfo);
945     if (!keyParams->isDeStorage) {
946         return res;
947     }
948     if (res == HAL_SUCCESS) {
949         struct HksBlob keyAliasBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
950         MoveDeKeyToCe(keyParams->keyBuff.isAlias, keyParams->osAccountId, &keyAliasBlob);
951     } else {
952         KeyParams ceParams = {
953             .keyBuff = { keyParams->keyBuff.key, keyParams->keyBuff.keyLen, keyParams->keyBuff.isAlias },
954             .isDeStorage = false,
955             .osAccountId = keyParams->osAccountId
956         };
957         res = GetKeyExtInfoInner(&ceParams, outExtInfo);
958     }
959     return res;
960 }
961 
CheckAesGcmEncryptParam(const KeyParams * keyParams,const Uint8Buff * plain,const GcmParam * encryptInfo,Uint8Buff * outCipher)962 static int32_t CheckAesGcmEncryptParam(const KeyParams *keyParams, const Uint8Buff *plain,
963     const GcmParam *encryptInfo, Uint8Buff *outCipher)
964 {
965     int32_t res = CheckKeyParams(keyParams);
966     if (res != HAL_SUCCESS) {
967         return res;
968     }
969     const Uint8Buff *inParams[] = { plain, outCipher };
970     const char* paramTags[] = { "plain", "outCipher" };
971     res = BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams));
972     if (res != HAL_SUCCESS) {
973         return res;
974     }
975 
976     CHECK_PTR_RETURN_HAL_ERROR_CODE(encryptInfo, "encryptInfo");
977     CHECK_PTR_RETURN_HAL_ERROR_CODE(encryptInfo->aad, "aad");
978     CHECK_LEN_ZERO_RETURN_ERROR_CODE(encryptInfo->aadLen, "aadLen");
979     CHECK_PTR_RETURN_HAL_ERROR_CODE(encryptInfo->nonce, "nonce");
980     CHECK_LEN_LOWER_RETURN(encryptInfo->nonceLen, HKS_AE_NONCE_LEN, "nonceLen");
981     CHECK_LEN_LOWER_RETURN(outCipher->length, plain->length + HKS_AE_TAG_LEN, "outCipher");
982 
983     return HAL_SUCCESS;
984 }
985 
ConstructAesGcmEncryptParamSet(const GcmParam * encryptInfo,const KeyParams * keyParams,struct HksParamSet ** paramSet)986 static int32_t ConstructAesGcmEncryptParamSet(const GcmParam *encryptInfo, const KeyParams *keyParams,
987     struct HksParamSet **paramSet)
988 {
989     struct HksBlob nonceBlob = { encryptInfo->nonceLen, encryptInfo->nonce };
990     struct HksBlob aadBlob = { encryptInfo->aadLen, encryptInfo->aad };
991     uint32_t len = GetParamLen(keyParams->isDeStorage, BASE_ENCRYPT_PARAMS_LEN);
992     struct HksParam *encryptParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0);
993     if (encryptParams == NULL) {
994         LOGE("Malloc for encryptParams failed.");
995         return HAL_ERR_BAD_ALLOC;
996     }
997     uint32_t idx = 0;
998     encryptParams[idx].tag = HKS_TAG_PURPOSE;
999     encryptParams[idx++].uint32Param = HKS_KEY_PURPOSE_ENCRYPT;
1000     encryptParams[idx].tag = HKS_TAG_ALGORITHM;
1001     encryptParams[idx++].uint32Param = HKS_ALG_AES;
1002     encryptParams[idx].tag = HKS_TAG_BLOCK_MODE;
1003     encryptParams[idx++].uint32Param = HKS_MODE_GCM;
1004     encryptParams[idx].tag = HKS_TAG_PADDING;
1005     encryptParams[idx++].uint32Param = HKS_PADDING_NONE;
1006     encryptParams[idx].tag = HKS_TAG_NONCE;
1007     encryptParams[idx++].blob = nonceBlob;
1008     encryptParams[idx].tag = HKS_TAG_ASSOCIATED_DATA;
1009     encryptParams[idx++].blob = aadBlob;
1010     encryptParams[idx].tag = HKS_TAG_IS_KEY_ALIAS;
1011     encryptParams[idx++].boolParam = keyParams->keyBuff.isAlias;
1012     AddStorageExtParams(encryptParams, keyParams->isDeStorage, &idx, keyParams->osAccountId);
1013     int32_t res = ConstructParamSet(paramSet, encryptParams, idx);
1014     HcFree(encryptParams);
1015     if (res != HAL_SUCCESS) {
1016         LOGE("Failed to construct encrypt param set, res: %d", res);
1017     }
1018     return res;
1019 }
1020 
AesGcmEncrypt(const KeyParams * keyParams,const Uint8Buff * plain,const GcmParam * encryptInfo,Uint8Buff * outCipher)1021 static int32_t AesGcmEncrypt(const KeyParams *keyParams, const Uint8Buff *plain, const GcmParam *encryptInfo,
1022     Uint8Buff *outCipher)
1023 {
1024     int32_t res = CheckAesGcmEncryptParam(keyParams, plain, encryptInfo, outCipher);
1025     if (res != HAL_SUCCESS) {
1026         return res;
1027     }
1028 
1029     struct HksBlob keyBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
1030     struct HksBlob plainBlob = { plain->length, plain->val };
1031     struct HksBlob cipherBlob = { outCipher->length, outCipher->val };
1032 
1033     struct HksParamSet *paramSet = NULL;
1034     res = ConstructAesGcmEncryptParamSet(encryptInfo, keyParams, &paramSet);
1035     if (res != HAL_SUCCESS) {
1036         return res;
1037     }
1038 
1039     LOGI("[HUKS]: HksEncrypt enter.");
1040     res = HksEncrypt(&keyBlob, paramSet, &plainBlob, &cipherBlob);
1041     FreeParamSet(paramSet);
1042     LOGI("[HUKS]: HksEncrypt quit. [Res]: %d", res);
1043     if (res != HKS_SUCCESS) {
1044         LOGE("[HUKS]: HksEncrypt fail. [Res]: %d", res);
1045         return HAL_FAILED;
1046     }
1047     return HAL_SUCCESS;
1048 }
1049 
CheckAesGcmDecryptParam(const KeyParams * keyParams,const Uint8Buff * cipher,const GcmParam * decryptInfo,Uint8Buff * outPlain)1050 static int32_t CheckAesGcmDecryptParam(const KeyParams *keyParams, const Uint8Buff *cipher,
1051     const GcmParam *decryptInfo, Uint8Buff *outPlain)
1052 {
1053     int32_t res = CheckKeyParams(keyParams);
1054     if (res != HAL_SUCCESS) {
1055         return res;
1056     }
1057     const Uint8Buff *inParams[] = { cipher, outPlain };
1058     const char *paramTags[] = { "cipher", "outPlain" };
1059     res = BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams));
1060     if (res != HAL_SUCCESS) {
1061         return res;
1062     }
1063 
1064     CHECK_PTR_RETURN_HAL_ERROR_CODE(decryptInfo, "decryptInfo");
1065     CHECK_PTR_RETURN_HAL_ERROR_CODE(decryptInfo->aad, "aad");
1066     CHECK_LEN_ZERO_RETURN_ERROR_CODE(decryptInfo->aadLen, "aadLen");
1067     CHECK_PTR_RETURN_HAL_ERROR_CODE(decryptInfo->nonce, "nonce");
1068     CHECK_LEN_LOWER_RETURN(decryptInfo->nonceLen, HKS_AE_NONCE_LEN, "nonceLen");
1069     CHECK_LEN_LOWER_RETURN(outPlain->length, cipher->length - HKS_AE_TAG_LEN, "outPlain");
1070 
1071     return HAL_SUCCESS;
1072 }
1073 
ConstructAesGcmDecryptParamSet(const GcmParam * decryptInfo,const KeyParams * keyParams,struct HksParamSet ** paramSet)1074 static int32_t ConstructAesGcmDecryptParamSet(const GcmParam *decryptInfo, const KeyParams *keyParams,
1075     struct HksParamSet **paramSet)
1076 {
1077     struct HksBlob nonceBlob = { decryptInfo->nonceLen, decryptInfo->nonce };
1078     struct HksBlob aadBlob = { decryptInfo->aadLen, decryptInfo->aad };
1079     uint32_t len = GetParamLen(keyParams->isDeStorage, BASE_DECRYPT_PARAMS_LEN);
1080     struct HksParam *decryptParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0);
1081     if (decryptParams == NULL) {
1082         LOGE("Malloc for decryptParams failed.");
1083         return HAL_ERR_BAD_ALLOC;
1084     }
1085     uint32_t idx = 0;
1086     decryptParams[idx].tag = HKS_TAG_PURPOSE;
1087     decryptParams[idx++].uint32Param = HKS_KEY_PURPOSE_DECRYPT;
1088     decryptParams[idx].tag = HKS_TAG_ALGORITHM;
1089     decryptParams[idx++].uint32Param = HKS_ALG_AES;
1090     decryptParams[idx].tag = HKS_TAG_BLOCK_MODE;
1091     decryptParams[idx++].uint32Param = HKS_MODE_GCM;
1092     decryptParams[idx].tag = HKS_TAG_PADDING;
1093     decryptParams[idx++].uint32Param = HKS_PADDING_NONE;
1094     decryptParams[idx].tag = HKS_TAG_NONCE;
1095     decryptParams[idx++].blob = nonceBlob;
1096     decryptParams[idx].tag = HKS_TAG_ASSOCIATED_DATA;
1097     decryptParams[idx++].blob = aadBlob;
1098     decryptParams[idx].tag = HKS_TAG_IS_KEY_ALIAS;
1099     decryptParams[idx++].boolParam = keyParams->keyBuff.isAlias;
1100     AddStorageExtParams(decryptParams, keyParams->isDeStorage, &idx, keyParams->osAccountId);
1101     int32_t res = ConstructParamSet(paramSet, decryptParams, idx);
1102     HcFree(decryptParams);
1103     if (res != HAL_SUCCESS) {
1104         LOGE("Failed to construct decrypt param set, res: %d", res);
1105     }
1106     return res;
1107 }
1108 
AesGcmDecrypt(const KeyParams * keyParams,const Uint8Buff * cipher,const GcmParam * decryptInfo,Uint8Buff * outPlain)1109 static int32_t AesGcmDecrypt(const KeyParams *keyParams, const Uint8Buff *cipher, const GcmParam *decryptInfo,
1110     Uint8Buff *outPlain)
1111 {
1112     int32_t res = CheckAesGcmDecryptParam(keyParams, cipher, decryptInfo, outPlain);
1113     if (res != HAL_SUCCESS) {
1114         return res;
1115     }
1116 
1117     struct HksBlob keyBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
1118     struct HksBlob cipherBlob = { cipher->length, cipher->val };
1119     struct HksBlob plainBlob = { outPlain->length, outPlain->val };
1120 
1121     struct HksParamSet *paramSet = NULL;
1122     res = ConstructAesGcmDecryptParamSet(decryptInfo, keyParams, &paramSet);
1123     if (res != HAL_SUCCESS) {
1124         return res;
1125     }
1126 
1127     LOGI("[HUKS]: HksDecrypt enter.");
1128     res = HksDecrypt(&keyBlob, paramSet, &cipherBlob, &plainBlob);
1129     FreeParamSet(paramSet);
1130     LOGI("[HUKS]: HksDecrypt quit. [Res]: %d", res);
1131     if (res != HKS_SUCCESS) {
1132         LOGE("[HUKS]: HksDecrypt fail. [Res]: %d", res);
1133         return HAL_FAILED;
1134     }
1135     return HAL_SUCCESS;
1136 }
1137 
HashToPoint(const Uint8Buff * hash,Algorithm algo,Uint8Buff * outEcPoint)1138 static int32_t HashToPoint(const Uint8Buff *hash, Algorithm algo, Uint8Buff *outEcPoint)
1139 {
1140     CHECK_PTR_RETURN_HAL_ERROR_CODE(hash, "hash");
1141     CHECK_PTR_RETURN_HAL_ERROR_CODE(hash->val, "hash->val");
1142     CHECK_LEN_EQUAL_RETURN(hash->length, SHA256_LEN, "hash->length");
1143     CHECK_PTR_RETURN_HAL_ERROR_CODE(outEcPoint, "outEcPoint");
1144     CHECK_PTR_RETURN_HAL_ERROR_CODE(outEcPoint->val, "outEcPoint->val");
1145 
1146     if (algo != X25519 && algo != P256) {
1147         LOGE("Compute algo: %d.", algo);
1148         return HAL_ERR_INVALID_PARAM;
1149     }
1150     if (algo == P256) {
1151         LOGI("Compute HashToPoint for P256");
1152         return MbedtlsHashToPoint(hash, outEcPoint);
1153     }
1154 
1155     CHECK_LEN_EQUAL_RETURN(outEcPoint->length, SHA256_LEN, "outEcPoint->length");
1156     return HashToPointX25519(hash, outEcPoint);
1157 }
1158 
ConstructInitParamsP256(struct HksParamSet ** initParamSet,const KeyParams * keyParams)1159 static int32_t ConstructInitParamsP256(struct HksParamSet **initParamSet, const KeyParams *keyParams)
1160 {
1161     uint32_t len = GetParamLen(keyParams->isDeStorage, BASE_AGREE_INIT_PARAMS_LEN);
1162     struct HksParam *initParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0);
1163     if (initParams == NULL) {
1164         LOGE("Malloc for initParams failed.");
1165         return HAL_ERR_BAD_ALLOC;
1166     }
1167     uint32_t idx = 0;
1168     initParams[idx].tag = HKS_TAG_ALGORITHM;
1169     initParams[idx++].uint32Param = HKS_ALG_ECDH;
1170     initParams[idx].tag = HKS_TAG_PURPOSE;
1171     initParams[idx++].uint32Param = HKS_KEY_PURPOSE_AGREE;
1172     initParams[idx].tag = HKS_TAG_KEY_SIZE;
1173     initParams[idx++].uint32Param = HKS_ECC_KEY_SIZE_256;
1174     AddStorageExtParams(initParams, keyParams->isDeStorage, &idx, keyParams->osAccountId);
1175     int32_t res = ConstructParamSet(initParamSet, initParams, idx);
1176     HcFree(initParams);
1177     if (res != HAL_SUCCESS) {
1178         LOGE("Construct init param set failed, res = %d", res);
1179     }
1180     return res;
1181 }
1182 
ConstructFinishParamsP256(struct HksParamSet ** finishParamSet,const KeyParams * keyParams,const struct HksBlob * sharedKeyAliasBlob)1183 static int32_t ConstructFinishParamsP256(struct HksParamSet **finishParamSet, const KeyParams *keyParams,
1184     const struct HksBlob *sharedKeyAliasBlob)
1185 {
1186     uint32_t len = GetParamLen(keyParams->isDeStorage, BASE_AGREE_FINISH_PARAMS_LEN);
1187     struct HksParam *finishParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0);
1188     if (finishParams == NULL) {
1189         LOGE("Malloc for finishParams failed.");
1190         return HAL_ERR_BAD_ALLOC;
1191     }
1192     uint32_t idx = 0;
1193     finishParams[idx].tag = HKS_TAG_KEY_STORAGE_FLAG;
1194     finishParams[idx++].uint32Param = HKS_STORAGE_PERSISTENT;
1195     finishParams[idx].tag = HKS_TAG_IS_KEY_ALIAS;
1196     finishParams[idx++].boolParam = true;
1197     finishParams[idx].tag = HKS_TAG_ALGORITHM;
1198     finishParams[idx++].uint32Param = HKS_ALG_AES;
1199     finishParams[idx].tag = HKS_TAG_KEY_SIZE;
1200     finishParams[idx++].uint32Param = HKS_AES_KEY_SIZE_256;
1201     finishParams[idx].tag = HKS_TAG_PURPOSE;
1202     finishParams[idx++].uint32Param = HKS_KEY_PURPOSE_DERIVE;
1203     finishParams[idx].tag = HKS_TAG_DIGEST;
1204     finishParams[idx++].uint32Param = HKS_DIGEST_SHA256;
1205     finishParams[idx].tag = HKS_TAG_KEY_ALIAS;
1206     finishParams[idx++].blob = *sharedKeyAliasBlob;
1207     AddStorageExtParams(finishParams, keyParams->isDeStorage, &idx, keyParams->osAccountId);
1208     int32_t res = ConstructParamSet(finishParamSet, finishParams, idx);
1209     HcFree(finishParams);
1210     if (res != HAL_SUCCESS) {
1211         LOGE("Construct finish param set failed, res = %d", res);
1212     }
1213     return res;
1214 }
1215 
AgreeSharedSecretWithStorageP256(const KeyParams * priKeyParams,const KeyBuff * pubKeyBuff,const struct HksBlob * sharedKeyAliasBlob)1216 static int32_t AgreeSharedSecretWithStorageP256(const KeyParams *priKeyParams, const KeyBuff *pubKeyBuff,
1217     const struct HksBlob *sharedKeyAliasBlob)
1218 {
1219     struct HksParamSet *initParamSet = NULL;
1220     struct HksParamSet *finishParamSet = NULL;
1221     int32_t res = ConstructInitParamsP256(&initParamSet, priKeyParams);
1222     if (res != HAL_SUCCESS) {
1223         return res;
1224     }
1225     res = ConstructFinishParamsP256(&finishParamSet, priKeyParams, sharedKeyAliasBlob);
1226     if (res != HAL_SUCCESS) {
1227         FreeParamSet(initParamSet);
1228         return res;
1229     }
1230     struct HksBlob priKeyAliasBlob = { priKeyParams->keyBuff.keyLen, priKeyParams->keyBuff.key };
1231     struct HksBlob pubKeyBlob = { pubKeyBuff->keyLen, pubKeyBuff->key };
1232     uint8_t handle[sizeof(uint64_t)] = { 0 };
1233     struct HksBlob handleBlob = { sizeof(uint64_t), handle };
1234     uint8_t outDataUpdate[ECDH_COMMON_SIZE_P256] = { 0 };
1235     struct HksBlob outDataUpdateBlob = { ECDH_COMMON_SIZE_P256, outDataUpdate };
1236     uint8_t outDataFinish[ECDH_COMMON_SIZE_P256] = { 0 };
1237     struct HksBlob outDataFinishBlob = { ECDH_COMMON_SIZE_P256, outDataFinish };
1238     do {
1239         res = HksInit(&priKeyAliasBlob, initParamSet, &handleBlob, NULL);
1240         if (res != HKS_SUCCESS) {
1241             LOGE("Huks agree P256 key: HksInit failed, res = %d", res);
1242             res = HAL_ERR_HUKS;
1243             break;
1244         }
1245         res = HksUpdate(&handleBlob, initParamSet, &pubKeyBlob, &outDataUpdateBlob);
1246         if (res != HKS_SUCCESS) {
1247             LOGE("Huks agree P256 key: HksUpdate failed, res = %d", res);
1248             res = HAL_ERR_HUKS;
1249             break;
1250         }
1251         LOGI("[HUKS]: HksFinish enter.");
1252         res = HksFinish(&handleBlob, finishParamSet, &pubKeyBlob, &outDataFinishBlob);
1253         LOGI("[HUKS]: HksFinish quit. [Res]: %d", res);
1254         if (res != HKS_SUCCESS) {
1255             LOGE("[HUKS]: HksFinish fail. [Res]: %d", res);
1256             res = HAL_ERR_HUKS;
1257             break;
1258         }
1259     } while (0);
1260     FreeParamSet(initParamSet);
1261     FreeParamSet(finishParamSet);
1262     return res;
1263 }
1264 
ConstructAgreeWithStorageParams(struct HksParamSet ** paramSet,uint32_t keyLen,Algorithm algo,const KeyParams * priKeyParams,const KeyBuff * pubKeyBuff)1265 static int32_t ConstructAgreeWithStorageParams(struct HksParamSet **paramSet, uint32_t keyLen, Algorithm algo,
1266     const KeyParams *priKeyParams, const KeyBuff *pubKeyBuff)
1267 {
1268     struct HksBlob priKeyBlob = { priKeyParams->keyBuff.keyLen, priKeyParams->keyBuff.key };
1269     struct HksBlob pubKeyBlob = { pubKeyBuff->keyLen, pubKeyBuff->key };
1270     uint32_t len = GetParamLen(priKeyParams->isDeStorage, BASE_AGREE_WITH_STORAGE_PARAMS_LEN);
1271     struct HksParam *agreeParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0);
1272     if (agreeParams == NULL) {
1273         LOGE("Malloc for agreeParams failed.");
1274         return HAL_ERR_BAD_ALLOC;
1275     }
1276     uint32_t idx = 0;
1277     agreeParams[idx].tag = HKS_TAG_ALGORITHM;
1278     agreeParams[idx++].uint32Param = HKS_ALG_AES;
1279     agreeParams[idx].tag = HKS_TAG_KEY_SIZE;
1280     agreeParams[idx++].uint32Param = keyLen * BITS_PER_BYTE;
1281     agreeParams[idx].tag = HKS_TAG_PURPOSE;
1282     agreeParams[idx++].uint32Param = HKS_KEY_PURPOSE_DERIVE;
1283     agreeParams[idx].tag = HKS_TAG_DIGEST;
1284     agreeParams[idx++].uint32Param = HKS_DIGEST_SHA256;
1285     agreeParams[idx].tag = HKS_TAG_KEY_GENERATE_TYPE;
1286     agreeParams[idx++].uint32Param = HKS_KEY_GENERATE_TYPE_AGREE;
1287     agreeParams[idx].tag = HKS_TAG_AGREE_ALG;
1288     agreeParams[idx++].uint32Param = g_algToHksAlgorithm[algo]; // only support HKS_ALG_ED25519 and HKS_ALG_X25519
1289     agreeParams[idx].tag = HKS_TAG_AGREE_PRIVATE_KEY_ALIAS;
1290     agreeParams[idx++].blob = priKeyBlob;
1291     agreeParams[idx].tag = HKS_TAG_AGREE_PUBLIC_KEY;
1292     agreeParams[idx++].blob = pubKeyBlob;
1293     agreeParams[idx].tag = HKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS;
1294     agreeParams[idx++].boolParam = pubKeyBuff->isAlias;
1295     AddStorageExtParams(agreeParams, priKeyParams->isDeStorage, &idx, priKeyParams->osAccountId);
1296     int32_t res = ConstructParamSet(paramSet, agreeParams, idx);
1297     HcFree(agreeParams);
1298     if (res != HAL_SUCCESS) {
1299         LOGE("Construct agree param set failed, res = %d", res);
1300     }
1301     return res;
1302 }
1303 
CheckAgreeWithStorageParams(const KeyParams * priKeyParams,const KeyBuff * pubKeyBuff,uint32_t sharedKeyLen,const Uint8Buff * sharedKeyAlias)1304 static int32_t CheckAgreeWithStorageParams(const KeyParams *priKeyParams, const KeyBuff *pubKeyBuff,
1305     uint32_t sharedKeyLen, const Uint8Buff *sharedKeyAlias)
1306 {
1307     int32_t res = CheckKeyParams(priKeyParams);
1308     if (res != HAL_SUCCESS) {
1309         return res;
1310     }
1311     CHECK_PTR_RETURN_HAL_ERROR_CODE(pubKeyBuff, "pubKeyBuff");
1312     CHECK_PTR_RETURN_HAL_ERROR_CODE(pubKeyBuff->key, "pubKeyBuff->key");
1313     CHECK_LEN_ZERO_RETURN_ERROR_CODE(pubKeyBuff->keyLen, "pubKeyBuff->keyLen");
1314     CHECK_PTR_RETURN_HAL_ERROR_CODE(sharedKeyAlias, "sharedKeyAlias");
1315     CHECK_PTR_RETURN_HAL_ERROR_CODE(sharedKeyAlias->val, "sharedKeyAlias->val");
1316     CHECK_LEN_ZERO_RETURN_ERROR_CODE(sharedKeyAlias->length, "sharedKeyAlias->length");
1317     CHECK_LEN_ZERO_RETURN_ERROR_CODE(sharedKeyLen, "sharedKeyLen");
1318     return HAL_SUCCESS;
1319 }
1320 
MoveSharedKeyToCe(const KeyParams * priKeyParams,const struct HksBlob * sharedKeyAlias)1321 static void MoveSharedKeyToCe(const KeyParams *priKeyParams, const struct HksBlob *sharedKeyAlias)
1322 {
1323     struct HksBlob priKeyBlob = { priKeyParams->keyBuff.keyLen, priKeyParams->keyBuff.key };
1324     MoveDeKeyToCe(priKeyParams->keyBuff.isAlias, priKeyParams->osAccountId, &priKeyBlob);
1325     MoveDeKeyToCe(true, priKeyParams->osAccountId, sharedKeyAlias);
1326 }
1327 
AgreeSharedSecretWithStorage(const KeyParams * priKeyParams,const KeyBuff * pubKeyBuff,Algorithm algo,uint32_t sharedKeyLen,const Uint8Buff * sharedKeyAlias)1328 static int32_t AgreeSharedSecretWithStorage(const KeyParams *priKeyParams, const KeyBuff *pubKeyBuff,
1329     Algorithm algo, uint32_t sharedKeyLen, const Uint8Buff *sharedKeyAlias)
1330 {
1331     int32_t res = CheckAgreeWithStorageParams(priKeyParams, pubKeyBuff, sharedKeyLen, sharedKeyAlias);
1332     if (res != HAL_SUCCESS) {
1333         return res;
1334     }
1335 
1336     struct HksBlob sharedKeyAliasBlob = { sharedKeyAlias->length, sharedKeyAlias->val };
1337     if (g_algToHksAlgorithm[algo] == HKS_ALG_ECC) {
1338         LOGI("Hks agree key with storage for P256.");
1339         return AgreeSharedSecretWithStorageP256(priKeyParams, pubKeyBuff, &sharedKeyAliasBlob);
1340     }
1341     struct HksParamSet *deParamSet = NULL;
1342     KeyParams keyParams = {
1343         .keyBuff = { priKeyParams->keyBuff.key, priKeyParams->keyBuff.keyLen, priKeyParams->keyBuff.isAlias },
1344         .isDeStorage = true,
1345         .osAccountId = priKeyParams->osAccountId
1346     };
1347     res = ConstructAgreeWithStorageParams(&deParamSet, sharedKeyLen, algo, &keyParams, pubKeyBuff);
1348     if (res != HAL_SUCCESS) {
1349         return res;
1350     }
1351     struct HksParamSet *ceParamSet = NULL;
1352     keyParams.isDeStorage = false;
1353     res = ConstructAgreeWithStorageParams(&ceParamSet, sharedKeyLen, algo, &keyParams, pubKeyBuff);
1354     if (res != HAL_SUCCESS) {
1355         FreeParamSet(deParamSet);
1356         return res;
1357     }
1358 
1359     LOGI("[HUKS]: HksGenerateKey enter.");
1360     if (priKeyParams->isDeStorage) {
1361         res = HksGenerateKey(&sharedKeyAliasBlob, deParamSet, NULL);
1362         if (res == HKS_SUCCESS) {
1363             MoveSharedKeyToCe(priKeyParams, &sharedKeyAliasBlob);
1364         } else {
1365             res = HksGenerateKey(&sharedKeyAliasBlob, ceParamSet, NULL);
1366         }
1367     } else {
1368         res = HksGenerateKey(&sharedKeyAliasBlob, ceParamSet, NULL);
1369         if (res != HKS_SUCCESS) {
1370             res = HksGenerateKey(&sharedKeyAliasBlob, deParamSet, NULL);
1371         }
1372     }
1373     LOGI("[HUKS]: HksGenerateKey quit. [Res]: %d", res);
1374     FreeParamSet(deParamSet);
1375     FreeParamSet(ceParamSet);
1376     if (res != HKS_SUCCESS) {
1377         LOGE("[HUKS]: HksGenerateKey fail. [Res]: %d", res);
1378         return HAL_FAILED;
1379     }
1380     return HAL_SUCCESS;
1381 }
1382 
CheckAgreeParams(const KeyParams * priKeyParams,const KeyBuff * pubKey,const Uint8Buff * sharedKey)1383 static int32_t CheckAgreeParams(const KeyParams *priKeyParams, const KeyBuff *pubKey, const Uint8Buff *sharedKey)
1384 {
1385     int32_t res = CheckKeyParams(priKeyParams);
1386     if (res != HAL_SUCCESS) {
1387         return res;
1388     }
1389     CHECK_PTR_RETURN_HAL_ERROR_CODE(pubKey, "pubKey");
1390     CHECK_PTR_RETURN_HAL_ERROR_CODE(pubKey->key, "pubKey->key");
1391     CHECK_LEN_ZERO_RETURN_ERROR_CODE(pubKey->keyLen, "pubKey->keyLen");
1392     CHECK_PTR_RETURN_HAL_ERROR_CODE(sharedKey, "sharedKey");
1393     CHECK_PTR_RETURN_HAL_ERROR_CODE(sharedKey->val, "sharedKey->val");
1394     CHECK_LEN_ZERO_RETURN_ERROR_CODE(sharedKey->length, "sharedKey->length");
1395     return HAL_SUCCESS;
1396 }
1397 
ConstructAgreeParamSet(const KeyParams * keyParams,Algorithm algo,const Uint8Buff * sharedKey,struct HksParamSet ** paramSet)1398 static int32_t ConstructAgreeParamSet(const KeyParams *keyParams, Algorithm algo, const Uint8Buff *sharedKey,
1399     struct HksParamSet **paramSet)
1400 {
1401     uint32_t len = GetParamLen(keyParams->isDeStorage, BASE_AGREE_PARAMS_LEN);
1402     struct HksParam *agreeParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0);
1403     if (agreeParams == NULL) {
1404         LOGE("Malloc for agreeParams failed.");
1405         return HAL_ERR_BAD_ALLOC;
1406     }
1407     uint32_t idx = 0;
1408     agreeParams[idx].tag = HKS_TAG_ALGORITHM;
1409     agreeParams[idx++].uint32Param = g_algToHksAlgorithm[algo]; // only support HKS_ALG_X25519 now
1410     agreeParams[idx].tag = HKS_TAG_KEY_SIZE;
1411     agreeParams[idx++].uint32Param = sharedKey->length * BITS_PER_BYTE;
1412     agreeParams[idx].tag = HKS_TAG_IS_KEY_ALIAS;
1413     agreeParams[idx++].boolParam = keyParams->keyBuff.isAlias;
1414     AddStorageExtParams(agreeParams, keyParams->isDeStorage, &idx, keyParams->osAccountId);
1415     int32_t res = ConstructParamSet(paramSet, agreeParams, idx);
1416     HcFree(agreeParams);
1417     if (res != HAL_SUCCESS) {
1418         LOGE("Construct agree param set failed, res = %d", res);
1419     }
1420     return res;
1421 }
1422 
AgreeSharedSecret(const KeyParams * priKeyParams,const KeyBuff * pubKey,Algorithm algo,Uint8Buff * sharedKey)1423 static int32_t AgreeSharedSecret(const KeyParams *priKeyParams, const KeyBuff *pubKey, Algorithm algo,
1424     Uint8Buff *sharedKey)
1425 {
1426     int32_t res = CheckAgreeParams(priKeyParams, pubKey, sharedKey);
1427     if (res != HAL_SUCCESS) {
1428         return res;
1429     }
1430 
1431     if (g_algToHksAlgorithm[algo] == HKS_ALG_ECC) {
1432         LOGI("Hks agree key for P256.");
1433         KeyBuff priKey = { priKeyParams->keyBuff.key, priKeyParams->keyBuff.keyLen, priKeyParams->keyBuff.isAlias };
1434         return MbedtlsAgreeSharedSecret(&priKey, pubKey, sharedKey);
1435     }
1436 
1437     struct HksBlob priKeyBlob = { priKeyParams->keyBuff.keyLen, priKeyParams->keyBuff.key };
1438     struct HksBlob pubKeyBlob = { pubKey->keyLen, pubKey->key };
1439     struct HksBlob sharedKeyBlob = { sharedKey->length, sharedKey->val };
1440 
1441     struct HksParamSet *paramSet = NULL;
1442     res = ConstructAgreeParamSet(priKeyParams, algo, sharedKey, &paramSet);
1443     if (res != HAL_SUCCESS) {
1444         return res;
1445     }
1446 
1447     LOGI("[HUKS]: HksAgreeKey enter.");
1448     res = HksAgreeKey(paramSet, &priKeyBlob, &pubKeyBlob, &sharedKeyBlob);
1449     FreeParamSet(paramSet);
1450     LOGI("[HUKS]: HksAgreeKey quit. [Res]: %d", res);
1451     if (res != HKS_SUCCESS) {
1452         LOGE("[HUKS]: HksAgreeKey fail. [Res]: %d", res);
1453         return HAL_FAILED;
1454     }
1455     return HAL_SUCCESS;
1456 }
1457 
BigNumExpMod(const Uint8Buff * base,const Uint8Buff * exp,const char * bigNumHex,Uint8Buff * outNum)1458 static int32_t BigNumExpMod(const Uint8Buff *base, const Uint8Buff *exp, const char *bigNumHex, Uint8Buff *outNum)
1459 {
1460     const Uint8Buff *inParams[] = { base, exp, outNum };
1461     const char *paramTags[] = { "base", "exp", "outNum" };
1462     int32_t res = BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams));
1463     if (res != HAL_SUCCESS) {
1464         return res;
1465     }
1466 
1467     CHECK_PTR_RETURN_HAL_ERROR_CODE(bigNumHex, "bigNumHex");
1468     uint32_t primeLen = HcStrlen(bigNumHex) / BYTE_TO_HEX_OPER_LENGTH;
1469     if ((primeLen != BIG_PRIME_LEN_384) && (primeLen != BIG_PRIME_LEN_256)) {
1470         LOGE("Not support big number len %d", outNum->length);
1471         return HAL_FAILED;
1472     }
1473     CHECK_LEN_EQUAL_RETURN(outNum->length, primeLen, "outNum->length");
1474 
1475     struct HksBlob baseBlob = { base->length, base->val };
1476     struct HksBlob expBlob = { exp->length, exp->val };
1477     struct HksBlob outNumBlob = { outNum->length, outNum->val };
1478     struct HksBlob bigNumBlob = { 0, NULL };
1479     bigNumBlob.size = outNum->length;
1480     bigNumBlob.data = (uint8_t *)HcMalloc(bigNumBlob.size, 0);
1481     if (bigNumBlob.data == NULL) {
1482         LOGE("malloc bigNumBlob.data failed.");
1483         return HAL_ERR_BAD_ALLOC;
1484     }
1485     res = HexStringToByte(bigNumHex, bigNumBlob.data, bigNumBlob.size);
1486     if (res != HAL_SUCCESS) {
1487         LOGE("HexStringToByte for bigNumHex failed.");
1488         HcFree(bigNumBlob.data);
1489         return res;
1490     }
1491 
1492     res = HksBnExpMod(&outNumBlob, &baseBlob, &expBlob, &bigNumBlob);
1493     if (res != HKS_SUCCESS) {
1494         LOGE("Huks calculate big number exp mod failed, res = %d", res);
1495         HcFree(bigNumBlob.data);
1496         return HAL_FAILED;
1497     }
1498     outNum->length = outNumBlob.size;
1499 
1500     HcFree(bigNumBlob.data);
1501     return HAL_SUCCESS;
1502 }
1503 
ConstructGenerateKeyPairWithStorageParams(struct HksParamSet ** paramSet,Algorithm algo,uint32_t keyLen,KeyPurpose purpose,const KeyParams * authIdParams)1504 static int32_t ConstructGenerateKeyPairWithStorageParams(struct HksParamSet **paramSet, Algorithm algo,
1505     uint32_t keyLen, KeyPurpose purpose, const KeyParams *authIdParams)
1506 {
1507     struct HksBlob authIdBlob = { authIdParams->keyBuff.keyLen, authIdParams->keyBuff.key };
1508     uint32_t len = GetParamLen(authIdParams->isDeStorage, BASE_GENERATE_KEY_PAIR_PARAMS_LEN);
1509     struct HksParam *generateParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0);
1510     if (generateParams == NULL) {
1511         LOGE("Malloc for generateParams failed.");
1512         return HAL_ERR_BAD_ALLOC;
1513     }
1514     uint32_t idx = 0;
1515     generateParams[idx].tag = HKS_TAG_ALGORITHM;
1516     generateParams[idx++].uint32Param = g_algToHksAlgorithm[algo];
1517     generateParams[idx].tag = HKS_TAG_KEY_STORAGE_FLAG;
1518     generateParams[idx++].uint32Param = HKS_STORAGE_PERSISTENT;
1519     generateParams[idx].tag = HKS_TAG_PURPOSE;
1520     generateParams[idx++].uint32Param = g_purposeToHksKeyPurpose[purpose];
1521     generateParams[idx].tag = HKS_TAG_KEY_SIZE;
1522     generateParams[idx++].uint32Param = keyLen * BITS_PER_BYTE;
1523     generateParams[idx].tag = HKS_TAG_KEY_AUTH_ID;
1524     generateParams[idx++].blob = authIdBlob;
1525     generateParams[idx].tag = HKS_TAG_DIGEST;
1526     generateParams[idx++].uint32Param = HKS_DIGEST_SHA256;
1527     AddStorageExtParams(generateParams, authIdParams->isDeStorage, &idx, authIdParams->osAccountId);
1528     int32_t res = ConstructParamSet(paramSet, generateParams, idx);
1529     HcFree(generateParams);
1530     if (res != HAL_SUCCESS) {
1531         LOGE("Construct generate key pair param set failed, res = %d", res);
1532     }
1533     return res;
1534 }
1535 
CheckGenerateKeyPairParams(const KeyParams * keyParams,const ExtraInfo * exInfo,uint32_t keyLen)1536 static int32_t CheckGenerateKeyPairParams(const KeyParams *keyParams, const ExtraInfo *exInfo, uint32_t keyLen)
1537 {
1538     int32_t res = CheckKeyParams(keyParams);
1539     if (res != HAL_SUCCESS)  {
1540         return res;
1541     }
1542     CHECK_PTR_RETURN_HAL_ERROR_CODE(exInfo, "exInfo");
1543     CHECK_PTR_RETURN_HAL_ERROR_CODE(exInfo->authId.val, "authId->val");
1544     CHECK_LEN_ZERO_RETURN_ERROR_CODE(exInfo->authId.length, "authId->length");
1545     CHECK_LEN_ZERO_RETURN_ERROR_CODE(keyLen, "keyLen");
1546     return HAL_SUCCESS;
1547 }
1548 
GenerateKeyPairWithStorage(const KeyParams * keyParams,uint32_t keyLen,Algorithm algo,KeyPurpose purpose,const ExtraInfo * exInfo)1549 static int32_t GenerateKeyPairWithStorage(const KeyParams *keyParams, uint32_t keyLen, Algorithm algo,
1550     KeyPurpose purpose, const ExtraInfo *exInfo)
1551 {
1552     int32_t res = CheckGenerateKeyPairParams(keyParams, exInfo, keyLen);
1553     if (res != HAL_SUCCESS) {
1554         return res;
1555     }
1556 
1557     KeyParams authIdParams = {
1558         .keyBuff = { exInfo->authId.val, exInfo->authId.length, true },
1559         .isDeStorage = keyParams->isDeStorage,
1560         .osAccountId = keyParams->osAccountId
1561     };
1562     struct HksParamSet *paramSet = NULL;
1563     res = ConstructGenerateKeyPairWithStorageParams(&paramSet, algo, keyLen, purpose, &authIdParams);
1564     if (res != HAL_SUCCESS) {
1565         return res;
1566     }
1567     struct HksBlob keyAliasBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
1568 
1569     LOGI("[HUKS]: HksGenerateKey enter.");
1570     res = HksGenerateKey(&keyAliasBlob, paramSet, NULL);
1571     FreeParamSet(paramSet);
1572     LOGI("[HUKS]: HksGenerateKey quit. [Res]: %d", res);
1573     if (res != HKS_SUCCESS) {
1574         LOGE("[HUKS]: HksGenerateKey fail. [Res]: %d", res);
1575         return HAL_FAILED;
1576     }
1577     return HAL_SUCCESS;
1578 }
1579 
GetKeyPair(struct HksParamSet * outParamSet,Uint8Buff * outPriKey,Uint8Buff * outPubKey)1580 static int32_t GetKeyPair(struct HksParamSet *outParamSet, Uint8Buff *outPriKey, Uint8Buff *outPubKey)
1581 {
1582     int32_t res = HksFreshParamSet(outParamSet, false); /* false means fresh by local, not through IPC */
1583     if (res != HKS_SUCCESS) {
1584         LOGE("fresh param set failed, res:%d", res);
1585         return HAL_ERR_FRESH_PARAM_SET_FAILED;
1586     }
1587 
1588     struct HksParam *pubKeyParam = NULL;
1589     res = HksGetParam(outParamSet, HKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA, &pubKeyParam);
1590     if (res != HKS_SUCCESS) {
1591         LOGE("get pub key from param set failed, res:%d", res);
1592         return HAL_ERR_GET_PARAM_FAILED;
1593     }
1594 
1595     struct HksParam *priKeyParam = NULL;
1596     res = HksGetParam(outParamSet, HKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA, &priKeyParam);
1597     if (res != HKS_SUCCESS) {
1598         LOGE("get priv key from param set failed, res:%d", res);
1599         return HAL_ERR_GET_PARAM_FAILED;
1600     }
1601 
1602     if (memcpy_s(outPubKey->val, outPubKey->length, pubKeyParam->blob.data, pubKeyParam->blob.size) != EOK) {
1603         LOGE("parse x25519 output param set memcpy public key failed!");
1604         return HAL_ERR_MEMORY_COPY;
1605     }
1606     outPubKey->length = pubKeyParam->blob.size;
1607 
1608     if (memcpy_s(outPriKey->val, outPriKey->length, priKeyParam->blob.data, priKeyParam->blob.size) != EOK) {
1609         LOGE("parse x25519 output param set memcpy private key failed!");
1610         return HAL_ERR_MEMORY_COPY;
1611     }
1612     outPriKey->length = priKeyParam->blob.size;
1613 
1614     return HAL_SUCCESS;
1615 }
1616 
ConstructGenerateKeyPairParams(struct HksParamSet ** paramSet,Algorithm algo,uint32_t keyLen)1617 static int32_t ConstructGenerateKeyPairParams(struct HksParamSet **paramSet, Algorithm algo, uint32_t keyLen)
1618 {
1619     struct HksParam keyParam[] = {
1620         {
1621             .tag = HKS_TAG_KEY_STORAGE_FLAG,
1622             .uint32Param = HKS_STORAGE_TEMP
1623         }, {
1624             .tag = HKS_TAG_ALGORITHM,
1625             .uint32Param = g_algToHksAlgorithm[algo]
1626         }, {
1627             .tag = HKS_TAG_KEY_SIZE,
1628             .uint32Param = keyLen * BITS_PER_BYTE
1629         }, {
1630             .tag = HKS_TAG_IS_KEY_ALIAS,
1631             .uint32Param = false
1632         }
1633     };
1634 
1635     int32_t res = ConstructParamSet(paramSet, keyParam, CAL_ARRAY_SIZE(keyParam));
1636     if (res != HAL_SUCCESS) {
1637         LOGE("Construct param set failed, res = %d", res);
1638         return res;
1639     }
1640     return res;
1641 }
1642 
GenerateKeyPair(Algorithm algo,Uint8Buff * outPriKey,Uint8Buff * outPubKey)1643 static int32_t GenerateKeyPair(Algorithm algo, Uint8Buff *outPriKey, Uint8Buff *outPubKey)
1644 {
1645     CHECK_PTR_RETURN_HAL_ERROR_CODE(outPriKey, "outPriKey");
1646     CHECK_PTR_RETURN_HAL_ERROR_CODE(outPriKey->val, "outPriKey->key");
1647     CHECK_LEN_ZERO_RETURN_ERROR_CODE(outPriKey->length, "outPriKey->keyLen");
1648     CHECK_PTR_RETURN_HAL_ERROR_CODE(outPubKey, "outPubKey");
1649     CHECK_PTR_RETURN_HAL_ERROR_CODE(outPubKey->val, "outPubKey->key");
1650     CHECK_LEN_ZERO_RETURN_ERROR_CODE(outPubKey->length, "outPubKey->keyLen");
1651 
1652     if (outPriKey->length != outPubKey->length) {
1653         LOGE("key len not equal.");
1654         return HAL_ERR_INVALID_LEN;
1655     }
1656     uint32_t keyLen = outPriKey->length;
1657 
1658     struct HksParamSet *paramSet = NULL;
1659     struct HksParamSet *outParamSet = NULL;
1660     int32_t res = ConstructGenerateKeyPairParams(&paramSet, algo, keyLen);
1661     if (res != HAL_SUCCESS) {
1662         return res;
1663     }
1664 
1665     /* need 2 HksParam struct for outPriKey and outPubKey */
1666     uint32_t outParamSetSize = sizeof(struct HksParamSet) +
1667         2 * (sizeof(struct HksParam)) + outPriKey->length + outPubKey->length;
1668     outParamSet = (struct HksParamSet *)HcMalloc(outParamSetSize, 0);
1669     if (outParamSet == NULL) {
1670         LOGE("allocate buffer for output param set failed");
1671         res = HAL_ERR_BAD_ALLOC;
1672         goto ERR;
1673     }
1674     outParamSet->paramSetSize = outParamSetSize;
1675 
1676     LOGI("[HUKS]: HksGenerateKey enter.");
1677     res = HksGenerateKey(NULL, paramSet, outParamSet);
1678     LOGI("[HUKS]: HksGenerateKey quit. [Res]: %d", res);
1679     if (res != HKS_SUCCESS) {
1680         LOGI("[HUKS]: HksGenerateKey quit. [Res]: %d", res);
1681         res = HAL_FAILED;
1682         goto ERR;
1683     }
1684 
1685     res = GetKeyPair(outParamSet, outPriKey, outPubKey);
1686     if (res != HAL_SUCCESS) {
1687         LOGE("parse x25519 output param set failed, res:%d", res);
1688         goto ERR;
1689     }
1690 ERR:
1691     FreeParamSet(paramSet);
1692     HcFree(outParamSet);
1693     return res;
1694 }
1695 
ConstructExportParams(bool isDeStorage,int32_t osAccountId,struct HksParamSet ** paramSet)1696 static int32_t ConstructExportParams(bool isDeStorage, int32_t osAccountId, struct HksParamSet **paramSet)
1697 {
1698     uint32_t len = GetParamLen(isDeStorage, 0);
1699     if (len == 0) {
1700         return HAL_SUCCESS;
1701     }
1702     struct HksParam *exportParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0);
1703     if (exportParams == NULL) {
1704         LOGE("Malloc for exportParams failed.");
1705         return HAL_ERR_BAD_ALLOC;
1706     }
1707     uint32_t idx = 0;
1708     AddStorageExtParams(exportParams, isDeStorage, &idx, osAccountId);
1709     int32_t res = ConstructParamSet(paramSet, exportParams, idx);
1710     HcFree(exportParams);
1711     if (res != HAL_SUCCESS) {
1712         LOGE("Failed to construct export param set, res: %d", res);
1713     }
1714     return res;
1715 }
1716 
CheckExportParams(const KeyParams * keyParams,const Uint8Buff * outPubKey)1717 static int32_t CheckExportParams(const KeyParams *keyParams, const Uint8Buff *outPubKey)
1718 {
1719     int32_t res = CheckKeyParams(keyParams);
1720     if (res != HAL_SUCCESS) {
1721         return res;
1722     }
1723     CHECK_PTR_RETURN_HAL_ERROR_CODE(outPubKey, "outPubKey");
1724     CHECK_PTR_RETURN_HAL_ERROR_CODE(outPubKey->val, "outPubKey->val");
1725     CHECK_LEN_ZERO_RETURN_ERROR_CODE(outPubKey->length, "outPubKey->length");
1726     return HAL_SUCCESS;
1727 }
1728 
ExportPublicKey(const KeyParams * keyParams,Uint8Buff * outPubKey)1729 static int32_t ExportPublicKey(const KeyParams *keyParams, Uint8Buff *outPubKey)
1730 {
1731     int32_t res = CheckExportParams(keyParams, outPubKey);
1732     if (res != HAL_SUCCESS) {
1733         return res;
1734     }
1735 
1736     struct HksParamSet *deParamSet = NULL;
1737     res = ConstructExportParams(true, keyParams->osAccountId, &deParamSet);
1738     if (res != HAL_SUCCESS) {
1739         return res;
1740     }
1741     struct HksParamSet *ceParamSet = NULL;
1742     res = ConstructExportParams(false, keyParams->osAccountId, &ceParamSet);
1743     if (res != HAL_SUCCESS) {
1744         FreeParamSet(deParamSet);
1745         return res;
1746     }
1747     struct HksBlob keyAliasBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
1748     struct HksBlob keyBlob = { outPubKey->length, outPubKey->val };
1749 
1750     LOGI("[HUKS]: HksExportPublicKey enter.");
1751     if (keyParams->isDeStorage) {
1752         res = HksExportPublicKey(&keyAliasBlob, deParamSet, &keyBlob);
1753         if (res == HKS_SUCCESS) {
1754             MoveDeKeyToCe(true, keyParams->osAccountId, &keyAliasBlob);
1755         } else {
1756             res = HksExportPublicKey(&keyAliasBlob, ceParamSet, &keyBlob);
1757         }
1758     } else {
1759         res = HksExportPublicKey(&keyAliasBlob, ceParamSet, &keyBlob);
1760         if (res != HKS_SUCCESS) {
1761             res = HksExportPublicKey(&keyAliasBlob, deParamSet, &keyBlob);
1762         }
1763     }
1764     LOGI("[HUKS]: HksExportPublicKey quit. [Res]: %d", res);
1765     FreeParamSet(deParamSet);
1766     FreeParamSet(ceParamSet);
1767     if (res != HKS_SUCCESS) {
1768         LOGE("[HUKS]: HksExportPublicKey failed. [Res]: %d", res);
1769         return HAL_FAILED;
1770     }
1771     outPubKey->length = keyBlob.size;
1772     return HAL_SUCCESS;
1773 }
1774 
ConstructSignParams(bool isDeStorage,int32_t osAccountId,struct HksParamSet ** paramSet,Algorithm algo)1775 static int32_t ConstructSignParams(bool isDeStorage, int32_t osAccountId, struct HksParamSet **paramSet,
1776     Algorithm algo)
1777 {
1778     uint32_t len = GetParamLen(isDeStorage, BASE_SIGN_PARAMS_LEN);
1779     struct HksParam *signParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0);
1780     if (signParams == NULL) {
1781         LOGE("Malloc for signParams failed.");
1782         return HAL_ERR_BAD_ALLOC;
1783     }
1784     uint32_t idx = 0;
1785     signParams[idx].tag = HKS_TAG_PURPOSE;
1786     signParams[idx++].uint32Param = HKS_KEY_PURPOSE_SIGN;
1787     signParams[idx].tag = HKS_TAG_ALGORITHM;
1788     signParams[idx++].uint32Param = g_algToHksAlgorithm[algo]; // only support HKS_ALG_ED25519 and HKS_ALG_ECC.
1789     signParams[idx].tag = HKS_TAG_DIGEST;
1790     signParams[idx++].uint32Param = HKS_DIGEST_SHA256;
1791     AddStorageExtParams(signParams, isDeStorage, &idx, osAccountId);
1792     int32_t res = ConstructParamSet(paramSet, signParams, idx);
1793     HcFree(signParams);
1794     if (res != HAL_SUCCESS) {
1795         LOGE("Construct sign param set failed, res = %d", res);
1796     }
1797     return res;
1798 }
1799 
CheckSignParams(const KeyParams * keyParams,const Uint8Buff * message,const Uint8Buff * outSignature)1800 static int32_t CheckSignParams(const KeyParams *keyParams, const Uint8Buff *message,
1801     const Uint8Buff *outSignature)
1802 {
1803     int32_t res = CheckKeyParams(keyParams);
1804     if (res != HAL_SUCCESS) {
1805         return res;
1806     }
1807     const Uint8Buff *inParams[] = { message, outSignature };
1808     const char *paramTags[] = { "message", "outSignature" };
1809     return BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams));
1810 }
1811 
Sign(const KeyParams * keyParams,const Uint8Buff * message,Algorithm algo,Uint8Buff * outSignature)1812 static int32_t Sign(const KeyParams *keyParams, const Uint8Buff *message, Algorithm algo,
1813     Uint8Buff *outSignature)
1814 {
1815     int32_t res = CheckSignParams(keyParams, message, outSignature);
1816     if (res != HAL_SUCCESS) {
1817         return res;
1818     }
1819 
1820     uint8_t messageHashVal[SHA256_LEN] = { 0 };
1821     Uint8Buff messageHash = { messageHashVal, SHA256_LEN };
1822     res = Sha256(message, &messageHash);
1823     if (res != HAL_SUCCESS) {
1824         LOGE("Sha256 failed.");
1825         return res;
1826     }
1827     struct HksParamSet *deParamSet = NULL;
1828     res = ConstructSignParams(true, keyParams->osAccountId, &deParamSet, algo);
1829     if (res != HAL_SUCCESS) {
1830         return res;
1831     }
1832     struct HksParamSet *ceParamSet = NULL;
1833     res = ConstructSignParams(false, keyParams->osAccountId, &ceParamSet, algo);
1834     if (res != HAL_SUCCESS) {
1835         FreeParamSet(deParamSet);
1836         return res;
1837     }
1838     struct HksBlob keyAliasBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
1839     struct HksBlob messageBlob = { messageHash.length, messageHash.val };
1840     struct HksBlob signatureBlob = { outSignature->length, outSignature->val };
1841 
1842     LOGI("[HUKS]: HksSign enter.");
1843     if (keyParams->isDeStorage) {
1844         res = HksSign(&keyAliasBlob, deParamSet, &messageBlob, &signatureBlob);
1845         if (res == HKS_SUCCESS) {
1846             MoveDeKeyToCe(keyParams->keyBuff.isAlias, keyParams->osAccountId, &keyAliasBlob);
1847         } else {
1848             res = HksSign(&keyAliasBlob, ceParamSet, &messageBlob, &signatureBlob);
1849         }
1850     } else {
1851         res = HksSign(&keyAliasBlob, ceParamSet, &messageBlob, &signatureBlob);
1852         if (res != HKS_SUCCESS) {
1853             res = HksSign(&keyAliasBlob, deParamSet, &messageBlob, &signatureBlob);
1854         }
1855     }
1856     LOGI("[HUKS]: HksSign quit. [Res]: %d", res);
1857     FreeParamSet(deParamSet);
1858     FreeParamSet(ceParamSet);
1859     if (res != HKS_SUCCESS) {
1860         LOGE("[HUKS]: HksSign fail. [Res]: %d", res);
1861         return HAL_FAILED;
1862     }
1863     outSignature->length = signatureBlob.size;
1864     return HAL_SUCCESS;
1865 }
1866 
ConstructVerifyParams(struct HksParamSet ** paramSet,const KeyParams * keyParams,Algorithm algo)1867 static int32_t ConstructVerifyParams(struct HksParamSet **paramSet, const KeyParams *keyParams, Algorithm algo)
1868 {
1869     uint32_t len = GetParamLen(keyParams->isDeStorage, BASE_VERIFY_PARAMS_LEN);
1870     struct HksParam *verifyParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0);
1871     if (verifyParams == NULL) {
1872         LOGE("Malloc for verifyParams failed.");
1873         return HAL_ERR_BAD_ALLOC;
1874     }
1875     uint32_t idx = 0;
1876     verifyParams[idx].tag = HKS_TAG_PURPOSE;
1877     verifyParams[idx++].uint32Param = HKS_KEY_PURPOSE_VERIFY;
1878     verifyParams[idx].tag = HKS_TAG_ALGORITHM;
1879     verifyParams[idx++].uint32Param = g_algToHksAlgorithm[algo]; // only support HKS_ALG_ED25519 and HKS_ALG_ECC.
1880     verifyParams[idx].tag = HKS_TAG_IS_KEY_ALIAS;
1881     verifyParams[idx++].boolParam = keyParams->keyBuff.isAlias;
1882     verifyParams[idx].tag = HKS_TAG_DIGEST;
1883     verifyParams[idx++].uint32Param = HKS_DIGEST_SHA256;
1884     AddStorageExtParams(verifyParams, keyParams->isDeStorage, &idx, keyParams->osAccountId);
1885     int32_t res = ConstructParamSet(paramSet, verifyParams, idx);
1886     HcFree(verifyParams);
1887     if (res != HAL_SUCCESS) {
1888         LOGE("Construct verify param set failed, res = %d", res);
1889     }
1890     return res;
1891 }
1892 
CheckVerifyParams(const KeyParams * keyParams,const Uint8Buff * message,const Uint8Buff * signature)1893 static int32_t CheckVerifyParams(const KeyParams *keyParams, const Uint8Buff *message,
1894     const Uint8Buff *signature)
1895 {
1896     int32_t res = CheckKeyParams(keyParams);
1897     if (res != HAL_SUCCESS) {
1898         return res;
1899     }
1900     const Uint8Buff *inParams[] = { message, signature };
1901     const char *paramTags[] = { "message", "signature" };
1902     return BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams));
1903 }
1904 
Verify(const KeyParams * keyParams,const Uint8Buff * message,Algorithm algo,const Uint8Buff * signature)1905 static int32_t Verify(const KeyParams *keyParams, const Uint8Buff *message, Algorithm algo,
1906     const Uint8Buff *signature)
1907 {
1908     int32_t res = CheckVerifyParams(keyParams, message, signature);
1909     if (res != HAL_SUCCESS) {
1910         return res;
1911     }
1912 
1913     uint8_t messageHashVal[SHA256_LEN] = { 0 };
1914     Uint8Buff messageHash = { messageHashVal, SHA256_LEN };
1915     res = Sha256(message, &messageHash);
1916     if (res != HAL_SUCCESS) {
1917         LOGE("Sha256 failed.");
1918         return res;
1919     }
1920 
1921     struct HksParamSet *paramSet = NULL;
1922     res = ConstructVerifyParams(&paramSet, keyParams, algo);
1923     if (res != HAL_SUCCESS) {
1924         return res;
1925     }
1926     struct HksBlob keyAliasBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
1927     struct HksBlob messageBlob = { messageHash.length, messageHash.val };
1928     struct HksBlob signatureBlob = { signature->length, signature->val };
1929 
1930     LOGI("[HUKS]: HksVerify enter.");
1931     res = HksVerify(&keyAliasBlob, paramSet, &messageBlob, &signatureBlob);
1932     FreeParamSet(paramSet);
1933     LOGI("[HUKS]: HksVerify quit. [Res]: %d", res);
1934     if ((res != HKS_SUCCESS)) {
1935         LOGE("[HUKS]: HksVerify fail. [Res]: %d", res);
1936         return HAL_FAILED;
1937     }
1938     return HAL_SUCCESS;
1939 }
1940 
ConstructImportPublicKeyParams(struct HksParamSet ** paramSet,Algorithm algo,uint32_t keyLen,const KeyParams * authIdParams,const union KeyRoleInfoUnion * roleInfoUnion)1941 static int32_t ConstructImportPublicKeyParams(struct HksParamSet **paramSet, Algorithm algo, uint32_t keyLen,
1942     const KeyParams *authIdParams, const union KeyRoleInfoUnion *roleInfoUnion)
1943 {
1944     if (g_algToHksAlgorithm[algo] == HKS_ALG_ECC) {
1945         keyLen = ECC_PK_LEN;
1946     }
1947     struct HksBlob authIdBlob = { authIdParams->keyBuff.keyLen, authIdParams->keyBuff.key };
1948     uint32_t len = GetParamLen(authIdParams->isDeStorage, BASE_IMPORT_PUB_KEY_PARAMS_LEN);
1949     struct HksParam *importParams = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0);
1950     if (importParams == NULL) {
1951         LOGE("Malloc for importParams failed.");
1952         return HAL_ERR_BAD_ALLOC;
1953     }
1954     uint32_t idx = 0;
1955     importParams[idx].tag = HKS_TAG_ALGORITHM;
1956     importParams[idx++].uint32Param = g_algToHksAlgorithm[algo];
1957     importParams[idx].tag = HKS_TAG_KEY_SIZE;
1958     importParams[idx++].uint32Param = keyLen * BITS_PER_BYTE;
1959     importParams[idx].tag = HKS_TAG_PADDING;
1960     importParams[idx++].uint32Param = HKS_PADDING_NONE;
1961     importParams[idx].tag = HKS_TAG_KEY_AUTH_ID;
1962     importParams[idx++].blob = authIdBlob;
1963     importParams[idx].tag = HKS_TAG_IS_ALLOWED_WRAP;
1964     importParams[idx++].boolParam = true;
1965     importParams[idx].tag = HKS_TAG_PURPOSE;
1966     importParams[idx++].uint32Param = HKS_KEY_PURPOSE_VERIFY;
1967     importParams[idx].tag = HKS_TAG_KEY_ROLE;
1968     importParams[idx++].uint32Param = roleInfoUnion->roleInfo;
1969     importParams[idx].tag = HKS_TAG_DIGEST;
1970     importParams[idx++].uint32Param = HKS_DIGEST_SHA256;
1971     AddStorageExtParams(importParams, authIdParams->isDeStorage, &idx, authIdParams->osAccountId);
1972     int32_t res = ConstructParamSet(paramSet, importParams, idx);
1973     HcFree(importParams);
1974     if (res != HAL_SUCCESS) {
1975         LOGE("Construct import param set failed, res = %d", res);
1976     }
1977     return res;
1978 }
1979 
CheckImportPubKeyParams(const KeyParams * keyParams,const Uint8Buff * pubKey,const ExtraInfo * exInfo)1980 static int32_t CheckImportPubKeyParams(const KeyParams *keyParams, const Uint8Buff *pubKey,
1981     const ExtraInfo *exInfo)
1982 {
1983     int32_t res = CheckKeyParams(keyParams);
1984     if (res != HAL_SUCCESS) {
1985         return res;
1986     }
1987     CHECK_PTR_RETURN_HAL_ERROR_CODE(pubKey, "pubKey");
1988     CHECK_PTR_RETURN_HAL_ERROR_CODE(pubKey->val, "pubKey->val");
1989     CHECK_LEN_ZERO_RETURN_ERROR_CODE(pubKey->length, "pubKey->length");
1990     CHECK_PTR_RETURN_HAL_ERROR_CODE(exInfo, "exInfo");
1991     CHECK_PTR_RETURN_HAL_ERROR_CODE(exInfo->authId.val, "authId->val");
1992     CHECK_LEN_ZERO_RETURN_ERROR_CODE(exInfo->authId.length, "authId->length");
1993     CHECK_LEN_HIGHER_RETURN(exInfo->pairType, PAIR_TYPE_END - 1, "pairType");
1994     return HAL_SUCCESS;
1995 }
1996 
ImportPublicKey(const KeyParams * keyParams,const Uint8Buff * pubKey,Algorithm algo,const ExtraInfo * exInfo)1997 static int32_t ImportPublicKey(const KeyParams *keyParams, const Uint8Buff *pubKey, Algorithm algo,
1998     const ExtraInfo *exInfo)
1999 {
2000     int32_t res = CheckImportPubKeyParams(keyParams, pubKey, exInfo);
2001     if (res != HAL_SUCCESS) {
2002         return res;
2003     }
2004 
2005     union KeyRoleInfoUnion roleInfoUnion;
2006     roleInfoUnion.roleInfoStruct.userType = (uint8_t)exInfo->userType;
2007     roleInfoUnion.roleInfoStruct.pairType = (uint8_t)exInfo->pairType;
2008     roleInfoUnion.roleInfoStruct.reserved1 = (uint8_t)0;
2009     roleInfoUnion.roleInfoStruct.reserved2 = (uint8_t)0;
2010 
2011     KeyParams authIdParams = {
2012         .keyBuff = { exInfo->authId.val, exInfo->authId.length, true },
2013         .isDeStorage = keyParams->isDeStorage,
2014         .osAccountId = keyParams->osAccountId
2015     };
2016     struct HksParamSet *paramSet = NULL;
2017     res = ConstructImportPublicKeyParams(&paramSet, algo, pubKey->length, &authIdParams, &roleInfoUnion);
2018     if (res != HAL_SUCCESS) {
2019         return res;
2020     }
2021     struct HksBlob keyAliasBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
2022     struct HksBlob pubKeyBlob = { pubKey->length, pubKey->val };
2023 
2024     LOGI("[HUKS]: HksImportKey enter.");
2025     res = HksImportKey(&keyAliasBlob, paramSet, &pubKeyBlob);
2026     FreeParamSet(paramSet);
2027     LOGI("[HUKS]: HksImportKey quit. [Res]: %d", res);
2028     if (res != HKS_SUCCESS) {
2029         LOGE("[HUKS]: HksImportKey fail. [Res]: %d", res);
2030         return HAL_FAILED;
2031     }
2032     return HAL_SUCCESS;
2033 }
2034 
CheckBigNumCompareParams(const Uint8Buff * a,const Uint8Buff * b,int * res)2035 static bool CheckBigNumCompareParams(const Uint8Buff *a, const Uint8Buff *b, int *res)
2036 {
2037     if ((a == NULL || a->val == NULL) && (b == NULL || b->val == NULL)) {
2038         *res = 0; // a = b
2039         return false;
2040     }
2041     if ((a == NULL || a->val == NULL) && (b != NULL && b->val != NULL)) {
2042         *res = 1; // a < b
2043         return false;
2044     }
2045     if ((a != NULL && a->val != NULL) && (b == NULL || b->val == NULL)) {
2046         *res = -1; // a > b
2047         return false;
2048     }
2049     return true;
2050 }
2051 
BigNumCompare(const Uint8Buff * a,const Uint8Buff * b)2052 static int32_t BigNumCompare(const Uint8Buff *a, const Uint8Buff *b)
2053 {
2054     int res = 0;
2055     if (!CheckBigNumCompareParams(a, b, &res)) {
2056         return res;
2057     }
2058     const uint8_t *tmpA = a->val;
2059     const uint8_t *tmpB = b->val;
2060     uint32_t len = a->length;
2061     if (a->length < b->length) {
2062         for (uint32_t i = 0; i < b->length - a->length; i++) {
2063             if (b->val[i] > 0) {
2064                 return 1; // a < b
2065             }
2066         }
2067         tmpA = a->val;
2068         tmpB = b->val + b->length - a->length;
2069         len = a->length;
2070     }
2071     if (a->length > b->length) {
2072         for (uint32_t i = 0; i < a->length - b->length; i++) {
2073             if (a->val[i] > 0) {
2074                 return -1; // a > b
2075             }
2076         }
2077         tmpA = a->val + a->length - b->length;
2078         tmpB = b->val;
2079         len = b->length;
2080     }
2081     for (uint32_t i = 0; i < len; i++) {
2082         if (*(tmpA + i) > *(tmpB + i)) {
2083             return -1; // a > b
2084         }
2085         if (*(tmpA + i) < *(tmpB + i)) {
2086             return 1; // a < b
2087         }
2088     }
2089     return 0; // a == b
2090 }
2091 
CheckDlPublicKey(const Uint8Buff * key,const char * primeHex)2092 static bool CheckDlPublicKey(const Uint8Buff *key, const char *primeHex)
2093 {
2094     if (key == NULL || key->val == NULL || primeHex == NULL) {
2095         LOGE("Params is null.");
2096         return false;
2097     }
2098     uint8_t min = 1;
2099 
2100     uint32_t innerKeyLen = HcStrlen(primeHex) / BYTE_TO_HEX_OPER_LENGTH;
2101     if (key->length > innerKeyLen) {
2102         LOGE("Key length > prime number length.");
2103         return false;
2104     }
2105     uint8_t *primeByte = (uint8_t *)HcMalloc(innerKeyLen, 0);
2106     if (primeByte == NULL) {
2107         LOGE("Malloc for primeByte failed.");
2108         return false;
2109     }
2110     if (HexStringToByte(primeHex, primeByte, innerKeyLen) != HAL_SUCCESS) {
2111         LOGE("Convert prime number from hex string to byte failed.");
2112         HcFree(primeByte);
2113         return false;
2114     }
2115     /*
2116      * P - 1, since the last byte of large prime number must be greater than 1,
2117      * needn't to think about borrowing forward
2118      */
2119     primeByte[innerKeyLen - 1] -= 1;
2120 
2121     Uint8Buff minBuff = { &min, sizeof(uint8_t) };
2122     if (BigNumCompare(key, &minBuff) >= 0) {
2123         LOGE("Pubkey is invalid, key <= 1.");
2124         HcFree(primeByte);
2125         return false;
2126     }
2127 
2128     Uint8Buff primeBuff = { primeByte, innerKeyLen };
2129     if (BigNumCompare(key, &primeBuff) <= 0) {
2130         LOGE("Pubkey is invalid, key >= p - 1.");
2131         HcFree(primeByte);
2132         return false;
2133     }
2134 
2135     HcFree(primeByte);
2136     return true;
2137 }
2138 
CheckEcPublicKey(const Uint8Buff * pubKey,Algorithm algo)2139 static bool CheckEcPublicKey(const Uint8Buff *pubKey, Algorithm algo)
2140 {
2141     (void)pubKey;
2142     (void)algo;
2143     return true;
2144 }
2145 
InitImportParam(const KeyParams * keyParams,const ExtraInfo * exInfo,struct HksParam ** importParam)2146 static int32_t InitImportParam(const KeyParams *keyParams, const ExtraInfo *exInfo, struct HksParam **importParam)
2147 {
2148     if (exInfo != NULL) {
2149         CHECK_PTR_RETURN_HAL_ERROR_CODE(exInfo->authId.val, "authId");
2150         CHECK_LEN_ZERO_RETURN_ERROR_CODE(exInfo->authId.length, "authId");
2151         CHECK_LEN_HIGHER_RETURN(exInfo->pairType, PAIR_TYPE_END - 1, "pairType");
2152     }
2153     uint32_t baseLen = ((exInfo == NULL) ? BASE_IMPORT_PARAMS_LEN : (BASE_IMPORT_PARAMS_LEN + EXT_IMPORT_PARAMS_LEN));
2154     uint32_t len = GetParamLen(keyParams->isDeStorage, baseLen);
2155     *importParam = (struct HksParam *)HcMalloc(sizeof(struct HksParam) * len, 0);
2156     if (*importParam == NULL) {
2157         LOGE("Malloc for importParam failed.");
2158         return HAL_ERR_BAD_ALLOC;
2159     }
2160     return HAL_SUCCESS;
2161 }
2162 
ConstructImportSymmetricKeyParam(struct HksParamSet ** paramSet,const KeyParams * keyParams,uint32_t keyLen,KeyPurpose purpose,const ExtraInfo * exInfo)2163 static int32_t ConstructImportSymmetricKeyParam(struct HksParamSet **paramSet, const KeyParams *keyParams,
2164     uint32_t keyLen, KeyPurpose purpose, const ExtraInfo *exInfo)
2165 {
2166     struct HksParam *importParam = NULL;
2167     int32_t res = InitImportParam(keyParams, exInfo, &importParam);
2168     if (res != HAL_SUCCESS) {
2169         return res;
2170     }
2171     uint32_t idx = 0;
2172     if (exInfo != NULL) {
2173         struct HksBlob authIdBlob = { 0, NULL };
2174         union KeyRoleInfoUnion roleInfoUnion;
2175         (void)memset_s(&roleInfoUnion, sizeof(roleInfoUnion), 0, sizeof(roleInfoUnion));
2176         authIdBlob.size = exInfo->authId.length;
2177         authIdBlob.data = exInfo->authId.val;
2178         roleInfoUnion.roleInfoStruct.userType = (uint8_t)exInfo->userType;
2179         roleInfoUnion.roleInfoStruct.pairType = (uint8_t)exInfo->pairType;
2180         importParam[idx].tag = HKS_TAG_KEY_AUTH_ID;
2181         importParam[idx++].blob = authIdBlob;
2182         importParam[idx].tag = HKS_TAG_KEY_ROLE;
2183         importParam[idx++].uint32Param = roleInfoUnion.roleInfo;
2184     }
2185 
2186     importParam[idx].tag = HKS_TAG_ALGORITHM;
2187     importParam[idx++].uint32Param = HKS_ALG_AES;
2188     importParam[idx].tag = HKS_TAG_KEY_SIZE;
2189     importParam[idx++].uint32Param = keyLen * BITS_PER_BYTE;
2190     importParam[idx].tag = HKS_TAG_PADDING;
2191     importParam[idx++].uint32Param = HKS_PADDING_NONE;
2192     importParam[idx].tag = HKS_TAG_IS_ALLOWED_WRAP;
2193     importParam[idx++].boolParam = false;
2194     importParam[idx].tag = HKS_TAG_PURPOSE;
2195     importParam[idx++].uint32Param = g_purposeToHksKeyPurpose[purpose];
2196     importParam[idx].tag = HKS_TAG_BLOCK_MODE;
2197     importParam[idx++].uint32Param = HKS_MODE_GCM;
2198     importParam[idx].tag = HKS_TAG_DIGEST;
2199     importParam[idx++].uint32Param = HKS_DIGEST_SHA256;
2200     AddStorageExtParams(importParam, keyParams->isDeStorage, &idx, keyParams->osAccountId);
2201     res = ConstructParamSet(paramSet, importParam, idx);
2202     HcFree(importParam);
2203     return res;
2204 }
2205 
CheckImportSymmetricKeyParams(const KeyParams * keyParams,const Uint8Buff * authToken)2206 static int32_t CheckImportSymmetricKeyParams(const KeyParams *keyParams, const Uint8Buff *authToken)
2207 {
2208     int32_t res = CheckKeyParams(keyParams);
2209     if (res != HAL_SUCCESS) {
2210         return res;
2211     }
2212     const Uint8Buff *inParams[] = { authToken };
2213     const char *paramTags[] = { "authToken" };
2214     return BaseCheckParams(inParams, paramTags, CAL_ARRAY_SIZE(inParams));
2215 }
2216 
ImportSymmetricKey(const KeyParams * keyParams,const Uint8Buff * authToken,KeyPurpose purpose,const ExtraInfo * exInfo)2217 static int32_t ImportSymmetricKey(const KeyParams *keyParams, const Uint8Buff *authToken, KeyPurpose purpose,
2218     const ExtraInfo *exInfo)
2219 {
2220     int32_t res = CheckImportSymmetricKeyParams(keyParams, authToken);
2221     if (res != HAL_SUCCESS) {
2222         return res;
2223     }
2224 
2225     struct HksParamSet *paramSet = NULL;
2226     res = ConstructImportSymmetricKeyParam(&paramSet, keyParams, authToken->length, purpose, exInfo);
2227     if (res != HAL_SUCCESS) {
2228         LOGE("construct param set failed, res = %d", res);
2229         return res;
2230     }
2231     struct HksBlob keyAliasBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
2232     struct HksBlob symKeyBlob = { authToken->length, authToken->val };
2233 
2234     LOGI("[HUKS]: HksImportKey enter.");
2235     res = HksImportKey(&keyAliasBlob, paramSet, &symKeyBlob);
2236     FreeParamSet(paramSet);
2237     LOGI("[HUKS]: HksImportKey quit. [Res]: %d", res);
2238     if (res != HKS_SUCCESS) {
2239         LOGE("[HUKS]: HksImportKey fail. [Res]: %d", res);
2240         return HAL_FAILED;
2241     }
2242     return HAL_SUCCESS;
2243 }
2244 
2245 static const AlgLoader g_huksLoader = {
2246     .initAlg = InitHks,
2247     .sha256 = Sha256,
2248     .generateRandom = GenerateRandom,
2249     .computeHmac = ComputeHmac,
2250     .computeHmacWithThreeStage = ComputeHmacWithThreeStage,
2251     .computeHkdf = ComputeHkdf,
2252     .computePseudonymPsk = ComputePseudonymPsk,
2253     .getKeyExtInfo = GetKeyExtInfo,
2254     .importSymmetricKey = ImportSymmetricKey,
2255     .checkKeyExist = CheckKeyExist,
2256     .deleteKey = DeleteKey,
2257     .aesGcmEncrypt = AesGcmEncrypt,
2258     .aesGcmDecrypt = AesGcmDecrypt,
2259     .hashToPoint = HashToPoint,
2260     .agreeSharedSecretWithStorage = AgreeSharedSecretWithStorage,
2261     .agreeSharedSecret = AgreeSharedSecret,
2262     .bigNumExpMod = BigNumExpMod,
2263     .generateKeyPairWithStorage = GenerateKeyPairWithStorage,
2264     .generateKeyPair = GenerateKeyPair,
2265     .exportPublicKey = ExportPublicKey,
2266     .sign = Sign,
2267     .verify = Verify,
2268     .importPublicKey = ImportPublicKey,
2269     .checkDlPublicKey = CheckDlPublicKey,
2270     .checkEcPublicKey = CheckEcPublicKey,
2271     .bigNumCompare = BigNumCompare,
2272     .base64Encode = MbedtlsBase64Encode,
2273     .base64Decode = MbedtlsBase64Decode
2274 };
2275 
GetRealLoaderInstance(void)2276 const AlgLoader *GetRealLoaderInstance(void)
2277 {
2278     return &g_huksLoader;
2279 }
2280