• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021-2025 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_utils.h"
18 
19 #include "huks_adapter_diff_impl.h"
20 #include "hc_log.h"
21 #include "mbedtls_ec_adapter.h"
22 #include "string_util.h"
23 
24 #define ECDH_COMMON_SIZE_P256 512
25 
26 static enum HksKeyAlg g_algToHksAlgorithm[] = {
27     HKS_ALG_ED25519,
28     HKS_ALG_X25519,
29     HKS_ALG_ECC,
30     HKS_ALG_AES,
31 };
32 
Sha256(const Uint8Buff * message,Uint8Buff * hash)33 static int32_t Sha256(const Uint8Buff *message, Uint8Buff *hash)
34 {
35     CHECK_PTR_RETURN_HAL_ERROR_CODE(message, "message");
36     CHECK_PTR_RETURN_HAL_ERROR_CODE(message->val, "message->val");
37     CHECK_LEN_ZERO_RETURN_ERROR_CODE(message->length, "message->length");
38 
39     CHECK_PTR_RETURN_HAL_ERROR_CODE(hash, "hash");
40     CHECK_PTR_RETURN_HAL_ERROR_CODE(hash->val, "hash->val");
41     CHECK_LEN_EQUAL_RETURN(hash->length, SHA256_LEN, "hash->length");
42 
43     struct HksBlob srcBlob = { message->length, message->val };
44     struct HksBlob hashBlob = { hash->length, hash->val };
45     struct HksParamSet *paramSet = NULL;
46     struct HksParam digestParam[] = {
47         {
48             .tag = HKS_TAG_DIGEST,
49             .uint32Param = HKS_DIGEST_SHA256
50         }
51     };
52     int32_t res = ConstructParamSet(&paramSet, digestParam, CAL_ARRAY_SIZE(digestParam));
53     if (res != HAL_SUCCESS) {
54         LOGE("construct param set failed, res = %" LOG_PUB "d", res);
55         return res;
56     }
57 
58     res = HksHash(paramSet, &srcBlob, &hashBlob);
59     if (res != HKS_SUCCESS || hashBlob.size != SHA256_LEN) {
60         LOGE("[HUKS]: HksHash fail. [Res]: %" LOG_PUB "d", res);
61         FreeParamSet(paramSet);
62         return HAL_ERR_HUKS;
63     }
64 
65     FreeParamSet(paramSet);
66     return HAL_SUCCESS;
67 }
68 
GenerateRandom(Uint8Buff * rand)69 static int32_t GenerateRandom(Uint8Buff *rand)
70 {
71     CHECK_PTR_RETURN_HAL_ERROR_CODE(rand, "rand");
72     CHECK_PTR_RETURN_HAL_ERROR_CODE(rand->val, "rand->val");
73     CHECK_LEN_ZERO_RETURN_ERROR_CODE(rand->length, "rand->length");
74 
75     struct HksBlob randBlob = { rand->length, rand->val };
76     int32_t res = HksGenerateRandom(NULL, &randBlob);
77     if (res != HKS_SUCCESS) {
78         LOGE("[HUKS]: HksGenerateRandom fail. [Res]: %" LOG_PUB "d", res);
79         return HAL_ERR_HUKS;
80     }
81 
82     return HAL_SUCCESS;
83 }
84 
CheckKeyExist(const Uint8Buff * keyAlias,bool isDeStorage,int32_t osAccountId)85 static int32_t CheckKeyExist(const Uint8Buff *keyAlias, bool isDeStorage, int32_t osAccountId)
86 {
87     CHECK_PTR_RETURN_HAL_ERROR_CODE(keyAlias, "keyAlias");
88     CHECK_PTR_RETURN_HAL_ERROR_CODE(keyAlias->val, "keyAlias->val");
89     CHECK_LEN_ZERO_RETURN_ERROR_CODE(keyAlias->length, "keyAlias->length");
90 
91     struct HksParamSet *deParamSet = NULL;
92     int32_t res = ConstructCheckParamSet(true, osAccountId, &deParamSet);
93     if (res != HAL_SUCCESS) {
94         return res;
95     }
96     struct HksParamSet *ceParamSet = NULL;
97     res = ConstructCheckParamSet(false, osAccountId, &ceParamSet);
98     if (res != HAL_SUCCESS) {
99         FreeParamSet(deParamSet);
100         return res;
101     }
102     struct HksBlob keyAliasBlob = { keyAlias->length, keyAlias->val };
103     if (isDeStorage) {
104         res = HksKeyExist(&keyAliasBlob, deParamSet);
105         if (res == HKS_SUCCESS) {
106             MoveDeKeyToCe(true, osAccountId, &keyAliasBlob);
107         } else {
108             res = HksKeyExist(&keyAliasBlob, ceParamSet);
109         }
110     } else {
111         res = HksKeyExist(&keyAliasBlob, ceParamSet);
112         if (res != HKS_SUCCESS) {
113             res = HksKeyExist(&keyAliasBlob, deParamSet);
114         }
115     }
116     FreeParamSet(deParamSet);
117     FreeParamSet(ceParamSet);
118 
119     if (res == HKS_ERROR_NOT_EXIST) {
120         LOGE("[HUKS]: Key not exist. [Res]: %" LOG_PUB "d", res);
121         return HAL_ERR_KEY_NOT_EXIST;
122     }
123     if (res != HKS_SUCCESS) {
124         LOGE("[HUKS]: HksKeyExist fail. [Res]: %" LOG_PUB "d", res);
125         return HAL_ERR_HUKS;
126     }
127 
128     return HAL_SUCCESS;
129 }
130 
DeleteKey(const Uint8Buff * keyAlias,bool isDeStorage,int32_t osAccountId)131 static int32_t DeleteKey(const Uint8Buff *keyAlias, bool isDeStorage, int32_t osAccountId)
132 {
133     CHECK_PTR_RETURN_HAL_ERROR_CODE(keyAlias, "keyAlias");
134     CHECK_PTR_RETURN_HAL_ERROR_CODE(keyAlias->val, "keyAlias->val");
135     CHECK_LEN_ZERO_RETURN_ERROR_CODE(keyAlias->length, "keyAlias->length");
136 
137     struct HksParamSet *deParamSet = NULL;
138     int32_t res = ConstructDeleteParamSet(true, osAccountId, &deParamSet);
139     if (res != HAL_SUCCESS) {
140         return res;
141     }
142     struct HksParamSet *ceParamSet = NULL;
143     res = ConstructDeleteParamSet(false, osAccountId, &ceParamSet);
144     if (res != HAL_SUCCESS) {
145         FreeParamSet(deParamSet);
146         return res;
147     }
148     struct HksBlob keyAliasBlob = { keyAlias->length, keyAlias->val };
149 
150     LOGI("[HUKS]: HksDeleteKey enter.");
151     if (isDeStorage) {
152         res = HksDeleteKey(&keyAliasBlob, deParamSet);
153         if (res != HKS_SUCCESS) {
154             res = HksDeleteKey(&keyAliasBlob, ceParamSet);
155         }
156     } else {
157         res = HksDeleteKey(&keyAliasBlob, ceParamSet);
158         if (res != HKS_SUCCESS) {
159             res = HksDeleteKey(&keyAliasBlob, deParamSet);
160         }
161     }
162     LOGI("[HUKS]: HksDeleteKey quit. [Res]: %" LOG_PUB "d", res);
163 
164     FreeParamSet(deParamSet);
165     FreeParamSet(ceParamSet);
166     if (res == HKS_ERROR_NOT_EXIST) {
167         LOGI("Key not exists.");
168         return HAL_SUCCESS;
169     }
170     if (res != HKS_SUCCESS) {
171         LOGE("[HUKS]: HksDeleteKey fail. [Res]: %" LOG_PUB "d", res);
172         return HAL_ERR_HUKS;
173     }
174     return HAL_SUCCESS;
175 }
176 
ComputeHmac(const KeyParams * keyParams,const Uint8Buff * message,Uint8Buff * outHmac)177 static int32_t ComputeHmac(const KeyParams *keyParams, const Uint8Buff *message, Uint8Buff *outHmac)
178 {
179     int32_t res = CheckHmacParams(keyParams, message, outHmac);
180     if (res != HAL_SUCCESS) {
181         return res;
182     }
183 
184     struct HksParamSet *deParamSet = NULL;
185     res = ConstructHmacParamSet(true, keyParams->osAccountId, keyParams->keyBuff.isAlias, &deParamSet);
186     if (res != HAL_SUCCESS) {
187         return res;
188     }
189     struct HksParamSet *ceParamSet = NULL;
190     res = ConstructHmacParamSet(false, keyParams->osAccountId, keyParams->keyBuff.isAlias, &ceParamSet);
191     if (res != HAL_SUCCESS) {
192         FreeParamSet(deParamSet);
193         return res;
194     }
195     struct HksBlob keyBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
196     struct HksBlob srcBlob = { message->length, message->val };
197     struct HksBlob hmacBlob = { outHmac->length, outHmac->val };
198 
199     LOGI("[HUKS]: HksMac enter.");
200     if (keyParams->isDeStorage) {
201         res = HksMac(&keyBlob, deParamSet, &srcBlob, &hmacBlob);
202     } else {
203         res = HksMac(&keyBlob, ceParamSet, &srcBlob, &hmacBlob);
204         if (res != HKS_SUCCESS  || hmacBlob.size != HMAC_LEN) {
205             res = HksMac(&keyBlob, deParamSet, &srcBlob, &hmacBlob);
206         }
207     }
208     LOGI("[HUKS]: HksMac quit. [Res]: %" LOG_PUB "d", res);
209     FreeParamSet(deParamSet);
210     FreeParamSet(ceParamSet);
211     if (res != HKS_SUCCESS  || hmacBlob.size != HMAC_LEN) {
212         LOGE("[HUKS]: HksMac fail. [Res]: %" LOG_PUB "d", res);
213         return HAL_ERR_HUKS;
214     }
215     return HAL_SUCCESS;
216 }
217 
DoAbortHks(struct HksBlob * handleDerive,struct HksParamSet * deriveParamSet)218 static void DoAbortHks(struct HksBlob *handleDerive, struct HksParamSet *deriveParamSet)
219 {
220     int32_t res = HksAbort(handleDerive, deriveParamSet);
221     if (res != HKS_SUCCESS) {
222         LOGE("Failed to abort huks, res:%" LOG_PUB "d", res);
223     }
224 }
225 
ComputeHmacWithThreeStageInner(const KeyParams * keyParams,const Uint8Buff * message,Uint8Buff * outHmac)226 static int32_t ComputeHmacWithThreeStageInner(const KeyParams *keyParams, const Uint8Buff *message, Uint8Buff *outHmac)
227 {
228     struct HksParamSet *deriveParamSet = NULL;
229     int32_t res = ConstructDeriveParamSet(keyParams, message, &deriveParamSet);
230     if (res != HAL_SUCCESS) {
231         return res;
232     }
233     struct HksParamSet *finishParamSet = NULL;
234     res = ConstructFinishParamSet(keyParams, &finishParamSet);
235     if (res != HAL_SUCCESS) {
236         FreeParamSet(deriveParamSet);
237         return res;
238     }
239     uint8_t handle[sizeof(uint64_t)] = { 0 };
240     struct HksBlob handleDerive = { sizeof(uint64_t), handle };
241     struct HksBlob keyAliasBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
242     uint8_t tmpOut[2048] = { 0 };
243     struct HksBlob outData = { 2048, tmpOut };
244     struct HksBlob inData = { 0, NULL };
245     struct HksBlob hmacBlob = { outHmac->length, outHmac->val };
246     do {
247         res = HksInit(&keyAliasBlob, deriveParamSet, &handleDerive, NULL);
248         if (res != HKS_SUCCESS) {
249             LOGE("Failed to init derive params!");
250             res = HAL_ERR_HUKS;
251             break;
252         }
253         res = HksUpdate(&handleDerive, deriveParamSet, &inData, &outData);
254         if (res != HKS_SUCCESS) {
255             LOGE("Failed to update derive params!");
256             DoAbortHks(&handleDerive, deriveParamSet);
257             res = HAL_ERR_HUKS;
258             break;
259         }
260         res = HksFinish(&handleDerive, finishParamSet, &inData, &hmacBlob);
261         if (res != HKS_SUCCESS || hmacBlob.size != HMAC_LEN) {
262             LOGE("Compute hmac with three stage failed! [Res]: %" LOG_PUB "d, [size]: %" LOG_PUB "d",
263                 res, hmacBlob.size);
264             DoAbortHks(&handleDerive, finishParamSet);
265             res = HAL_ERR_HUKS;
266             break;
267         }
268     } while (0);
269     FreeParamSet(deriveParamSet);
270     FreeParamSet(finishParamSet);
271     return res;
272 }
273 
ComputeHmacWithThreeStageIfKeyExist(const KeyParams * keyParams,const Uint8Buff * message,Uint8Buff * outHmac)274 static int32_t ComputeHmacWithThreeStageIfKeyExist(const KeyParams *keyParams, const Uint8Buff *message,
275     Uint8Buff *outHmac)
276 {
277     Uint8Buff keyAlias = { keyParams->keyBuff.key, keyParams->keyBuff.keyLen };
278     int32_t res = CheckKeyExist(&keyAlias, keyParams->isDeStorage, keyParams->osAccountId);
279     if (res != HAL_SUCCESS) {
280         LOGE("Huks key is not exist, [Res]: %" LOG_PUB "d", res);
281         return res;
282     }
283     return ComputeHmacWithThreeStageInner(keyParams, message, outHmac);
284 }
285 
ComputeHmacWithThreeStage(const KeyParams * keyParams,const Uint8Buff * message,Uint8Buff * outHmac)286 static int32_t ComputeHmacWithThreeStage(const KeyParams *keyParams, const Uint8Buff *message, Uint8Buff *outHmac)
287 {
288     int32_t res = CheckHmacWithThreeStageParams(keyParams, message, outHmac);
289     if (res != HAL_SUCCESS) {
290         return res;
291     }
292 
293     res = ComputeHmacWithThreeStageIfKeyExist(keyParams, message, outHmac);
294     if (!keyParams->isDeStorage) {
295         return res;
296     }
297     if (res == HAL_SUCCESS) {
298         struct HksBlob keyAliasBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
299         MoveDeKeyToCe(keyParams->keyBuff.isAlias, keyParams->osAccountId, &keyAliasBlob);
300     } else {
301         KeyParams ceParams = {
302             .keyBuff = { keyParams->keyBuff.key, keyParams->keyBuff.keyLen, keyParams->keyBuff.isAlias },
303             .isDeStorage = false,
304             .osAccountId = keyParams->osAccountId
305         };
306         res = ComputeHmacWithThreeStageIfKeyExist(&ceParams, message, outHmac);
307     }
308     return res;
309 }
310 
ComputeHkdf(const KeyParams * keyParams,const Uint8Buff * salt,const Uint8Buff * keyInfo,Uint8Buff * outHkdf)311 static int32_t ComputeHkdf(const KeyParams *keyParams, const Uint8Buff *salt, const Uint8Buff *keyInfo,
312     Uint8Buff *outHkdf)
313 {
314     int32_t res = CheckHkdfParams(keyParams, salt, outHkdf);
315     if (res != HAL_SUCCESS) {
316         return res;
317     }
318 
319     struct HksBlob srcKeyBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
320     struct HksBlob derivedKeyBlob = { outHkdf->length, outHkdf->val };
321 
322     struct HksParamSet *deParamSet = NULL;
323     res = ConstructHkdfParamSet(true, keyParams, salt, keyInfo, &deParamSet);
324     if (res != HAL_SUCCESS) {
325         return res;
326     }
327     struct HksParamSet *ceParamSet = NULL;
328     res = ConstructHkdfParamSet(false, keyParams, salt, keyInfo, &ceParamSet);
329     if (res != HAL_SUCCESS) {
330         FreeParamSet(deParamSet);
331         return res;
332     }
333 
334     LOGI("[HUKS]: HksDeriveKey enter.");
335     if (keyParams->isDeStorage) {
336         res = HksDeriveKey(deParamSet, &srcKeyBlob, &derivedKeyBlob);
337         if (res == HKS_SUCCESS) {
338             MoveDeKeyToCe(keyParams->keyBuff.isAlias, keyParams->osAccountId, &srcKeyBlob);
339         } else {
340             res = HksDeriveKey(ceParamSet, &srcKeyBlob, &derivedKeyBlob);
341         }
342     } else {
343         res = HksDeriveKey(ceParamSet, &srcKeyBlob, &derivedKeyBlob);
344         if (res != HKS_SUCCESS) {
345             res = HksDeriveKey(deParamSet, &srcKeyBlob, &derivedKeyBlob);
346         }
347     }
348     LOGI("[HUKS]: HksDeriveKey quit. [Res]: %" LOG_PUB "d", res);
349     FreeParamSet(deParamSet);
350     FreeParamSet(ceParamSet);
351     if (res != HKS_SUCCESS) {
352         LOGE("[HUKS]: HksDeriveKey fail. [Res]: %" LOG_PUB "d", res);
353         return HAL_ERR_HUKS;
354     }
355     return HAL_SUCCESS;
356 }
357 
ComputePseudonymPskInner(const KeyParams * keyParams,const Uint8Buff * pskKeyAlias,const Uint8Buff * extInfo,Uint8Buff * outPsk)358 static int32_t ComputePseudonymPskInner(const KeyParams *keyParams, const Uint8Buff *pskKeyAlias,
359     const Uint8Buff *extInfo, Uint8Buff *outPsk)
360 {
361     struct HksBlob srcKeyBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
362     struct HksBlob derivedKeyBlob = { outPsk->length, outPsk->val };
363     struct HksBlob extInfoBlob = { 0, NULL };
364     if (extInfo != NULL) {
365         extInfoBlob.data = extInfo->val;
366         extInfoBlob.size = extInfo->length;
367     }
368     struct HksParamSet *paramSet = NULL;
369     int32_t res = ConstructPseudonymParamSet(keyParams, pskKeyAlias, &extInfoBlob, outPsk->length, &paramSet);
370     if (res != HAL_SUCCESS) {
371         LOGE("Construct param set failed!");
372         return res;
373     }
374 
375     LOGI("[HUKS]: HksDeriveKey enter.");
376     res = HksDeriveKey(paramSet, &srcKeyBlob, &derivedKeyBlob);
377     FreeParamSet(paramSet);
378     LOGI("[HUKS]: HksDeriveKey quit. [Res]: %" LOG_PUB "d", res);
379     if (res != HKS_SUCCESS) {
380         LOGE("[HUKS]: HksDeriveKey fail. [Res]: %" LOG_PUB "d", res);
381         return HAL_ERR_HUKS;
382     }
383     return HAL_SUCCESS;
384 }
385 
386 // pseudonym psk alias:sha256(serviceType bytes+peerAuthId bytes+{0x00, 0x07})
ComputePseudonymPsk(const KeyParams * keyParams,const Uint8Buff * pskKeyAlias,const Uint8Buff * extInfo,Uint8Buff * outPsk)387 static int32_t ComputePseudonymPsk(const KeyParams *keyParams, const Uint8Buff *pskKeyAlias,
388     const Uint8Buff *extInfo, Uint8Buff *outPsk)
389 {
390     int32_t res = CheckPskParams(keyParams, pskKeyAlias, outPsk);
391     if (res != HAL_SUCCESS) {
392         return res;
393     }
394 
395     res = ComputePseudonymPskInner(keyParams, pskKeyAlias, extInfo, outPsk);
396     if (!keyParams->isDeStorage) {
397         return res;
398     }
399     if (res == HAL_SUCCESS) {
400         struct HksBlob keyAliasBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
401         MoveDeKeyToCe(keyParams->keyBuff.isAlias, keyParams->osAccountId, &keyAliasBlob);
402     } else {
403         KeyParams ceParams = {
404             .keyBuff = { keyParams->keyBuff.key, keyParams->keyBuff.keyLen, keyParams->keyBuff.isAlias },
405             .isDeStorage = false,
406             .osAccountId = keyParams->osAccountId
407         };
408         res = ComputePseudonymPskInner(&ceParams, pskKeyAlias, extInfo, outPsk);
409     }
410     return res;
411 }
412 
ConstructOutParamSet(struct HksParamSet ** outParamSet)413 static int32_t ConstructOutParamSet(struct HksParamSet **outParamSet)
414 {
415     int32_t res = HksInitParamSet(outParamSet);
416     if (res != HKS_SUCCESS) {
417         LOGE("init out param set failed, res = %" LOG_PUB "d", res);
418         return HAL_ERR_INIT_PARAM_SET_FAILED;
419     }
420 
421     uint32_t outParamSetSize = 2048;
422     uint8_t *blobVal = (uint8_t *)HcMalloc(outParamSetSize, 0);
423     if (blobVal == NULL) {
424         LOGE("Failed to alloc memory for out blob value!");
425         HksFreeParamSet(outParamSet);
426         return HAL_ERR_BAD_ALLOC;
427     }
428     struct HksParam getParam = {
429         .tag = HKS_TAG_SYMMETRIC_KEY_DATA,
430         .blob = { .size = outParamSetSize, .data = blobVal }
431     };
432 
433     res = HksAddParams(*outParamSet, &getParam, 1);
434     if (res != HKS_SUCCESS) {
435         LOGE("Failed to add param!");
436         HksFreeParamSet(outParamSet);
437         HcFree(blobVal);
438         return HAL_ERR_ADD_PARAM_FAILED;
439     }
440 
441     res = HksBuildParamSet(outParamSet);
442     HcFree(blobVal);
443     if (res != HKS_SUCCESS) {
444         LOGE("build param set failed, res = %" LOG_PUB "d", res);
445         HksFreeParamSet(outParamSet);
446         return HAL_ERR_BUILD_PARAM_SET_FAILED;
447     }
448     return HAL_SUCCESS;
449 }
450 
GetKeyExtInfoInner(const KeyParams * keyParams,Uint8Buff * outExtInfo)451 static int32_t GetKeyExtInfoInner(const KeyParams *keyParams, Uint8Buff *outExtInfo)
452 {
453     struct HksParamSet *paramSet = NULL;
454     int32_t res = ConstructGetKeyExtInfoParamSet(keyParams, &paramSet);
455     if (res != HAL_SUCCESS) {
456         return res;
457     }
458     struct HksParamSet *outParamSet = NULL;
459     res = ConstructOutParamSet(&outParamSet);
460     if (res != HAL_SUCCESS) {
461         FreeParamSet(paramSet);
462         return res;
463     }
464     struct HksBlob keyAliasBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
465     res = HksGetKeyParamSet(&keyAliasBlob, paramSet, outParamSet);
466     FreeParamSet(paramSet);
467     if (res != HKS_SUCCESS) {
468         LOGE("Failed to get key param set!");
469         FreeParamSet(outParamSet);
470         return HAL_ERR_HUKS;
471     }
472     res = GetExtInfoByParamSet(outParamSet, outExtInfo);
473     FreeParamSet(outParamSet);
474     return res;
475 }
476 
GetKeyExtInfo(const KeyParams * keyParams,Uint8Buff * outExtInfo)477 static int32_t GetKeyExtInfo(const KeyParams *keyParams, Uint8Buff *outExtInfo)
478 {
479     int32_t res = CheckKeyParams(keyParams);
480     if (res != HAL_SUCCESS) {
481         return res;
482     }
483     if (outExtInfo == NULL) {
484         LOGE("outExtInfo is null!");
485         return HAL_ERR_NULL_PTR;
486     }
487 
488     res = GetKeyExtInfoInner(keyParams, outExtInfo);
489     if (!keyParams->isDeStorage) {
490         return res;
491     }
492     if (res == HAL_SUCCESS) {
493         struct HksBlob keyAliasBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
494         MoveDeKeyToCe(keyParams->keyBuff.isAlias, keyParams->osAccountId, &keyAliasBlob);
495     } else {
496         KeyParams ceParams = {
497             .keyBuff = { keyParams->keyBuff.key, keyParams->keyBuff.keyLen, keyParams->keyBuff.isAlias },
498             .isDeStorage = false,
499             .osAccountId = keyParams->osAccountId
500         };
501         res = GetKeyExtInfoInner(&ceParams, outExtInfo);
502     }
503     return res;
504 }
505 
AesGcmEncrypt(const KeyParams * keyParams,const Uint8Buff * plain,const GcmParam * encryptInfo,Uint8Buff * outCipher)506 static int32_t AesGcmEncrypt(const KeyParams *keyParams, const Uint8Buff *plain, const GcmParam *encryptInfo,
507     Uint8Buff *outCipher)
508 {
509     int32_t res = CheckAesGcmEncryptParam(keyParams, plain, encryptInfo, outCipher);
510     if (res != HAL_SUCCESS) {
511         return res;
512     }
513 
514     struct HksBlob keyBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
515     struct HksBlob plainBlob = { plain->length, plain->val };
516     struct HksBlob cipherBlob = { outCipher->length, outCipher->val };
517 
518     struct HksParamSet *paramSet = NULL;
519     res = ConstructAesGcmEncryptParamSet(encryptInfo, keyParams, &paramSet);
520     if (res != HAL_SUCCESS) {
521         return res;
522     }
523 
524     LOGI("[HUKS]: HksEncrypt enter.");
525     res = HksEncrypt(&keyBlob, paramSet, &plainBlob, &cipherBlob);
526     FreeParamSet(paramSet);
527     LOGI("[HUKS]: HksEncrypt quit. [Res]: %" LOG_PUB "d", res);
528     if (res != HKS_SUCCESS) {
529         LOGE("[HUKS]: HksEncrypt fail. [Res]: %" LOG_PUB "d", res);
530         return HAL_ERR_HUKS;
531     }
532     return HAL_SUCCESS;
533 }
534 
AesGcmDecrypt(const KeyParams * keyParams,const Uint8Buff * cipher,const GcmParam * decryptInfo,Uint8Buff * outPlain)535 static int32_t AesGcmDecrypt(const KeyParams *keyParams, const Uint8Buff *cipher, const GcmParam *decryptInfo,
536     Uint8Buff *outPlain)
537 {
538     int32_t res = CheckAesGcmDecryptParam(keyParams, cipher, decryptInfo, outPlain);
539     if (res != HAL_SUCCESS) {
540         return res;
541     }
542 
543     struct HksBlob keyBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
544     struct HksBlob cipherBlob = { cipher->length, cipher->val };
545     struct HksBlob plainBlob = { outPlain->length, outPlain->val };
546 
547     struct HksParamSet *paramSet = NULL;
548     res = ConstructAesGcmDecryptParamSet(decryptInfo, keyParams, &paramSet);
549     if (res != HAL_SUCCESS) {
550         return res;
551     }
552 
553     LOGI("[HUKS]: HksDecrypt enter.");
554     res = HksDecrypt(&keyBlob, paramSet, &cipherBlob, &plainBlob);
555     FreeParamSet(paramSet);
556     LOGI("[HUKS]: HksDecrypt quit. [Res]: %" LOG_PUB "d", res);
557     if (res != HKS_SUCCESS) {
558         LOGE("[HUKS]: HksDecrypt fail. [Res]: %" LOG_PUB "d", res);
559         return HAL_ERR_HUKS;
560     }
561     return HAL_SUCCESS;
562 }
563 
HashToPoint(const Uint8Buff * hash,Algorithm algo,Uint8Buff * outEcPoint)564 static int32_t HashToPoint(const Uint8Buff *hash, Algorithm algo, Uint8Buff *outEcPoint)
565 {
566     CHECK_PTR_RETURN_HAL_ERROR_CODE(hash, "hash");
567     CHECK_PTR_RETURN_HAL_ERROR_CODE(hash->val, "hash->val");
568     CHECK_LEN_EQUAL_RETURN(hash->length, SHA256_LEN, "hash->length");
569     CHECK_PTR_RETURN_HAL_ERROR_CODE(outEcPoint, "outEcPoint");
570     CHECK_PTR_RETURN_HAL_ERROR_CODE(outEcPoint->val, "outEcPoint->val");
571 
572     if (algo != X25519 && algo != P256) {
573         LOGE("Compute algo: %" LOG_PUB "d.", algo);
574         return HAL_ERR_INVALID_PARAM;
575     }
576     if (algo == P256) {
577         LOGI("Compute HashToPoint for P256");
578         return MbedtlsHashToPoint(hash, outEcPoint);
579     }
580 
581     CHECK_LEN_EQUAL_RETURN(outEcPoint->length, SHA256_LEN, "outEcPoint->length");
582     return HashToPointX25519(hash, outEcPoint);
583 }
584 
AgreeSharedSecretWithStorageP256(const KeyParams * priKeyParams,const KeyBuff * pubKeyBuff,const struct HksBlob * sharedKeyAliasBlob)585 static int32_t AgreeSharedSecretWithStorageP256(const KeyParams *priKeyParams, const KeyBuff *pubKeyBuff,
586     const struct HksBlob *sharedKeyAliasBlob)
587 {
588     struct HksParamSet *initParamSet = NULL;
589     struct HksParamSet *finishParamSet = NULL;
590     int32_t res = ConstructInitParamsP256(&initParamSet, priKeyParams);
591     if (res != HAL_SUCCESS) {
592         return res;
593     }
594     res = ConstructFinishParamsP256(&finishParamSet, priKeyParams, sharedKeyAliasBlob);
595     if (res != HAL_SUCCESS) {
596         FreeParamSet(initParamSet);
597         return res;
598     }
599     struct HksBlob priKeyAliasBlob = { priKeyParams->keyBuff.keyLen, priKeyParams->keyBuff.key };
600     struct HksBlob pubKeyBlob = { pubKeyBuff->keyLen, pubKeyBuff->key };
601     uint8_t handle[sizeof(uint64_t)] = { 0 };
602     struct HksBlob handleBlob = { sizeof(uint64_t), handle };
603     uint8_t outDataUpdate[ECDH_COMMON_SIZE_P256] = { 0 };
604     struct HksBlob outDataUpdateBlob = { ECDH_COMMON_SIZE_P256, outDataUpdate };
605     uint8_t outDataFinish[ECDH_COMMON_SIZE_P256] = { 0 };
606     struct HksBlob outDataFinishBlob = { ECDH_COMMON_SIZE_P256, outDataFinish };
607     do {
608         res = HksInit(&priKeyAliasBlob, initParamSet, &handleBlob, NULL);
609         if (res != HKS_SUCCESS) {
610             LOGE("Huks agree P256 key: HksInit failed, res = %" LOG_PUB "d", res);
611             res = HAL_ERR_HUKS;
612             break;
613         }
614         res = HksUpdate(&handleBlob, initParamSet, &pubKeyBlob, &outDataUpdateBlob);
615         if (res != HKS_SUCCESS) {
616             LOGE("Huks agree P256 key: HksUpdate failed, res = %" LOG_PUB "d", res);
617             DoAbortHks(&handleBlob, initParamSet);
618             res = HAL_ERR_HUKS;
619             break;
620         }
621         LOGI("[HUKS]: HksFinish enter.");
622         res = HksFinish(&handleBlob, finishParamSet, &pubKeyBlob, &outDataFinishBlob);
623         LOGI("[HUKS]: HksFinish quit. [Res]: %" LOG_PUB "d", res);
624         if (res != HKS_SUCCESS) {
625             LOGE("[HUKS]: HksFinish fail. [Res]: %" LOG_PUB "d", res);
626             DoAbortHks(&handleBlob, finishParamSet);
627             res = HAL_ERR_HUKS;
628             break;
629         }
630     } while (0);
631     FreeParamSet(initParamSet);
632     FreeParamSet(finishParamSet);
633     return res;
634 }
635 
AgreeSharedSecretIfKeyExist(const KeyParams * priKeyParams,const KeyBuff * pubKeyBuff,struct HksBlob * sharedKeyAliasBlob)636 static int32_t AgreeSharedSecretIfKeyExist(const KeyParams *priKeyParams, const KeyBuff *pubKeyBuff,
637     struct HksBlob *sharedKeyAliasBlob)
638 {
639     Uint8Buff keyAlias = { priKeyParams->keyBuff.key, priKeyParams->keyBuff.keyLen };
640     int32_t res = CheckKeyExist(&keyAlias, priKeyParams->isDeStorage, priKeyParams->osAccountId);
641     if (res != HAL_SUCCESS) {
642         LOGE("Huks key is not exist, [Res]: %" LOG_PUB "d", res);
643         return res;
644     }
645     return AgreeSharedSecretWithStorageP256(priKeyParams, pubKeyBuff, sharedKeyAliasBlob);
646 }
647 
AgreeSharedSecretWithStorage(const KeyParams * priKeyParams,const KeyBuff * pubKeyBuff,Algorithm algo,uint32_t sharedKeyLen,const Uint8Buff * sharedKeyAlias)648 static int32_t AgreeSharedSecretWithStorage(const KeyParams *priKeyParams, const KeyBuff *pubKeyBuff,
649     Algorithm algo, uint32_t sharedKeyLen, const Uint8Buff *sharedKeyAlias)
650 {
651     int32_t res = CheckAgreeWithStorageParams(priKeyParams, pubKeyBuff, sharedKeyLen, sharedKeyAlias);
652     if (res != HAL_SUCCESS) {
653         return res;
654     }
655 
656     struct HksBlob sharedKeyAliasBlob = { sharedKeyAlias->length, sharedKeyAlias->val };
657     if (g_algToHksAlgorithm[algo] == HKS_ALG_ECC) {
658         LOGI("Hks agree key with storage for P256.");
659         return AgreeSharedSecretIfKeyExist(priKeyParams, pubKeyBuff, &sharedKeyAliasBlob);
660     }
661     struct HksParamSet *deParamSet = NULL;
662     KeyParams keyParams = {
663         .keyBuff = { priKeyParams->keyBuff.key, priKeyParams->keyBuff.keyLen, priKeyParams->keyBuff.isAlias },
664         .isDeStorage = true,
665         .osAccountId = priKeyParams->osAccountId
666     };
667     res = ConstructAgreeWithStorageParams(&deParamSet, sharedKeyLen, algo, &keyParams, pubKeyBuff);
668     if (res != HAL_SUCCESS) {
669         return res;
670     }
671     struct HksParamSet *ceParamSet = NULL;
672     keyParams.isDeStorage = false;
673     res = ConstructAgreeWithStorageParams(&ceParamSet, sharedKeyLen, algo, &keyParams, pubKeyBuff);
674     if (res != HAL_SUCCESS) {
675         FreeParamSet(deParamSet);
676         return res;
677     }
678 
679     LOGI("[HUKS]: HksGenerateKey enter.");
680     if (priKeyParams->isDeStorage) {
681         res = HksGenerateKey(&sharedKeyAliasBlob, deParamSet, NULL);
682         if (res == HKS_SUCCESS) {
683             MoveSharedKeyToCe(priKeyParams, &sharedKeyAliasBlob);
684         } else {
685             res = HksGenerateKey(&sharedKeyAliasBlob, ceParamSet, NULL);
686         }
687     } else {
688         res = HksGenerateKey(&sharedKeyAliasBlob, ceParamSet, NULL);
689         if (res != HKS_SUCCESS) {
690             res = HksGenerateKey(&sharedKeyAliasBlob, deParamSet, NULL);
691         }
692     }
693     LOGI("[HUKS]: HksGenerateKey quit. [Res]: %" LOG_PUB "d", res);
694     FreeParamSet(deParamSet);
695     FreeParamSet(ceParamSet);
696     if (res != HKS_SUCCESS) {
697         LOGE("[HUKS]: HksGenerateKey fail. [Res]: %" LOG_PUB "d", res);
698         return HAL_ERR_HUKS;
699     }
700     return HAL_SUCCESS;
701 }
702 
AgreeSharedSecret(const KeyParams * priKeyParams,const KeyBuff * pubKey,Algorithm algo,Uint8Buff * sharedKey)703 static int32_t AgreeSharedSecret(const KeyParams *priKeyParams, const KeyBuff *pubKey, Algorithm algo,
704     Uint8Buff *sharedKey)
705 {
706     int32_t res = CheckAgreeParams(priKeyParams, pubKey, sharedKey);
707     if (res != HAL_SUCCESS) {
708         return res;
709     }
710 
711     if (g_algToHksAlgorithm[algo] == HKS_ALG_ECC) {
712         LOGI("Hks agree key for P256.");
713         KeyBuff priKey = { priKeyParams->keyBuff.key, priKeyParams->keyBuff.keyLen, priKeyParams->keyBuff.isAlias };
714         return MbedtlsAgreeSharedSecret(&priKey, pubKey, sharedKey);
715     }
716 
717     struct HksBlob priKeyBlob = { priKeyParams->keyBuff.keyLen, priKeyParams->keyBuff.key };
718     struct HksBlob pubKeyBlob = { pubKey->keyLen, pubKey->key };
719     struct HksBlob sharedKeyBlob = { sharedKey->length, sharedKey->val };
720 
721     struct HksParamSet *paramSet = NULL;
722     res = ConstructAgreeParamSet(priKeyParams, algo, sharedKey, &paramSet);
723     if (res != HAL_SUCCESS) {
724         return res;
725     }
726 
727     LOGI("[HUKS]: HksAgreeKey enter.");
728     res = HksAgreeKey(paramSet, &priKeyBlob, &pubKeyBlob, &sharedKeyBlob);
729     FreeParamSet(paramSet);
730     LOGI("[HUKS]: HksAgreeKey quit. [Res]: %" LOG_PUB "d", res);
731     if (res != HKS_SUCCESS) {
732         LOGE("[HUKS]: HksAgreeKey fail. [Res]: %" LOG_PUB "d", res);
733         return HAL_ERR_HUKS;
734     }
735     return HAL_SUCCESS;
736 }
737 
GenerateKeyPairWithStorage(const KeyParams * keyParams,uint32_t keyLen,Algorithm algo,KeyPurpose purpose,const ExtraInfo * exInfo)738 static int32_t GenerateKeyPairWithStorage(const KeyParams *keyParams, uint32_t keyLen, Algorithm algo,
739     KeyPurpose purpose, const ExtraInfo *exInfo)
740 {
741     int32_t res = CheckGenerateKeyPairParams(keyParams, exInfo, keyLen);
742     if (res != HAL_SUCCESS) {
743         return res;
744     }
745 
746     KeyParams authIdParams = {
747         .keyBuff = { exInfo->authId.val, exInfo->authId.length, true },
748         .isDeStorage = keyParams->isDeStorage,
749         .osAccountId = keyParams->osAccountId
750     };
751     struct HksParamSet *paramSet = NULL;
752     res = ConstructGenerateKeyPairWithStorageParams(&paramSet, algo, keyLen, purpose, &authIdParams);
753     if (res != HAL_SUCCESS) {
754         return res;
755     }
756     struct HksBlob keyAliasBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
757 
758     LOGI("[HUKS]: HksGenerateKey enter.");
759     res = HksGenerateKey(&keyAliasBlob, paramSet, NULL);
760     FreeParamSet(paramSet);
761     LOGI("[HUKS]: HksGenerateKey quit. [Res]: %" LOG_PUB "d", res);
762     if (res != HKS_SUCCESS) {
763         LOGE("[HUKS]: HksGenerateKey fail. [Res]: %" LOG_PUB "d", res);
764         return HAL_ERR_HUKS;
765     }
766     return HAL_SUCCESS;
767 }
768 
GetKeyPair(struct HksParamSet * outParamSet,Uint8Buff * outPriKey,Uint8Buff * outPubKey)769 static int32_t GetKeyPair(struct HksParamSet *outParamSet, Uint8Buff *outPriKey, Uint8Buff *outPubKey)
770 {
771     int32_t res = HksFreshParamSet(outParamSet, false); /* false means fresh by local, not through IPC */
772     if (res != HKS_SUCCESS) {
773         LOGE("fresh param set failed, res:%" LOG_PUB "d", res);
774         return HAL_ERR_FRESH_PARAM_SET_FAILED;
775     }
776 
777     struct HksParam *pubKeyParam = NULL;
778     res = HksGetParam(outParamSet, HKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA, &pubKeyParam);
779     if (res != HKS_SUCCESS) {
780         LOGE("get pub key from param set failed, res:%" LOG_PUB "d", res);
781         return HAL_ERR_GET_PARAM_FAILED;
782     }
783 
784     struct HksParam *priKeyParam = NULL;
785     res = HksGetParam(outParamSet, HKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA, &priKeyParam);
786     if (res != HKS_SUCCESS) {
787         LOGE("get priv key from param set failed, res:%" LOG_PUB "d", res);
788         return HAL_ERR_GET_PARAM_FAILED;
789     }
790 
791     if (memcpy_s(outPubKey->val, outPubKey->length, pubKeyParam->blob.data, pubKeyParam->blob.size) != EOK) {
792         LOGE("parse x25519 output param set memcpy public key failed!");
793         return HAL_ERR_MEMORY_COPY;
794     }
795     outPubKey->length = pubKeyParam->blob.size;
796 
797     if (memcpy_s(outPriKey->val, outPriKey->length, priKeyParam->blob.data, priKeyParam->blob.size) != EOK) {
798         LOGE("parse x25519 output param set memcpy private key failed!");
799         return HAL_ERR_MEMORY_COPY;
800     }
801     outPriKey->length = priKeyParam->blob.size;
802 
803     return HAL_SUCCESS;
804 }
805 
GenerateKeyPair(Algorithm algo,Uint8Buff * outPriKey,Uint8Buff * outPubKey)806 static int32_t GenerateKeyPair(Algorithm algo, Uint8Buff *outPriKey, Uint8Buff *outPubKey)
807 {
808     CHECK_PTR_RETURN_HAL_ERROR_CODE(outPriKey, "outPriKey");
809     CHECK_PTR_RETURN_HAL_ERROR_CODE(outPriKey->val, "outPriKey->key");
810     CHECK_LEN_ZERO_RETURN_ERROR_CODE(outPriKey->length, "outPriKey->keyLen");
811     CHECK_PTR_RETURN_HAL_ERROR_CODE(outPubKey, "outPubKey");
812     CHECK_PTR_RETURN_HAL_ERROR_CODE(outPubKey->val, "outPubKey->key");
813     CHECK_LEN_ZERO_RETURN_ERROR_CODE(outPubKey->length, "outPubKey->keyLen");
814 
815     if (outPriKey->length != outPubKey->length) {
816         LOGE("key len not equal.");
817         return HAL_ERR_INVALID_LEN;
818     }
819     uint32_t keyLen = outPriKey->length;
820 
821     struct HksParamSet *paramSet = NULL;
822     struct HksParamSet *outParamSet = NULL;
823     int32_t res = ConstructGenerateKeyPairParams(&paramSet, algo, keyLen);
824     if (res != HAL_SUCCESS) {
825         return res;
826     }
827 
828     /* need 2 HksParam struct for outPriKey and outPubKey */
829     uint32_t outParamSetSize = sizeof(struct HksParamSet) +
830         2 * (sizeof(struct HksParam)) + outPriKey->length + outPubKey->length;
831     outParamSet = (struct HksParamSet *)HcMalloc(outParamSetSize, 0);
832     if (outParamSet == NULL) {
833         LOGE("allocate buffer for output param set failed");
834         res = HAL_ERR_BAD_ALLOC;
835         goto ERR;
836     }
837     outParamSet->paramSetSize = outParamSetSize;
838 
839     LOGI("[HUKS]: HksGenerateKey enter.");
840     res = HksGenerateKey(NULL, paramSet, outParamSet);
841     LOGI("[HUKS]: HksGenerateKey quit. [Res]: %" LOG_PUB "d", res);
842     if (res != HKS_SUCCESS) {
843         LOGI("[HUKS]: HksGenerateKey quit. [Res]: %" LOG_PUB "d", res);
844         res = HAL_ERR_HUKS;
845         goto ERR;
846     }
847 
848     res = GetKeyPair(outParamSet, outPriKey, outPubKey);
849     if (res != HAL_SUCCESS) {
850         LOGE("parse x25519 output param set failed, res:%" LOG_PUB "d", res);
851         goto ERR;
852     }
853 ERR:
854     FreeParamSet(paramSet);
855     HcFree(outParamSet);
856     return res;
857 }
858 
ExportPublicKey(const KeyParams * keyParams,Uint8Buff * outPubKey)859 static int32_t ExportPublicKey(const KeyParams *keyParams, Uint8Buff *outPubKey)
860 {
861     int32_t res = CheckExportParams(keyParams, outPubKey);
862     if (res != HAL_SUCCESS) {
863         return res;
864     }
865 
866     struct HksParamSet *deParamSet = NULL;
867     res = ConstructExportParams(true, keyParams->osAccountId, &deParamSet);
868     if (res != HAL_SUCCESS) {
869         return res;
870     }
871     struct HksParamSet *ceParamSet = NULL;
872     res = ConstructExportParams(false, keyParams->osAccountId, &ceParamSet);
873     if (res != HAL_SUCCESS) {
874         FreeParamSet(deParamSet);
875         return res;
876     }
877     struct HksBlob keyAliasBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
878     struct HksBlob keyBlob = { outPubKey->length, outPubKey->val };
879 
880     LOGI("[HUKS]: HksExportPublicKey enter.");
881     if (keyParams->isDeStorage) {
882         res = HksExportPublicKey(&keyAliasBlob, deParamSet, &keyBlob);
883         if (res == HKS_SUCCESS) {
884             MoveDeKeyToCe(true, keyParams->osAccountId, &keyAliasBlob);
885         } else {
886             res = HksExportPublicKey(&keyAliasBlob, ceParamSet, &keyBlob);
887         }
888     } else {
889         res = HksExportPublicKey(&keyAliasBlob, ceParamSet, &keyBlob);
890         if (res != HKS_SUCCESS) {
891             res = HksExportPublicKey(&keyAliasBlob, deParamSet, &keyBlob);
892         }
893     }
894     LOGI("[HUKS]: HksExportPublicKey quit. [Res]: %" LOG_PUB "d", res);
895     FreeParamSet(deParamSet);
896     FreeParamSet(ceParamSet);
897     if (res != HKS_SUCCESS) {
898         LOGE("[HUKS]: HksExportPublicKey failed. [Res]: %" LOG_PUB "d", res);
899         return HAL_ERR_HUKS;
900     }
901     outPubKey->length = keyBlob.size;
902     return HAL_SUCCESS;
903 }
904 
Sign(const KeyParams * keyParams,const Uint8Buff * message,Algorithm algo,Uint8Buff * outSignature)905 static int32_t Sign(const KeyParams *keyParams, const Uint8Buff *message, Algorithm algo,
906     Uint8Buff *outSignature)
907 {
908     int32_t res = CheckSignParams(keyParams, message, outSignature);
909     if (res != HAL_SUCCESS) {
910         return res;
911     }
912 
913     uint8_t messageHashVal[SHA256_LEN] = { 0 };
914     Uint8Buff messageHash = { messageHashVal, SHA256_LEN };
915     res = Sha256(message, &messageHash);
916     if (res != HAL_SUCCESS) {
917         LOGE("The operation of Sha256 failed.");
918         return res;
919     }
920     struct HksParamSet *deParamSet = NULL;
921     res = ConstructSignParams(true, keyParams->osAccountId, &deParamSet, algo);
922     if (res != HAL_SUCCESS) {
923         return res;
924     }
925     struct HksParamSet *ceParamSet = NULL;
926     res = ConstructSignParams(false, keyParams->osAccountId, &ceParamSet, algo);
927     if (res != HAL_SUCCESS) {
928         FreeParamSet(deParamSet);
929         return res;
930     }
931     struct HksBlob keyAliasBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
932     struct HksBlob messageBlob = { messageHash.length, messageHash.val };
933     struct HksBlob signatureBlob = { outSignature->length, outSignature->val };
934 
935     LOGI("[HUKS]: HksSign enter.");
936     if (keyParams->isDeStorage) {
937         res = HksSign(&keyAliasBlob, deParamSet, &messageBlob, &signatureBlob);
938         if (res == HKS_SUCCESS) {
939             MoveDeKeyToCe(keyParams->keyBuff.isAlias, keyParams->osAccountId, &keyAliasBlob);
940         } else {
941             res = HksSign(&keyAliasBlob, ceParamSet, &messageBlob, &signatureBlob);
942         }
943     } else {
944         res = HksSign(&keyAliasBlob, ceParamSet, &messageBlob, &signatureBlob);
945         if (res != HKS_SUCCESS) {
946             res = HksSign(&keyAliasBlob, deParamSet, &messageBlob, &signatureBlob);
947         }
948     }
949     LOGI("[HUKS]: HksSign quit. [Res]: %" LOG_PUB "d", res);
950     FreeParamSet(deParamSet);
951     FreeParamSet(ceParamSet);
952     if (res != HKS_SUCCESS) {
953         LOGE("[HUKS]: HksSign fail. [Res]: %" LOG_PUB "d", res);
954         return HAL_ERR_HUKS;
955     }
956     outSignature->length = signatureBlob.size;
957     return HAL_SUCCESS;
958 }
959 
Verify(const KeyParams * keyParams,const Uint8Buff * message,Algorithm algo,const Uint8Buff * signature)960 static int32_t Verify(const KeyParams *keyParams, const Uint8Buff *message, Algorithm algo,
961     const Uint8Buff *signature)
962 {
963     int32_t res = CheckVerifyParams(keyParams, message, signature);
964     if (res != HAL_SUCCESS) {
965         return res;
966     }
967 
968     uint8_t messageHashVal[SHA256_LEN] = { 0 };
969     Uint8Buff messageHash = { messageHashVal, SHA256_LEN };
970     res = Sha256(message, &messageHash);
971     if (res != HAL_SUCCESS) {
972         LOGE("Sha256 failed.");
973         return res;
974     }
975 
976     struct HksParamSet *paramSet = NULL;
977     res = ConstructVerifyParams(&paramSet, keyParams, algo);
978     if (res != HAL_SUCCESS) {
979         return res;
980     }
981     struct HksBlob keyAliasBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
982     struct HksBlob messageBlob = { messageHash.length, messageHash.val };
983     struct HksBlob signatureBlob = { signature->length, signature->val };
984 
985     LOGI("[HUKS]: HksVerify enter.");
986     res = HksVerify(&keyAliasBlob, paramSet, &messageBlob, &signatureBlob);
987     FreeParamSet(paramSet);
988     LOGI("[HUKS]: HksVerify quit. [Res]: %" LOG_PUB "d", res);
989     if ((res != HKS_SUCCESS)) {
990         LOGE("[HUKS]: HksVerify fail. [Res]: %" LOG_PUB "d", res);
991         return HAL_ERR_HUKS;
992     }
993     return HAL_SUCCESS;
994 }
995 
ImportPublicKey(const KeyParams * keyParams,const Uint8Buff * pubKey,Algorithm algo,const ExtraInfo * exInfo)996 static int32_t ImportPublicKey(const KeyParams *keyParams, const Uint8Buff *pubKey, Algorithm algo,
997     const ExtraInfo *exInfo)
998 {
999     int32_t res = CheckImportPubKeyParams(keyParams, pubKey, exInfo);
1000     if (res != HAL_SUCCESS) {
1001         return res;
1002     }
1003 
1004     union KeyRoleInfoUnion roleInfoUnion;
1005     roleInfoUnion.roleInfoStruct.userType = (uint8_t)exInfo->userType;
1006     roleInfoUnion.roleInfoStruct.pairType = (uint8_t)exInfo->pairType;
1007     roleInfoUnion.roleInfoStruct.reserved1 = (uint8_t)0;
1008     roleInfoUnion.roleInfoStruct.reserved2 = (uint8_t)0;
1009 
1010     KeyParams authIdParams = {
1011         .keyBuff = { exInfo->authId.val, exInfo->authId.length, true },
1012         .isDeStorage = keyParams->isDeStorage,
1013         .osAccountId = keyParams->osAccountId
1014     };
1015     struct HksParamSet *paramSet = NULL;
1016     res = ConstructImportPublicKeyParams(&paramSet, algo, pubKey->length, &authIdParams, &roleInfoUnion);
1017     if (res != HAL_SUCCESS) {
1018         return res;
1019     }
1020     struct HksBlob keyAliasBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
1021     struct HksBlob pubKeyBlob = { pubKey->length, pubKey->val };
1022 
1023     LOGI("[HUKS]: HksImportKey enter.");
1024     res = HksImportKey(&keyAliasBlob, paramSet, &pubKeyBlob);
1025     FreeParamSet(paramSet);
1026     LOGI("[HUKS]: HksImportKey quit. [Res]: %" LOG_PUB "d", res);
1027     if (res != HKS_SUCCESS) {
1028         LOGE("[HUKS]: HksImportKey fail. [Res]: %" LOG_PUB "d", res);
1029         return HAL_ERR_HUKS;
1030     }
1031     return HAL_SUCCESS;
1032 }
1033 
BigNumCompare(const Uint8Buff * a,const Uint8Buff * b)1034 static int32_t BigNumCompare(const Uint8Buff *a, const Uint8Buff *b)
1035 {
1036     int res = 0;
1037     if (!CheckBigNumCompareParams(a, b, &res)) {
1038         return res;
1039     }
1040     const uint8_t *tmpA = a->val;
1041     const uint8_t *tmpB = b->val;
1042     uint32_t len = a->length;
1043     if (a->length < b->length) {
1044         for (uint32_t i = 0; i < b->length - a->length; i++) {
1045             if (b->val[i] > 0) {
1046                 return 1; // a < b
1047             }
1048         }
1049         tmpA = a->val;
1050         tmpB = b->val + b->length - a->length;
1051         len = a->length;
1052     }
1053     if (a->length > b->length) {
1054         for (uint32_t i = 0; i < a->length - b->length; i++) {
1055             if (a->val[i] > 0) {
1056                 return -1; // a > b
1057             }
1058         }
1059         tmpA = a->val + a->length - b->length;
1060         tmpB = b->val;
1061         len = b->length;
1062     }
1063     for (uint32_t i = 0; i < len; i++) {
1064         if (*(tmpA + i) > *(tmpB + i)) {
1065             return -1; // a > b
1066         }
1067         if (*(tmpA + i) < *(tmpB + i)) {
1068             return 1; // a < b
1069         }
1070     }
1071     return 0; // a == b
1072 }
1073 
CheckDlPublicKey(const Uint8Buff * key,const char * primeHex)1074 static bool CheckDlPublicKey(const Uint8Buff *key, const char *primeHex)
1075 {
1076     if (key == NULL || key->val == NULL || primeHex == NULL) {
1077         LOGE("Params is null.");
1078         return false;
1079     }
1080     uint8_t min = 1;
1081 
1082     uint32_t innerKeyLen = HcStrlen(primeHex) / BYTE_TO_HEX_OPER_LENGTH;
1083     if (key->length > innerKeyLen) {
1084         LOGE("Key length > prime number length.");
1085         return false;
1086     }
1087     uint8_t *primeByte = (uint8_t *)HcMalloc(innerKeyLen, 0);
1088     if (primeByte == NULL) {
1089         LOGE("Malloc for primeByte failed.");
1090         return false;
1091     }
1092     if (HexStringToByte(primeHex, primeByte, innerKeyLen) != HAL_SUCCESS) {
1093         LOGE("Convert prime number from hex string to byte failed.");
1094         HcFree(primeByte);
1095         return false;
1096     }
1097     /*
1098      * P - 1, since the last byte of large prime number must be greater than 1,
1099      * needn't to think about borrowing forward
1100      */
1101     primeByte[innerKeyLen - 1] -= 1;
1102 
1103     Uint8Buff minBuff = { &min, sizeof(uint8_t) };
1104     if (BigNumCompare(key, &minBuff) >= 0) {
1105         LOGE("Pubkey is invalid, key <= 1.");
1106         HcFree(primeByte);
1107         return false;
1108     }
1109 
1110     Uint8Buff primeBuff = { primeByte, innerKeyLen };
1111     if (BigNumCompare(key, &primeBuff) <= 0) {
1112         LOGE("Pubkey is invalid, key >= p - 1.");
1113         HcFree(primeByte);
1114         return false;
1115     }
1116 
1117     HcFree(primeByte);
1118     return true;
1119 }
1120 
CheckEcPublicKey(const Uint8Buff * pubKey,Algorithm algo)1121 static bool CheckEcPublicKey(const Uint8Buff *pubKey, Algorithm algo)
1122 {
1123     if (algo == P256) {
1124         LOGI("Start check P256 public key");
1125         return MbedtlsIsP256PublicKeyValid(pubKey);
1126     } else if (algo == X25519) {
1127         LOGI("Start check X25519 public key");
1128         return MbedtlsIsX25519PublicKeyValid(pubKey);
1129     }
1130     LOGE("Algorithm not support!");
1131     return false;
1132 }
1133 
ImportSymmetricKey(const KeyParams * keyParams,const Uint8Buff * authToken,KeyPurpose purpose,const ExtraInfo * exInfo)1134 static int32_t ImportSymmetricKey(const KeyParams *keyParams, const Uint8Buff *authToken, KeyPurpose purpose,
1135     const ExtraInfo *exInfo)
1136 {
1137     int32_t res = CheckImportSymmetricKeyParams(keyParams, authToken);
1138     if (res != HAL_SUCCESS) {
1139         return res;
1140     }
1141 
1142     struct HksParamSet *paramSet = NULL;
1143     res = ConstructImportSymmetricKeyParam(&paramSet, keyParams, authToken->length, purpose, exInfo);
1144     if (res != HAL_SUCCESS) {
1145         LOGE("construct param set failed, res = %" LOG_PUB "d", res);
1146         return res;
1147     }
1148     struct HksBlob keyAliasBlob = { keyParams->keyBuff.keyLen, keyParams->keyBuff.key };
1149     struct HksBlob symKeyBlob = { authToken->length, authToken->val };
1150 
1151     LOGI("[HUKS]: HksImportKey enter.");
1152     res = HksImportKey(&keyAliasBlob, paramSet, &symKeyBlob);
1153     FreeParamSet(paramSet);
1154     LOGI("[HUKS]: HksImportKey quit. [Res]: %" LOG_PUB "d", res);
1155     if (res != HKS_SUCCESS) {
1156         LOGE("[HUKS]: HksImportKey fail. [Res]: %" LOG_PUB "d", res);
1157         return HAL_ERR_HUKS;
1158     }
1159     return HAL_SUCCESS;
1160 }
1161 
1162 static const AlgLoader g_huksLoader = {
1163     .initAlg = InitHks,
1164     .sha256 = Sha256,
1165     .generateRandom = GenerateRandom,
1166     .computeHmac = ComputeHmac,
1167     .computeHmacWithThreeStage = ComputeHmacWithThreeStage,
1168     .computeHkdf = ComputeHkdf,
1169     .computePseudonymPsk = ComputePseudonymPsk,
1170     .getKeyExtInfo = GetKeyExtInfo,
1171     .importSymmetricKey = ImportSymmetricKey,
1172     .checkKeyExist = CheckKeyExist,
1173     .deleteKey = DeleteKey,
1174     .aesGcmEncrypt = AesGcmEncrypt,
1175     .aesGcmDecrypt = AesGcmDecrypt,
1176     .hashToPoint = HashToPoint,
1177     .agreeSharedSecretWithStorage = AgreeSharedSecretWithStorage,
1178     .agreeSharedSecret = AgreeSharedSecret,
1179     .bigNumExpMod = BigNumExpMod,
1180     .generateKeyPairWithStorage = GenerateKeyPairWithStorage,
1181     .generateKeyPair = GenerateKeyPair,
1182     .exportPublicKey = ExportPublicKey,
1183     .sign = Sign,
1184     .verify = Verify,
1185     .importPublicKey = ImportPublicKey,
1186     .checkDlPublicKey = CheckDlPublicKey,
1187     .checkEcPublicKey = CheckEcPublicKey,
1188     .bigNumCompare = BigNumCompare,
1189     .base64Encode = MbedtlsBase64Encode,
1190     .base64Decode = MbedtlsBase64Decode
1191 };
1192 
GetRealLoaderInstance(void)1193 const AlgLoader *GetRealLoaderInstance(void)
1194 {
1195     return &g_huksLoader;
1196 }
1197