OpenVPN 3 Core Library
Loading...
Searching...
No Matches
devurand.hpp
Go to the documentation of this file.
1// OpenVPN -- An application to securely tunnel IP networks
2// over a single port, with support for SSL/TLS-based
3// session authentication and key exchange,
4// packet encryption, packet authentication, and
5// packet compression.
6//
7// Copyright (C) 2012- OpenVPN Inc.
8//
9// SPDX-License-Identifier: MPL-2.0 OR AGPL-3.0-only WITH openvpn3-openssl-exception
10//
11
12#ifndef OPENVPN_RANDOM_DEVURAND_H
13#define OPENVPN_RANDOM_DEVURAND_H
14
15#include <sys/types.h> // for open()
16#include <sys/stat.h> // for open()
17#include <fcntl.h> // for open()
18
19#include <unistd.h> // for read()
20
23
24namespace openvpn {
25
27{
28 public:
29 OPENVPN_EXCEPTION(dev_urand_error);
30
32
34 : dev_urandom(::open("/dev/urandom", O_RDONLY))
35 {
36 if (!dev_urandom.defined())
37 throw dev_urand_error("init failed");
38 }
39
40 // Random algorithm name
41 std::string name() const override
42 {
43 return "DevURand";
44 }
45
46 // Fill buffer with random bytes
47 void rand_bytes(unsigned char *buf, size_t size) override
48 {
49 if (!rndbytes(buf, size))
50 throw dev_urand_error("rand_bytes failed");
51 }
52
53 // Like rand_bytes, but don't throw exception.
54 // Return true on successs, false on fail.
55 bool rand_bytes_noexcept(unsigned char *buf, size_t size) override
56 {
57 return rndbytes(buf, size);
58 }
59
60 private:
61 bool rndbytes(unsigned char *buf, ssize_t size)
62 {
63 const ssize_t actual = ::read(dev_urandom(), buf, size);
64 return size == actual;
65 }
66
68};
69
70} // namespace openvpn
71
72#endif
ScopedFD dev_urandom
Definition devurand.hpp:67
RCPtr< DevURand > Ptr
Definition devurand.hpp:31
bool rndbytes(unsigned char *buf, ssize_t size)
Definition devurand.hpp:61
std::string name() const override
Get the name of the random number generation algorithm.
Definition devurand.hpp:41
OPENVPN_EXCEPTION(dev_urand_error)
void rand_bytes(unsigned char *buf, size_t size) override
Fill a buffer with random bytes.
Definition devurand.hpp:47
bool rand_bytes_noexcept(unsigned char *buf, size_t size) override
Fill a buffer with random bytes without throwing exceptions.
Definition devurand.hpp:55
The smart pointer class.
Definition rc.hpp:119
bool defined() const
Definition scoped_fd.hpp:58
Abstract base class for cryptographically strong random number generators.
Definition randapi.hpp:228
Implementation of the base classes for random number generators.