• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "random.h"
17 
18 #include <cerrno>
19 #include <cstdio>
20 #include <fcntl.h>
21 #include <unistd.h>
22 #include "accesstoken_common_log.h"
23 
24 namespace OHOS {
25 namespace Security {
26 namespace AccessToken {
GetRandomUint32FromUrandom(void)27 extern "C" uint32_t GetRandomUint32FromUrandom(void)
28 {
29     uint64_t accessTokenFdTag = 0xD005A01;
30     uint32_t random;
31     int32_t fd = open("/dev/urandom", O_RDONLY);
32     if (fd < 0) {
33         LOGE(ATM_DOMAIN, ATM_TAG, "Failed to open urandom, errno=%{public}d.", errno);
34         return 0;
35     }
36     fdsan_exchange_owner_tag(fd, 0, accessTokenFdTag);
37     ssize_t len = read(fd, &random, sizeof(random));
38     (void)fdsan_close_with_tag(fd, accessTokenFdTag);
39 
40     if (len != sizeof(random)) {
41         LOGE(ATM_DOMAIN, ATM_TAG, "Failed to read from urandom, errno=%{public}d.", errno);
42         return 0;
43     }
44     return random;
45 }
46 } // namespace AccessToken
47 } // namespace Security
48 } // namespace OHOS
49