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 "random_mbedtls.h"
17 #include "access_token_error.h"
18 #include "access_token.h"
19
20 using OHOS::Security::AccessToken::RandomMbedtls;
21 using OHOS::Security::AccessToken::RET_SUCCESS;
22
23 namespace OHOS {
24 namespace Security {
25 namespace AccessToken {
GetRandomUint32()26 extern "C" unsigned int GetRandomUint32()
27 {
28 unsigned int rand;
29 int ret = RandomMbedtls::GetInstance().GenerateRandomArray(reinterpret_cast<unsigned char *>(&rand), sizeof(rand));
30 if (ret != RET_SUCCESS) {
31 return 0;
32 }
33 return rand;
34 }
35
GenerateRandomArray(unsigned char * randStr,unsigned int len)36 int RandomMbedtls::GenerateRandomArray(unsigned char *randStr, unsigned int len)
37 {
38 if (randStr == nullptr || len == 0) {
39 return ERR_PARAM_INVALID;
40 }
41 int ret;
42
43 Utils::UniqueWriteGuard<Utils::RWLock> infoGuard(this->randomLock_);
44 if (!initFlag_) {
45 mbedtls_ctr_drbg_init(&ctrDrbg_);
46 mbedtls_entropy_init(&entropy_);
47 ret = mbedtls_ctr_drbg_seed(&ctrDrbg_, mbedtls_entropy_func, &entropy_, nullptr, 0);
48 if (ret != 0) {
49 return ERR_FILE_OPERATE_FAILED;
50 }
51 initFlag_ = true;
52 }
53
54 ret = mbedtls_ctr_drbg_random(&ctrDrbg_, randStr, len);
55 if (ret != 0) {
56 return ERR_FILE_OPERATE_FAILED;
57 }
58 return RET_SUCCESS;
59 }
60
GetInstance()61 RandomMbedtls& RandomMbedtls::GetInstance()
62 {
63 static RandomMbedtls instance;
64 return instance;
65 }
66 } // namespace AccessToken
67 } // namespace Security
68 } // namespace OHOS
69