1 /*
2 * Copyright (c) 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 "crypto_rand.h"
17 #include <stdint.h>
18 #include "memory.h"
19 #include "result.h"
20 #include "blob.h"
21 #include "object_base.h"
22 #include "native_common.h"
23 #include "crypto_common.h"
24 #include "rand.h"
25
26 typedef struct OH_CryptoRand {
27 HcfObjectBase base;
28
29 const char *(*getAlgoName)(HcfRand *self);
30
31 HcfResult (*generateRandom)(HcfRand *self, int32_t numBytes, HcfBlob *random);
32
33 HcfResult (*setSeed)(HcfRand *self, HcfBlob *seed);
34 } OH_CryptoRand;
35
OH_CryptoRand_Create(OH_CryptoRand ** ctx)36 OH_Crypto_ErrCode OH_CryptoRand_Create(OH_CryptoRand **ctx)
37 {
38 if (ctx == NULL) {
39 return CRYPTO_PARAMETER_CHECK_FAILED;
40 }
41 HcfResult ret = HcfRandCreate((HcfRand **)ctx);
42 return GetOhCryptoErrCodeNew(ret);
43 }
44
OH_CryptoRand_GenerateRandom(OH_CryptoRand * ctx,int len,Crypto_DataBlob * out)45 OH_Crypto_ErrCode OH_CryptoRand_GenerateRandom(OH_CryptoRand *ctx, int len, Crypto_DataBlob *out)
46 {
47 if ((ctx == NULL) || (ctx->generateRandom == NULL) || (out == NULL)) {
48 return CRYPTO_PARAMETER_CHECK_FAILED;
49 }
50 HcfResult ret = ctx->generateRandom((HcfRand *)ctx, len, (HcfBlob *)out);
51 return GetOhCryptoErrCodeNew(ret);
52 }
53
OH_CryptoRand_GetAlgoName(OH_CryptoRand * ctx)54 const char *OH_CryptoRand_GetAlgoName(OH_CryptoRand *ctx)
55 {
56 if ((ctx == NULL) || (ctx->getAlgoName == NULL)) {
57 return NULL;
58 }
59 return ctx->getAlgoName((HcfRand *)ctx);
60 }
61
OH_CryptoRand_SetSeed(OH_CryptoRand * ctx,Crypto_DataBlob * seed)62 OH_Crypto_ErrCode OH_CryptoRand_SetSeed(OH_CryptoRand *ctx, Crypto_DataBlob *seed)
63 {
64 if ((ctx == NULL) || (ctx->setSeed == NULL)) {
65 return CRYPTO_PARAMETER_CHECK_FAILED;
66 }
67 HcfResult ret = ctx->setSeed((HcfRand *)ctx, (HcfBlob *)seed);
68 return GetOhCryptoErrCodeNew(ret);
69 }
70
OH_CryptoRand_Destroy(OH_CryptoRand * ctx)71 void OH_CryptoRand_Destroy(OH_CryptoRand *ctx)
72 {
73 HcfObjDestroy((HcfRand *)ctx);
74 }