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