3 * Copyright 1998-1999 The OpenLDAP Foundation, All Rights Reserved.
4 * COPYING RESTRICTIONS APPLY, see COPYRIGHT file
12 #ifdef HAVE_WINCRYPT_H
22 #include <lutil_md5.h>
25 * lutil_entropy() provides nbytes of entropy in buf.
26 * Quality offerred is suitable for one-time uses, such as "once" keys.
27 * Values may not be suitable for multi-time uses.
29 * Note: Callers are encouraged to provide additional bytes of
30 * of entropy in the buf argument. This information is used in
31 * fallback mode to improve the quality of bytes returned.
33 * This routinue should be extended to support additional sources
36 int lutil_entropy( char *buf, ber_len_t nbytes )
38 if( nbytes == 0 ) return 0;
41 /* Linux and *BSD offer a urandom device */
45 fd = open( URANDOM_DEVICE, O_RDONLY );
47 if( fd < 0 ) return -1;
49 rc = read( fd, buf, nbytes );
52 /* should return nbytes */
53 if( rc < nbytes ) return -1;
59 /* Not used since _WIN32_WINNT not set... */
62 /* Get handle to user default provider */
63 if(!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, 0)) {
67 /* Generate random initialization vector */
68 if(!CryptGenRandom(hProv, (DWORD) nbytes, (BYTE *) buf)) {
72 /* Release provider handle */
73 if(hProv != 0) CryptReleaseContext(hProv, 0);
79 /* based upon Phil Karn's "practical randomness" idea
80 * but implementation 100% OpenLDAP. So don't blame Phil.
82 * Worse case is that this is a MD5 hash of a counter, if
83 * MD5 is a strong cryptographic hash, this should be fairly
88 * the caller may need to provide external synchronization OR
89 * provide entropy (in buf) to ensure quality results as
90 * access to this counter may not be atomic.
92 static int counter = 0;
99 struct rdata_s *stack;
103 #ifdef HAVE_GETTIMEOFDAY
109 unsigned long junk; /* purposely not initialized */
112 /* make sure rdata differs for each process */
113 rdata.pid = getpid();
115 /* make sure rdata differs for each program */
117 rdata.stack = &rdata;
119 for( n = 0; n < nbytes; n += 16 ) {
120 struct lutil_MD5Context ctx;
123 /* poor resolution */
124 #ifdef HAVE_GETTIMEOFDAY
125 (void) gettimeofday( &rdata.tv, NULL );
127 (void) time( &rdata.time );
130 /* make sure rdata differs */
131 rdata.counter = ++counter;
135 lutil_MD5Init( &ctx );
136 lutil_MD5Update( &ctx, (char *) &rdata, sizeof( rdata ) );
138 /* allow caller to provided additional entropy */
139 lutil_MD5Update( &ctx, (char *) &buf, nbytes );
141 lutil_MD5Final( digest, &ctx );
143 memcpy( &buf[n], digest,
144 nbytes - n >= 16 ? 16 : nbytes - n );