1 /*
2 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "hks_openssl_common.h"
17
18 #include <openssl/rand.h>
19 #include <stddef.h>
20
21 #include "hks_log.h"
22 #include "hks_mem.h"
23 #include "hks_openssl_engine.h"
24 #include "hks_template.h"
25 #include "securec.h"
26
HksOpensslGenerateRandomKey(const uint32_t keySize,struct HksBlob * key)27 int32_t HksOpensslGenerateRandomKey(const uint32_t keySize, struct HksBlob *key)
28 {
29 uint32_t keySizeByte = keySize / BIT_NUM_OF_UINT8;
30 int32_t ret = HKS_ERROR_CRYPTO_ENGINE_ERROR;
31
32 uint8_t *tmpKey = (uint8_t *)HksMalloc(keySizeByte);
33 HKS_IF_NULL_LOGE_RETURN(tmpKey, HKS_ERROR_MALLOC_FAIL, "malloc buffer failed")
34
35 do {
36 if (RAND_bytes(tmpKey, keySizeByte) <= 0) {
37 HKS_LOG_E("generate key is failed:0x%" LOG_PUBLIC "x", ret);
38 break;
39 }
40
41 key->data = tmpKey;
42 key->size = keySizeByte;
43 ret = HKS_SUCCESS;
44 } while (0);
45
46 if (ret != HKS_SUCCESS) {
47 (void)memset_s(tmpKey, keySizeByte, 0, keySizeByte);
48 HKS_FREE(tmpKey);
49 }
50 return ret;
51 }
52
HksOpensslFillRandomInner(struct HksBlob * randomData,bool isPriv)53 static int32_t HksOpensslFillRandomInner(struct HksBlob *randomData, bool isPriv)
54 {
55 int ret = isPriv ?
56 RAND_priv_bytes(randomData->data, randomData->size) :
57 RAND_bytes(randomData->data, randomData->size);
58 HKS_IF_TRUE_LOGE_RETURN(ret <= 0, HKS_ERROR_CRYPTO_ENGINE_ERROR,
59 "generate random failed, ret = 0x%" LOG_PUBLIC "x, isPriv = %" LOG_PUBLIC "d", ret, isPriv)
60 HKS_IF_TRUE_RETURN(randomData->size == 1, HKS_SUCCESS)
61
62 uint32_t j = 0;
63
64 for (uint32_t i = 0; i < randomData->size; i++) {
65 if (randomData->data[i] == 0) {
66 j++;
67 }
68 }
69 HKS_IF_TRUE_LOGE_RETURN(j == randomData->size, HKS_ERROR_CRYPTO_ENGINE_ERROR,
70 "fill random failed, size %" LOG_PUBLIC "x, isPriv = %" LOG_PUBLIC "d", randomData->size, isPriv)
71 HKS_LOG_D("generate random success, isPriv =%" LOG_PUBLIC "d", isPriv);
72
73 return HKS_SUCCESS;
74 }
75
HksOpensslFillRandom(struct HksBlob * randomData)76 int32_t HksOpensslFillRandom(struct HksBlob *randomData)
77 {
78 return HksOpensslFillRandomInner(randomData, false);
79 }
80
HksOpensslFillPrivRandom(struct HksBlob * randomData)81 int32_t HksOpensslFillPrivRandom(struct HksBlob *randomData)
82 {
83 return HksOpensslFillRandomInner(randomData, true);
84 }
85