ebb98baa98eeddebbc19bd2524a2bdf18111de76
[openssl.git] / crypto / rand / md_rand.c
1 /* crypto/rand/md_rand.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  * 
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  * 
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  * 
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from 
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  * 
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * 
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2000 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer. 
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111
112 #define ENTROPY_NEEDED 20  /* require 160 bits = 20 bytes of randomness */
113
114 #ifndef MD_RAND_DEBUG
115 # ifndef NDEBUG
116 #   define NDEBUG
117 # endif
118 #endif
119
120 #include <assert.h>
121 #include <stdio.h>
122 #include <time.h>
123 #include <string.h>
124
125 #include "openssl/e_os.h"
126
127 #include <openssl/crypto.h>
128 #include <openssl/err.h>
129
130 #if !defined(USE_MD5_RAND) && !defined(USE_SHA1_RAND) && !defined(USE_MDC2_RAND) && !defined(USE_MD2_RAND)
131 #if !defined(NO_SHA) && !defined(NO_SHA1)
132 #define USE_SHA1_RAND
133 #elif !defined(NO_MD5)
134 #define USE_MD5_RAND
135 #elif !defined(NO_MDC2) && !defined(NO_DES)
136 #define USE_MDC2_RAND
137 #elif !defined(NO_MD2)
138 #define USE_MD2_RAND
139 #else
140 #error No message digest algorithm available
141 #endif
142 #endif
143
144 /* Changed how the state buffer used.  I now attempt to 'wrap' such
145  * that I don't run over the same locations the next time  go through
146  * the 1023 bytes - many thanks to
147  * Robert J. LeBlanc <rjl@renaissoft.com> for his comments
148  */
149
150 #if defined(USE_MD5_RAND)
151 #include <openssl/md5.h>
152 #define MD_DIGEST_LENGTH        MD5_DIGEST_LENGTH
153 #define MD_CTX                  MD5_CTX
154 #define MD_Init(a)              MD5_Init(a)
155 #define MD_Update(a,b,c)        MD5_Update(a,b,c)
156 #define MD_Final(a,b)           MD5_Final(a,b)
157 #define MD(a,b,c)               MD5(a,b,c)
158 #elif defined(USE_SHA1_RAND)
159 #include <openssl/sha.h>
160 #define MD_DIGEST_LENGTH        SHA_DIGEST_LENGTH
161 #define MD_CTX                  SHA_CTX
162 #define MD_Init(a)              SHA1_Init(a)
163 #define MD_Update(a,b,c)        SHA1_Update(a,b,c)
164 #define MD_Final(a,b)           SHA1_Final(a,b)
165 #define MD(a,b,c)               SHA1(a,b,c)
166 #elif defined(USE_MDC2_RAND)
167 #include <openssl/mdc2.h>
168 #define MD_DIGEST_LENGTH        MDC2_DIGEST_LENGTH
169 #define MD_CTX                  MDC2_CTX
170 #define MD_Init(a)              MDC2_Init(a)
171 #define MD_Update(a,b,c)        MDC2_Update(a,b,c)
172 #define MD_Final(a,b)           MDC2_Final(a,b)
173 #define MD(a,b,c)               MDC2(a,b,c)
174 #elif defined(USE_MD2_RAND)
175 #include <openssl/md2.h>
176 #define MD_DIGEST_LENGTH        MD2_DIGEST_LENGTH
177 #define MD_CTX                  MD2_CTX
178 #define MD_Init(a)              MD2_Init(a)
179 #define MD_Update(a,b,c)        MD2_Update(a,b,c)
180 #define MD_Final(a,b)           MD2_Final(a,b)
181 #define MD(a,b,c)               MD2(a,b,c)
182 #endif
183
184 #include <openssl/rand.h>
185
186 #ifdef BN_DEBUG
187 # define PREDICT
188 #endif
189
190 /* #define NORAND       1 */
191 /* #define PREDICT      1 */
192
193 #define STATE_SIZE      1023
194 static int state_num=0,state_index=0;
195 static unsigned char state[STATE_SIZE+MD_DIGEST_LENGTH];
196 static unsigned char md[MD_DIGEST_LENGTH];
197 static long md_count[2]={0,0};
198 static double entropy=0;
199 static int initialized=0;
200
201 #ifdef PREDICT
202 int rand_predictable=0;
203 #endif
204
205 const char *RAND_version="RAND" OPENSSL_VERSION_PTEXT;
206
207 static void ssleay_rand_cleanup(void);
208 static void ssleay_rand_seed(const void *buf, int num);
209 static void ssleay_rand_add(const void *buf, int num, double add_entropy);
210 static int ssleay_rand_bytes(unsigned char *buf, int num);
211 static int ssleay_rand_pseudo_bytes(unsigned char *buf, int num);
212 static int ssleay_rand_status(void);
213
214 RAND_METHOD rand_ssleay_meth={
215         ssleay_rand_seed,
216         ssleay_rand_bytes,
217         ssleay_rand_cleanup,
218         ssleay_rand_add,
219         ssleay_rand_pseudo_bytes,
220         ssleay_rand_status
221         }; 
222
223 RAND_METHOD *RAND_SSLeay(void)
224         {
225         return(&rand_ssleay_meth);
226         }
227
228 static void ssleay_rand_cleanup(void)
229         {
230         memset(state,0,sizeof(state));
231         state_num=0;
232         state_index=0;
233         memset(md,0,MD_DIGEST_LENGTH);
234         md_count[0]=0;
235         md_count[1]=0;
236         entropy=0;
237         }
238
239 static void ssleay_rand_add(const void *buf, int num, double add)
240         {
241         int i,j,k,st_idx;
242         long md_c[2];
243         unsigned char local_md[MD_DIGEST_LENGTH];
244         MD_CTX m;
245
246 #ifdef NORAND
247         return;
248 #endif
249
250         /*
251          * (Based on the rand(3) manpage)
252          *
253          * The input is chopped up into units of 20 bytes (or less for
254          * the last block).  Each of these blocks is run through the hash
255          * function as follows:  The data passed to the hash function
256          * is the current 'md', the same number of bytes from the 'state'
257          * (the location determined by in incremented looping index) as
258          * the current 'block', the new key data 'block', and 'count'
259          * (which is incremented after each use).
260          * The result of this is kept in 'md' and also xored into the
261          * 'state' at the same locations that were used as input into the
262          * hash function.
263          */
264
265         CRYPTO_w_lock(CRYPTO_LOCK_RAND);
266         st_idx=state_index;
267
268         /* use our own copies of the counters so that even
269          * if a concurrent thread seeds with exactly the
270          * same data and uses the same subarray there's _some_
271          * difference */
272         md_c[0] = md_count[0];
273         md_c[1] = md_count[1];
274
275         memcpy(local_md, md, sizeof md);
276
277         /* state_index <= state_num <= STATE_SIZE */
278         state_index += num;
279         if (state_index >= STATE_SIZE)
280                 {
281                 state_index%=STATE_SIZE;
282                 state_num=STATE_SIZE;
283                 }
284         else if (state_num < STATE_SIZE)        
285                 {
286                 if (state_index > state_num)
287                         state_num=state_index;
288                 }
289         /* state_index <= state_num <= STATE_SIZE */
290
291         /* state[st_idx], ..., state[(st_idx + num - 1) % STATE_SIZE]
292          * are what we will use now, but other threads may use them
293          * as well */
294
295         md_count[1] += (num / MD_DIGEST_LENGTH) + (num % MD_DIGEST_LENGTH > 0);
296
297         CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
298
299         for (i=0; i<num; i+=MD_DIGEST_LENGTH)
300                 {
301                 j=(num-i);
302                 j=(j > MD_DIGEST_LENGTH)?MD_DIGEST_LENGTH:j;
303
304                 MD_Init(&m);
305                 MD_Update(&m,local_md,MD_DIGEST_LENGTH);
306                 k=(st_idx+j)-STATE_SIZE;
307                 if (k > 0)
308                         {
309                         MD_Update(&m,&(state[st_idx]),j-k);
310                         MD_Update(&m,&(state[0]),k);
311                         }
312                 else
313                         MD_Update(&m,&(state[st_idx]),j);
314                         
315                 MD_Update(&m,buf,j);
316                 MD_Update(&m,(unsigned char *)&(md_c[0]),sizeof(md_c));
317                 MD_Final(local_md,&m);
318                 md_c[1]++;
319
320                 buf=(const char *)buf + j;
321
322                 for (k=0; k<j; k++)
323                         {
324                         /* Parallel threads may interfere with this,
325                          * but always each byte of the new state is
326                          * the XOR of some previous value of its
327                          * and local_md (itermediate values may be lost).
328                          * Alway using locking could hurt performance more
329                          * than necessary given that conflicts occur only
330                          * when the total seeding is longer than the random
331                          * state. */
332                         state[st_idx++]^=local_md[k];
333                         if (st_idx >= STATE_SIZE)
334                                 st_idx=0;
335                         }
336                 }
337         memset((char *)&m,0,sizeof(m));
338
339         CRYPTO_w_lock(CRYPTO_LOCK_RAND);
340         /* Don't just copy back local_md into md -- this could mean that
341          * other thread's seeding remains without effect (except for
342          * the incremented counter).  By XORing it we keep at least as
343          * much entropy as fits into md. */
344         for (k = 0; k < sizeof md; k++)
345                 {
346                 md[k] ^= local_md[k];
347                 }
348         if (entropy < ENTROPY_NEEDED) /* stop counting when we have enough */
349             entropy += add;
350         CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
351         
352 #ifndef THREADS 
353         assert(md_c[1] == md_count[1]);
354 #endif
355         }
356
357 static void ssleay_rand_seed(const void *buf, int num)
358         {
359         ssleay_rand_add(buf, num, num);
360         }
361
362 static void ssleay_rand_initialize(void)
363         {
364         unsigned long l;
365 #ifndef GETPID_IS_MEANINGLESS
366         pid_t curr_pid = getpid();
367 #endif
368 #ifdef DEVRANDOM
369         FILE *fh;
370 #endif
371
372 #ifdef NORAND
373         return;
374 #endif
375
376         CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
377         /* put in some default random data, we need more than just this */
378 #ifndef GETPID_IS_MEANINGLESS
379         l=curr_pid;
380         RAND_add(&l,sizeof(l),0);
381         l=getuid();
382         RAND_add(&l,sizeof(l),0);
383 #endif
384         l=time(NULL);
385         RAND_add(&l,sizeof(l),0);
386
387 #ifdef DEVRANDOM
388         /* Use a random entropy pool device. Linux, FreeBSD and OpenBSD
389          * have this. Use /dev/urandom if you can as /dev/random may block
390          * if it runs out of random entries.  */
391
392         if ((fh = fopen(DEVRANDOM, "r")) != NULL)
393                 {
394                 unsigned char tmpbuf[ENTROPY_NEEDED];
395                 int n;
396                 
397                 setvbuf(fh, NULL, _IONBF, 0);
398                 n=fread((unsigned char *)tmpbuf,1,ENTROPY_NEEDED,fh);
399                 fclose(fh);
400                 RAND_add(tmpbuf,sizeof tmpbuf,n);
401                 memset(tmpbuf,0,n);
402                 }
403 #endif
404 #ifdef PURIFY
405         memset(state,0,STATE_SIZE);
406         memset(md,0,MD_DIGEST_LENGTH);
407 #endif
408         CRYPTO_w_lock(CRYPTO_LOCK_RAND);
409         initialized=1;
410         }
411
412 static int ssleay_rand_bytes(unsigned char *buf, int num)
413         {
414         static volatile int stirred_pool = 0;
415         int i,j,k,st_num,st_idx;
416         int ok;
417         long md_c[2];
418         unsigned char local_md[MD_DIGEST_LENGTH];
419         MD_CTX m;
420 #ifndef GETPID_IS_MEANINGLESS
421         pid_t curr_pid = getpid();
422 #endif
423         int do_stir_pool = 0;
424
425 #ifdef PREDICT
426         if (rand_predictable)
427                 {
428                 static unsigned char val=0;
429
430                 for (i=0; i<num; i++)
431                         buf[i]=val++;
432                 return(1);
433                 }
434 #endif
435
436         /*
437          * (Based on the rand(3) manpage:)
438          *
439          * For each group of 10 bytes (or less), we do the following:
440          *
441          * Input into the hash function the top 10 bytes from the
442          * local 'md' (which is initialized from the global 'md'
443          * before any bytes are generated), the bytes that are
444          * to be overwritten by the random bytes, and bytes from the
445          * 'state' (incrementing looping index).  From this digest output
446          * (which is kept in 'md'), the top (up to) 10 bytes are
447          * returned to the caller and the bottom (up to) 10 bytes are xored
448          * into the 'state'.
449          * Finally, after we have finished 'num' random bytes for the
450          * caller, 'count' (which is incremented) and the local and global 'md'
451          * are fed into the hash function and the results are kept in the
452          * global 'md'.
453          */
454
455         CRYPTO_w_lock(CRYPTO_LOCK_RAND);
456
457         if (!initialized)
458                 ssleay_rand_initialize();
459
460         if (!stirred_pool)
461                 do_stir_pool = 1;
462         
463         ok = (entropy >= ENTROPY_NEEDED);
464         if (!ok)
465                 {
466                 /* If the PRNG state is not yet unpredictable, then seeing
467                  * the PRNG output may help attackers to determine the new
468                  * state; thus we have to decrease the entropy estimate.
469                  * Once we've had enough initial seeding we don't bother to
470                  * adjust the entropy count, though, because we're not ambitious
471                  * to provide *information-theoretic* randomness.
472                  *
473                  * NOTE: This approach fails if the program forks before
474                  * we have enough entropy. Entropy should be collected
475                  * in a separate input pool and be transferred to the
476                  * output pool only when the entropy limit has been reached.
477                  */
478                 entropy -= num;
479                 if (entropy < 0)
480                         entropy = 0;
481                 }
482
483         if (do_stir_pool)
484                 {
485                 /* Our output function chains only half of 'md', so we better
486                  * make sure that the required entropy gets 'evenly distributed'
487                  * through 'state', our randomness pool.  The input function
488                  * (ssleay_rand_add) chains all of 'md', which makes it more
489                  * suitable for this purpose.
490                  */
491
492                 int n = STATE_SIZE; /* so that the complete pool gets accessed */
493                 while (n > 0)
494                         {
495 #if MD_DIGEST_LENGTH > 20
496 # error "Please adjust DUMMY_SEED."
497 #endif
498 #define DUMMY_SEED "...................." /* at least MD_DIGEST_LENGTH */
499                         /* Note that the seed does not matter, it's just that
500                          * ssleay_rand_add expects to have something to hash. */
501                         ssleay_rand_add(DUMMY_SEED, MD_DIGEST_LENGTH, 0.0);
502                         n -= MD_DIGEST_LENGTH;
503                         }
504                 if (ok)
505                         stirred_pool = 1;
506                 }
507
508         st_idx=state_index;
509         st_num=state_num;
510         md_c[0] = md_count[0];
511         md_c[1] = md_count[1];
512         memcpy(local_md, md, sizeof md);
513
514         state_index+=num;
515         if (state_index > state_num)
516                 state_index %= state_num;
517
518         /* state[st_idx], ..., state[(st_idx + num - 1) % st_num]
519          * are now ours (but other threads may use them too) */
520
521         md_count[0] += 1;
522         CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
523
524         while (num > 0)
525                 {
526                 j=(num >= MD_DIGEST_LENGTH/2)?MD_DIGEST_LENGTH/2:num;
527                 num-=j;
528                 MD_Init(&m);
529 #ifndef GETPID_IS_MEANINGLESS
530                 if (curr_pid) /* just in the first iteration to save time */
531                         {
532                         MD_Update(&m,(unsigned char*)&curr_pid,sizeof curr_pid);
533                         curr_pid = 0;
534                         }
535 #endif
536                 MD_Update(&m,&(local_md[MD_DIGEST_LENGTH/2]),MD_DIGEST_LENGTH/2);
537                 MD_Update(&m,(unsigned char *)&(md_c[0]),sizeof(md_c));
538 #ifndef PURIFY
539                 MD_Update(&m,buf,j); /* purify complains */
540 #endif
541                 k=(st_idx+j)-st_num;
542                 if (k > 0)
543                         {
544                         MD_Update(&m,&(state[st_idx]),j-k);
545                         MD_Update(&m,&(state[0]),k);
546                         }
547                 else
548                         MD_Update(&m,&(state[st_idx]),j);
549                 MD_Final(local_md,&m);
550
551                 for (i=0; i<j; i++)
552                         {
553                         state[st_idx++]^=local_md[i]; /* may compete with other threads */
554                         *(buf++)=local_md[i+MD_DIGEST_LENGTH/2];
555                         if (st_idx >= st_num)
556                                 st_idx=0;
557                         }
558                 }
559
560         MD_Init(&m);
561         MD_Update(&m,(unsigned char *)&(md_c[0]),sizeof(md_c));
562         MD_Update(&m,local_md,MD_DIGEST_LENGTH);
563         CRYPTO_w_lock(CRYPTO_LOCK_RAND);
564         MD_Update(&m,md,MD_DIGEST_LENGTH);
565         MD_Final(md,&m);
566         CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
567
568         memset(&m,0,sizeof(m));
569         if (ok)
570                 return(1);
571         else
572                 {
573                 RANDerr(RAND_F_SSLEAY_RAND_BYTES,RAND_R_PRNG_NOT_SEEDED);
574                 return(0);
575                 }
576         }
577
578 /* pseudo-random bytes that are guaranteed to be unique but not
579    unpredictable */
580 static int ssleay_rand_pseudo_bytes(unsigned char *buf, int num) 
581         {
582         int ret, err;
583
584         ret = RAND_bytes(buf, num);
585         if (ret == 0)
586                 {
587                 err = ERR_peek_error();
588                 if (ERR_GET_LIB(err) == ERR_LIB_RAND &&
589                     ERR_GET_REASON(err) == RAND_R_PRNG_NOT_SEEDED)
590                         (void)ERR_get_error();
591                 }
592         return (ret);
593         }
594
595 static int ssleay_rand_status(void)
596         {
597         int ret;
598
599         CRYPTO_w_lock(CRYPTO_LOCK_RAND);
600
601         if (!initialized)
602                 ssleay_rand_initialize();
603         ret = entropy >= ENTROPY_NEEDED;
604
605         CRYPTO_w_unlock(CRYPTO_LOCK_RAND);
606
607         return ret;
608         }
609
610 #ifdef WINDOWS
611 #include <windows.h>
612 #include <openssl/rand.h>
613
614 int RAND_event(UINT iMsg, WPARAM wParam, LPARAM lParam)
615         {
616         double add_entropy=0;
617         SYSTEMTIME t;
618
619         switch (iMsg)
620                 {
621         case WM_KEYDOWN:
622                         {
623                         static WPARAM key;
624                         if (key != wParam)
625                                 add_entropy = 0.05;
626                         key = wParam;
627                         }
628                         break;
629         case WM_MOUSEMOVE:
630                         {
631                         static int lastx,lasty,lastdx,lastdy;
632                         int x,y,dx,dy;
633
634                         x=LOWORD(lParam);
635                         y=HIWORD(lParam);
636                         dx=lastx-x;
637                         dy=lasty-y;
638                         if (dx != 0 && dy != 0 && dx-lastdx != 0 && dy-lastdy != 0)
639                                 add_entropy=.2;
640                         lastx=x, lasty=y;
641                         lastdx=dx, lastdy=dy;
642                         }
643                 break;
644                 }
645
646         GetSystemTime(&t);
647         RAND_add(&iMsg, sizeof(iMsg), add_entropy);
648         RAND_add(&wParam, sizeof(wParam), 0);
649         RAND_add(&lParam, sizeof(lParam), 0);
650         RAND_add(&t, sizeof(t), 0);
651
652         return (RAND_status());
653         }
654
655 /*****************************************************************************
656  * Initialisation function for the SSL random generator.  Takes the contents
657  * of the screen as random seed.
658  *
659  * Created 960901 by Gertjan van Oosten, gertjan@West.NL, West Consulting B.V.
660  *
661  * Code adapted from
662  * <URL:http://www.microsoft.com/kb/developr/win_dk/q97193.htm>;
663  * the original copyright message is:
664  *
665  *   (C) Copyright Microsoft Corp. 1993.  All rights reserved.
666  *
667  *   You have a royalty-free right to use, modify, reproduce and
668  *   distribute the Sample Files (and/or any modified version) in
669  *   any way you find useful, provided that you agree that
670  *   Microsoft has no warranty obligations or liability for any
671  *   Sample Application Files which are modified.
672  */
673 /*
674  * I have modified the loading of bytes via RAND_seed() mechanism since
675  * the original would have been very very CPU intensive since RAND_seed()
676  * does an MD5 per 16 bytes of input.  The cost to digest 16 bytes is the same
677  * as that to digest 56 bytes.  So under the old system, a screen of
678  * 1024*768*256 would have been CPU cost of approximately 49,000 56 byte MD5
679  * digests or digesting 2.7 mbytes.  What I have put in place would
680  * be 48 16k MD5 digests, or effectively 48*16+48 MD5 bytes or 816 kbytes
681  * or about 3.5 times as much.
682  * - eric 
683  */
684 void RAND_screen(void)
685 {
686   HDC           hScrDC;         /* screen DC */
687   HDC           hMemDC;         /* memory DC */
688   HBITMAP       hBitmap;        /* handle for our bitmap */
689   HBITMAP       hOldBitmap;     /* handle for previous bitmap */
690   BITMAP        bm;             /* bitmap properties */
691   unsigned int  size;           /* size of bitmap */
692   char          *bmbits;        /* contents of bitmap */
693   int           w;              /* screen width */
694   int           h;              /* screen height */
695   int           y;              /* y-coordinate of screen lines to grab */
696   int           n = 16;         /* number of screen lines to grab at a time */
697
698   /* Create a screen DC and a memory DC compatible to screen DC */
699   hScrDC = CreateDC("DISPLAY", NULL, NULL, NULL);
700   hMemDC = CreateCompatibleDC(hScrDC);
701
702   /* Get screen resolution */
703   w = GetDeviceCaps(hScrDC, HORZRES);
704   h = GetDeviceCaps(hScrDC, VERTRES);
705
706   /* Create a bitmap compatible with the screen DC */
707   hBitmap = CreateCompatibleBitmap(hScrDC, w, n);
708
709   /* Select new bitmap into memory DC */
710   hOldBitmap = SelectObject(hMemDC, hBitmap);
711
712   /* Get bitmap properties */
713   GetObject(hBitmap, sizeof(BITMAP), (LPSTR)&bm);
714   size = (unsigned int)bm.bmWidthBytes * bm.bmHeight * bm.bmPlanes;
715
716   bmbits = Malloc(size);
717   if (bmbits) {
718     /* Now go through the whole screen, repeatedly grabbing n lines */
719     for (y = 0; y < h-n; y += n)
720         {
721         unsigned char md[MD_DIGEST_LENGTH];
722
723         /* Bitblt screen DC to memory DC */
724         BitBlt(hMemDC, 0, 0, w, n, hScrDC, 0, y, SRCCOPY);
725
726         /* Copy bitmap bits from memory DC to bmbits */
727         GetBitmapBits(hBitmap, size, bmbits);
728
729         /* Get the MD5 of the bitmap */
730         MD(bmbits,size,md);
731
732         /* Seed the random generator with the MD5 digest */
733         RAND_seed(md, MD_DIGEST_LENGTH);
734         }
735
736     Free(bmbits);
737   }
738
739   /* Select old bitmap back into memory DC */
740   hBitmap = SelectObject(hMemDC, hOldBitmap);
741
742   /* Clean up */
743   DeleteObject(hBitmap);
744   DeleteDC(hMemDC);
745   DeleteDC(hScrDC);
746 }
747 #endif