| 41 | } |
| 42 | |
| 43 | void system_crypt_random(void* buf, std::size_t len, boost::system::error_code* ec) |
| 44 | { |
| 45 | # ifdef BOOST_POSIX_API |
| 46 | |
| 47 | int file = open("/dev/urandom", O_RDONLY); |
| 48 | if (file == -1) |
| 49 | { |
| 50 | file = open("/dev/random", O_RDONLY); |
| 51 | if (file == -1) |
| 52 | { |
| 53 | fail(errno, ec); |
| 54 | return; |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | size_t bytes_read = 0; |
| 59 | while (bytes_read < len) |
| 60 | { |
| 61 | ssize_t n = read(file, buf, len - bytes_read); |
| 62 | if (n == -1) |
| 63 | { |
| 64 | close(file); |
| 65 | fail(errno, ec); |
| 66 | return; |
| 67 | } |
| 68 | bytes_read += n; |
| 69 | buf = static_cast<char*>(buf) + n; |
| 70 | } |
| 71 | |
| 72 | close(file); |
| 73 | |
| 74 | # else // BOOST_WINDOWS_API |
| 75 | |
| 76 | HCRYPTPROV handle; |
| 77 | int errval = 0; |
| 78 | |
| 79 | if (!::CryptAcquireContextW(&handle, 0, 0, PROV_RSA_FULL, 0)) |
| 80 | { |
| 81 | errval = ::GetLastError(); |
| 82 | if (errval == NTE_BAD_KEYSET) |
| 83 | { |
| 84 | if (!::CryptAcquireContextW(&handle, 0, 0, PROV_RSA_FULL, CRYPT_NEWKEYSET)) |
| 85 | { |
| 86 | errval = ::GetLastError(); |
| 87 | } |
| 88 | else errval = 0; |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | if (!errval) |
| 93 | { |
| 94 | BOOL gen_ok = ::CryptGenRandom(handle, len, static_cast<unsigned char*>(buf)); |
| 95 | if (!gen_ok) |
| 96 | errval = ::GetLastError(); |
| 97 | ::CryptReleaseContext(handle, 0); |
| 98 | } |
| 99 | |
| 100 | if (!errval) return; |