11.22 Gathering Entropy from Thread Timings

11.22.1 Problem

You want to collect some entropy without user intervention, hoping that there is some inherent, measurable entropy in the environment.

11.22.2 Solution

In 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:

  1. Launch and join on some fixed number of threads (at least 100).

  2. Mix in a timestamp when all threads have returned successfully.

  3. Estimate entropy based on the considerations discussed in Recipe 11.19.

  4. Wait at least a second before trying again, in hopes that there is additional entropy affecting the system later.

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

Recipe 4.14, Recipe 11.19



Secure Programming Cookbook for C and C++
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2005
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net