1 /*
2 Copyright Bryan O'Sullivan 2012
3 
4 All rights reserved.
5 
6 Redistribution and use in source and binary forms, with or without
7 modification, are permitted provided that the following conditions are met:
8 
9     * Redistributions of source code must retain the above copyright
10       notice, this list of conditions and the following disclaimer.
11 
12     * Redistributions in binary form must reproduce the above
13       copyright notice, this list of conditions and the following
14       disclaimer in the documentation and/or other materials provided
15       with the distribution.
16 
17     * Neither the name of Johan Tibell nor the names of other
18       contributors may be used to endorse or promote products derived
19       from this software without specific prior written permission.
20 
21 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 */
33 
34 #include "MachDeps.h"
35 
36 int hashable_getRandomBytes(unsigned char *dest, int nbytes);
37 
38 #if defined(mingw32_HOST_OS) || defined(__MINGW32__)
39 
40 #include <windows.h>
41 #include <wincrypt.h>
42 
hashable_getRandomBytes(unsigned char * dest,int nbytes)43 int hashable_getRandomBytes(unsigned char *dest, int nbytes)
44 {
45   HCRYPTPROV hCryptProv;
46   int ret;
47 
48   if (!CryptAcquireContextA(&hCryptProv, NULL, NULL, PROV_RSA_FULL,
49 			    CRYPT_VERIFYCONTEXT))
50     return -1;
51 
52   ret = CryptGenRandom(hCryptProv, (DWORD) nbytes, (BYTE *) dest) ? nbytes : -1;
53 
54   CryptReleaseContext(hCryptProv, 0);
55 
56  bail:
57   return ret;
58 }
59 
60 #else
61 
62 #include <fcntl.h>
63 #include <sys/types.h>
64 #include <unistd.h>
65 
66 /* Assumptions: /dev/urandom exists and does something sane, and does
67    not block. */
68 
hashable_getRandomBytes(unsigned char * dest,int nbytes)69 int hashable_getRandomBytes(unsigned char *dest, int nbytes)
70 {
71   ssize_t off, nread;
72   int fd;
73 
74   fd = open("/dev/urandom", O_RDONLY);
75   if (fd == -1)
76     return -1;
77 
78   for (off = 0; nbytes > 0; nbytes -= nread) {
79     nread = read(fd, dest + off, nbytes);
80     off += nread;
81     if (nread == -1) {
82       off = -1;
83       break;
84     }
85   }
86 
87  bail:
88   close(fd);
89 
90   return off;
91 }
92 
93 #endif
94