• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021 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 "platform/include/random.h"
17 #include <fcntl.h>
18 #include <unistd.h>
19 #include "platform/include/platform_def.h"
20 
21 static int g_fd = -1;
22 
GetRandomFd()23 static int GetRandomFd()
24 {
25     if (g_fd >= 0) {
26         return g_fd;
27     }
28 
29     g_fd = open("/dev/random", O_RDONLY | O_NONBLOCK);
30     if (g_fd == -1) {
31         LOG_ERROR("Open random-device failed... error no: %{public}d.", errno);
32         return -1;
33     }
34 
35     return g_fd;
36 }
37 
CloseRandomFd()38 static void CloseRandomFd()
39 {
40     if (g_fd == -1) {
41         return;
42     }
43     (void)close(g_fd);
44     g_fd = -1;
45 }
46 
RandomGenerate()47 uint32_t RandomGenerate()
48 {
49     uint32_t val = 0;
50     int rfd = GetRandomFd();
51     if (rfd != -1) {
52         if (read(rfd, &val, sizeof(val)) == -1) {
53             LOG_ERROR("Read random-device failed... error no: %{public}d.", errno);
54         }
55         CloseRandomFd();
56     }
57     return val;
58 }