1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
3 * LibTomCrypt is a library that provides various cryptographic
4 * algorithms in a highly modular and flexible manner.
6 * The library is free for all purposes without any express
11 #ifdef LTC_RNG_GET_BYTES
14 portable way to get secure random bits to feed a PRNG (Tom St Denis)
17 #if defined(LTC_DEVRANDOM) && !defined(_WIN32)
18 /* on *NIX read /dev/random */
19 static unsigned long _rng_nix(unsigned char *buf, unsigned long len,
20 void (*callback)(void))
23 LTC_UNUSED_PARAM(callback);
24 LTC_UNUSED_PARAM(buf);
25 LTC_UNUSED_PARAM(len);
30 LTC_UNUSED_PARAM(callback);
31 #ifdef LTC_TRY_URANDOM_FIRST
32 f = fopen("/dev/urandom", "rb");
34 #endif /* LTC_TRY_URANDOM_FIRST */
35 f = fopen("/dev/random", "rb");
41 /* disable buffering */
42 if (setvbuf(f, NULL, _IONBF, 0) != 0) {
47 x = (unsigned long)fread(buf, 1, (size_t)len, f);
50 #endif /* LTC_NO_FILE */
53 #endif /* LTC_DEVRANDOM */
55 #if !defined(_WIN32_WCE)
59 static unsigned long _rng_ansic(unsigned char *buf, unsigned long len,
60 void (*callback)(void))
63 int l, acc, bits, a, b;
69 if (callback != NULL) callback();
72 t1 = XCLOCK(); while (t1 == XCLOCK()) a ^= 1;
73 t1 = XCLOCK(); while (t1 == XCLOCK()) b ^= 1;
86 /* Try the Microsoft CSP */
87 #if defined(_WIN32) || defined(_WIN32_WCE)
89 #define _WIN32_WINNT 0x0400
96 #define WIN32_LEAN_AND_MEAN
100 static unsigned long _rng_win32(unsigned char *buf, unsigned long len,
101 void (*callback)(void))
103 HCRYPTPROV hProv = 0;
104 LTC_UNUSED_PARAM(callback);
105 if (!CryptAcquireContext(&hProv, NULL, MS_DEF_PROV, PROV_RSA_FULL,
106 (CRYPT_VERIFYCONTEXT | CRYPT_MACHINE_KEYSET)) &&
107 !CryptAcquireContext (&hProv, NULL, MS_DEF_PROV, PROV_RSA_FULL,
108 CRYPT_VERIFYCONTEXT | CRYPT_MACHINE_KEYSET | CRYPT_NEWKEYSET))
111 if (CryptGenRandom(hProv, len, buf) == TRUE) {
112 CryptReleaseContext(hProv, 0);
115 CryptReleaseContext(hProv, 0);
124 @param out Destination
125 @param outlen Length desired (octets)
126 @param callback Pointer to void function to act as "callback" when RNG is slow. This can be NULL
127 @return Number of octets read
129 unsigned long rng_get_bytes(unsigned char *out, unsigned long outlen,
130 void (*callback)(void))
134 LTC_ARGCHK(out != NULL);
136 #ifdef LTC_PRNG_ENABLE_LTC_RNG
138 x = ltc_rng(out, outlen, callback);
145 #if defined(_WIN32) || defined(_WIN32_WCE)
146 x = _rng_win32(out, outlen, callback); if (x != 0) { return x; }
147 #elif defined(LTC_DEVRANDOM)
148 x = _rng_nix(out, outlen, callback); if (x != 0) { return x; }
151 x = _rng_ansic(out, outlen, callback); if (x != 0) { return x; }
155 #endif /* #ifdef LTC_RNG_GET_BYTES */
157 /* ref: $Format:%D$ */
158 /* git commit: $Format:%H$ */
159 /* commit time: $Format:%ai$ */