1 /*
2 * Copyright (C) 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 "rand_openssl.h"
17
18 #include "openssl_common.h"
19 #include "securec.h"
20 #include "log.h"
21 #include "memory.h"
22 #include "utils.h"
23
24 #include <openssl/rand.h>
25
26 typedef struct {
27 HcfRandSpi base;
28 } HcfRandSpiImpl;
29
GetRandOpenSSLClass(void)30 static const char *GetRandOpenSSLClass(void)
31 {
32 return "RandOpenssl";
33 }
34
OpensslGenerateRandom(HcfRandSpi * self,int32_t numBytes,HcfBlob * random)35 static HcfResult OpensslGenerateRandom(HcfRandSpi *self, int32_t numBytes, HcfBlob *random)
36 {
37 unsigned char randBuf[numBytes];
38 int32_t ret = RAND_priv_bytes(randBuf, numBytes);
39 if (ret != HCF_OPENSSL_SUCCESS) {
40 LOGE("RAND_bytes return error!");
41 HcfPrintOpensslError();
42 return HCF_ERR_CRYPTO_OPERATION;
43 }
44 random->data = (uint8_t *)HcfMalloc(numBytes, 0);
45 if (random->data == NULL) {
46 LOGE("Failed to allocate random->data memory!");
47 return HCF_ERR_MALLOC;
48 }
49 (void)memcpy_s(random->data, numBytes, randBuf, numBytes);
50 random->len = numBytes;
51 return HCF_SUCCESS;
52 }
53
OpensslSetSeed(HcfRandSpi * self,HcfBlob * seed)54 static void OpensslSetSeed(HcfRandSpi *self, HcfBlob *seed)
55 {
56 RAND_seed(seed->data, seed->len);
57 }
58
DestroyRandOpenssl(HcfObjectBase * self)59 static void DestroyRandOpenssl(HcfObjectBase *self)
60 {
61 if (self == NULL) {
62 LOGE("Self ptr is NULL!");
63 return;
64 }
65 if (!IsClassMatch(self, GetRandOpenSSLClass())) {
66 LOGE("Class is not match.");
67 return;
68 }
69 HcfFree(self);
70 }
71
HcfRandSpiCreate(HcfRandSpi ** spiObj)72 HcfResult HcfRandSpiCreate(HcfRandSpi **spiObj)
73 {
74 if (spiObj == NULL) {
75 LOGE("Invalid input parameter.");
76 return HCF_INVALID_PARAMS;
77 }
78 HcfRandSpiImpl *returnSpiImpl = (HcfRandSpiImpl *)HcfMalloc(sizeof(HcfRandSpiImpl), 0);
79 if (returnSpiImpl == NULL) {
80 LOGE("Failed to allocate returnImpl memory!");
81 return HCF_ERR_MALLOC;
82 }
83 returnSpiImpl->base.base.getClass = GetRandOpenSSLClass;
84 returnSpiImpl->base.base.destroy = DestroyRandOpenssl;
85 returnSpiImpl->base.engineGenerateRandom = OpensslGenerateRandom;
86 returnSpiImpl->base.engineSetSeed = OpensslSetSeed;
87 *spiObj = (HcfRandSpi *)returnSpiImpl;
88 return HCF_SUCCESS;
89 }