1 /* fhandler_random.cc: code to access /dev/random and /dev/urandom
3 This file is part of Cygwin.
5 This software is a copyrighted work licensed under the terms of the
6 Cygwin license. Please consult the file "CYGWIN_LICENSE" for
12 #include <sys/param.h>
19 #include "child_info.h"
24 /* The system PRNG is reseeded after reading 128K bytes. */
25 #define RESEED_INTERVAL (128 * 1024)
27 #define PSEUDO_MULTIPLIER (6364136223846793005LL)
28 #define PSEUDO_SHIFTVAL (21)
31 fhandler_dev_random::pseudo_write (const void *ptr
, size_t len
)
33 /* Use buffer to mess up the pseudo random number generator. */
34 for (size_t i
= 0; i
< len
; ++i
)
35 pseudo
= (pseudo
+ ((unsigned char *)ptr
)[i
]) * PSEUDO_MULTIPLIER
+ 1;
40 fhandler_dev_random::write (const void *ptr
, size_t len
)
50 /* Limit len to a value <= 4096 since we don't want to overact.
51 Copy to local buffer because RtlGenRandom violates const. */
52 size_t limited_len
= MIN (len
, 4096);
53 unsigned char buf
[limited_len
];
55 /* Mess up system entropy source. Return error if device is /dev/random. */
58 memcpy (buf
, ptr
, limited_len
);
59 if (!RtlGenRandom (buf
, limited_len
) && dev () == FH_RANDOM
)
61 /* Mess up the pseudo random number generator. */
62 pseudo_write (buf
, limited_len
);
69 /* Note that we return len, not limited_len. No reason to confuse the
75 fhandler_dev_random::pseudo_read (void *ptr
, size_t len
)
77 /* Use pseudo random number generator as fallback entropy source.
78 This multiplier was obtained from Knuth, D.E., "The Art of
79 Computer Programming," Vol 2, Seminumerical Algorithms, Third
80 Edition, Addison-Wesley, 1998, p. 106 (line 26) & p. 108 */
81 for (size_t i
= 0; i
< len
; ++i
)
83 pseudo
= pseudo
* PSEUDO_MULTIPLIER
+ 1;
84 ((unsigned char *)ptr
)[i
] = (pseudo
>> PSEUDO_SHIFTVAL
) & UCHAR_MAX
;
90 fhandler_dev_random::read (void *ptr
, size_t& len
)
104 /* /dev/random has to provide high quality random numbers. Therefore we
105 re-seed the system PRNG for each block of 512 bytes. This results in
106 sufficiently random sequences, comparable to the Linux /dev/random. */
107 if (dev () == FH_RANDOM
)
109 void *dummy
= malloc (RESEED_INTERVAL
);
116 for (size_t offset
= 0; offset
< len
; offset
+= 512)
118 if (!RtlGenRandom (dummy
, RESEED_INTERVAL
) ||
119 !RtlGenRandom ((PBYTE
) ptr
+ offset
, len
- offset
))
128 /* If device is /dev/urandom, just use system RNG as is, with our own
130 else if (!RtlGenRandom (ptr
, len
))
131 len
= pseudo_read (ptr
, len
);