6 #include "Windows/Synchronization.h"
\r
11 #define USE_POSIX_TIME
\r
12 #define USE_POSIX_TIME2
\r
15 #ifdef USE_POSIX_TIME
\r
17 #ifdef USE_POSIX_TIME2
\r
18 #include <sys/time.h>
\r
22 // This is not very good random number generator.
\r
23 // Please use it only for salt.
\r
24 // First generated data block depends from timer and processID.
\r
25 // Other generated data blocks depend from previous state
\r
26 // Maybe it's possible to restore original timer value from generated value.
\r
28 void CRandomGenerator::Init()
\r
30 NCrypto::NSha1::CContext hash;
\r
34 DWORD w = ::GetCurrentProcessId();
\r
35 hash.Update((const Byte *)&w, sizeof(w));
\r
36 w = ::GetCurrentThreadId();
\r
37 hash.Update((const Byte *)&w, sizeof(w));
\r
39 pid_t pid = getpid();
\r
40 hash.Update((const Byte *)&pid, sizeof(pid));
\r
42 hash.Update((const Byte *)&pid, sizeof(pid));
\r
45 for (int i = 0; i < 1000; i++)
\r
49 if (::QueryPerformanceCounter(&v))
\r
50 hash.Update((const Byte *)&v.QuadPart, sizeof(v.QuadPart));
\r
53 #ifdef USE_POSIX_TIME
\r
54 #ifdef USE_POSIX_TIME2
\r
56 if (gettimeofday(&v, 0) == 0)
\r
58 hash.Update((const Byte *)&v.tv_sec, sizeof(v.tv_sec));
\r
59 hash.Update((const Byte *)&v.tv_usec, sizeof(v.tv_usec));
\r
62 time_t v2 = time(NULL);
\r
63 hash.Update((const Byte *)&v2, sizeof(v2));
\r
66 DWORD tickCount = ::GetTickCount();
\r
67 hash.Update((const Byte *)&tickCount, sizeof(tickCount));
\r
69 for (int j = 0; j < 100; j++)
\r
73 hash.Update(_buff, NCrypto::NSha1::kDigestSize);
\r
80 static NWindows::NSynchronization::CCriticalSection g_CriticalSection;
\r
82 void CRandomGenerator::Generate(Byte *data, unsigned int size)
\r
84 g_CriticalSection.Enter();
\r
89 NCrypto::NSha1::CContext hash;
\r
92 hash.Update(_buff, NCrypto::NSha1::kDigestSize);
\r
96 UInt32 salt = 0xF672ABD1;
\r
97 hash.Update((const Byte *)&salt, sizeof(salt));
\r
98 hash.Update(_buff, NCrypto::NSha1::kDigestSize);
\r
99 Byte buff[NCrypto::NSha1::kDigestSize];
\r
101 for (unsigned int i = 0; i < NCrypto::NSha1::kDigestSize && size > 0; i++, size--)
\r
104 g_CriticalSection.Leave();
\r
107 CRandomGenerator g_RandomGenerator;
\r