blob: 6815ee7109148dcf33d5e33bf88f1c0edf93671c [file] [log] [blame]
Alexandre Lisionddd731e2014-01-31 11:50:08 -05001// Copyright (C) 2010 David Sugar, Tycho Softworks.
2//
3// This file is part of GNU uCommon C++.
4//
5// GNU uCommon C++ is free software: you can redistribute it and/or modify
6// it under the terms of the GNU Lesser General Public License as published
7// by the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// GNU uCommon C++ is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU Lesser General Public License for more details.
14//
15// You should have received a copy of the GNU Lesser General Public License
16// along with GNU uCommon C++. If not, see <http://www.gnu.org/licenses/>.
17
18#include "local.h"
19
20#ifndef _MSWINDOWS_
21#include <fcntl.h>
22#endif
23
24void Random::seed(void)
25{
26 time_t now;
27
28 time(&now);
29 srand((int)now);
30}
31
32bool Random::seed(const unsigned char *buf, size_t size)
33{
34#ifdef _MSWINDOWS_
35 return false;
36#else
37 int fd = open("/dev/random", O_WRONLY);
38 bool result = false;
39
40 if(fd > -1) {
41 if(write(fd, buf, size) > 0)
42 result = true;
43 close(fd);
44 }
45 return result;
46#endif
47}
48
49size_t Random::key(unsigned char *buf, size_t size)
50{
51#ifdef _MSWINDOWS_
52 if((_handle != (HCRYPTPROV)NULL) && CryptGenRandom(_handle, size, buf))
53 return size;
54 return 0;
55#else
56 int fd = open("/dev/random", O_RDONLY);
57 ssize_t result = 0;
58
59 if(fd > -1) {
60 result = read(fd, buf, size);
61 close(fd);
62 }
63
64 if(result < 0)
65 result = 0;
66
67 return (size_t)result;
68#endif
69}
70
71size_t Random::fill(unsigned char *buf, size_t size)
72{
73#ifdef _MSWINDOWS_
74 return key(buf, size);
75#else
76 int fd = open("/dev/urandom", O_RDONLY);
77 ssize_t result = 0;
78
79 if(fd > -1) {
80 result = read(fd, buf, size);
81 close(fd);
82 }
83 // ugly...would not trust it
84 else {
85 result = 0;
86 while(result++ < (ssize_t)size)
87 *(buf++) = rand() & 0xff;
88 }
89
90 if(result < 0)
91 result = 0;
92
93 return (size_t)result;
94#endif
95}
96
97bool Random::status(void)
98{
99#ifdef _MSWINDOWS_
100 return true;
101#else
102 if(fsys::is_file("/dev/random"))
103 return true;
104
105 return false;
106#endif
107}
108