[ Team LiB ] |
11.22 Gathering Entropy from Thread Timings11.22.1 ProblemYou want to collect some entropy without user intervention, hoping that there is some inherent, measurable entropy in the environment. 11.22.2 SolutionIn practice, timing how long it takes to start up and stop a particular number of threads can provide a bit of entropy. For example, many Java virtual machines exclusively use such a technique to gather entropy. Because the thread timing data is only indirectly related to actual user input, it is good to be extremely conservative about the quality of this entropy source. We recommend the following methodology:
The following code spawns a particular number of threads that you can time, in the hope of getting some entropy. This code works on Unix implementations that have the pthreads library (the POSIX standard for threads). Linking is different depending on platform; check your local pthreads documentation. #include <pthread.h> static void *thread_stub(void *arg) { return 0; } void spc_time_threads(unsigned int numiters) { pthread_t tid; while (numiters--) if (!pthread_create(&tid, 0, thread_stub, 0)) pthread_join(tid, 0); } On Windows, the idea is the same, and the structure of the code is similar. Here is the same code as presented above, but implemented using the Win32 API: #include <windows.h> static DWORD WINAPI ThreadStub(LPVOID lpData) { return 0; } void SpcTimeThreads(DWORD dwIterCount) { DWORD dwThreadId; HANDLE hThread; while (dwIterCount--) { if ((hThread = CreateThread(0, 0, ThreadStub, 0, 0, &dwThreadId)) != 0) { WaitForSingleObject(hThread, INFINITE); CloseHandle(hThread); } } } See Recipe 4.14 for several different ways to get a timestamp. We strongly recommend that you use the most accurate method available on your platform. 11.22.3 See Also |
[ Team LiB ] |