📄 random.c
字号:
{
DWORD dwTimer = GetTickCount ();
DWORD j = dwLastTimer - dwTimer;
unsigned __int32 crc = 0L;
int i;
dwLastTimer = dwTimer;
for (i = 0; i < sizeof (MOUSEHOOKSTRUCT); i++)
{
crc = UPDC32 (((unsigned char *) lpMouse)[i], crc);
}
if (crc != lastCrc && crc != lastCrc2)
{
unsigned __int32 timeCrc = 0L;
for (i = 0; i < 4; i++)
{
timeCrc = UPDC32 (((unsigned char *) &j)[i], timeCrc);
}
for (i = 0; i < 4; i++)
{
timeCrc = UPDC32 (((unsigned char *) &dwTimer)[i], timeCrc);
}
EnterCriticalSection (&critRandProt);
RandaddInt32 ((unsigned __int32) (crc + timeCrc));
LeaveCriticalSection (&critRandProt);
}
lastCrc2 = lastCrc;
lastCrc = crc;
}
return 0;
}
/* Capture the keyboard, as long as the event is not the same as the last two
events, add the crc of the event to the pool along with the crc of the time
difference between this event and the last. The role of CRC-32 is merely to
perform diffusion. Note that the output of CRC-32 is subsequently processed
using a cryptographically secure hash algorithm. */
LRESULT CALLBACK
KeyboardProc (int nCode, WPARAM wParam, LPARAM lParam)
{
static int lLastKey, lLastKey2;
static DWORD dwLastTimer;
int nKey = (lParam & 0x00ff0000) >> 16;
int nCapture = 0;
if (nCode < 0)
return CallNextHookEx (hMouse, nCode, wParam, lParam);
if ((lParam & 0x0000ffff) == 1 && !(lParam & 0x20000000) &&
(lParam & 0x80000000))
{
if (nKey != lLastKey)
nCapture = 1; /* Capture this key */
else if (nKey != lLastKey2)
nCapture = 1; /* Allow for one repeat */
}
if (nCapture)
{
DWORD dwTimer = GetTickCount ();
DWORD j = dwLastTimer - dwTimer;
unsigned __int32 timeCrc = 0L;
int i;
dwLastTimer = dwTimer;
lLastKey2 = lLastKey;
lLastKey = nKey;
for (i = 0; i < 4; i++)
{
timeCrc = UPDC32 (((unsigned char *) &j)[i], timeCrc);
}
for (i = 0; i < 4; i++)
{
timeCrc = UPDC32 (((unsigned char *) &dwTimer)[i], timeCrc);
}
EnterCriticalSection (&critRandProt);
RandaddInt32 ((unsigned __int32) (crc32int(&lParam) + timeCrc));
LeaveCriticalSection (&critRandProt);
}
return CallNextHookEx (hMouse, nCode, wParam, lParam);
}
/* This is the thread function which will poll the system for randomness */
void
ThreadSafeThreadFunction (void *dummy)
{
if (dummy); /* Remove unused parameter warning */
for (;;)
{
EnterCriticalSection (&critRandProt);
if (bThreadTerminate)
{
bThreadTerminate = FALSE;
LeaveCriticalSection (&critRandProt);
_endthread ();
}
else if (bFastPollEnabled)
{
FastPoll ();
}
LeaveCriticalSection (&critRandProt);
Sleep (FASTPOLL_INTERVAL);
}
}
/* Type definitions for function pointers to call NetAPI32 functions */
typedef
DWORD (WINAPI * NETSTATISTICSGET) (LPWSTR szServer, LPWSTR szService,
DWORD dwLevel, DWORD dwOptions,
LPBYTE * lpBuffer);
typedef
DWORD (WINAPI * NETAPIBUFFERSIZE) (LPVOID lpBuffer, LPDWORD cbBuffer);
typedef
DWORD (WINAPI * NETAPIBUFFERFREE) (LPVOID lpBuffer);
NETSTATISTICSGET pNetStatisticsGet = NULL;
NETAPIBUFFERSIZE pNetApiBufferSize = NULL;
NETAPIBUFFERFREE pNetApiBufferFree = NULL;
/* This is the slowpoll function which gathers up network/hard drive
performance data for the random pool */
BOOL SlowPoll (void)
{
int i;
static int isWorkstation = -1;
static int cbPerfData = 0x10000;
HANDLE hDevice;
LPBYTE lpBuffer;
DWORD dwSize, status;
LPWSTR lpszLanW, lpszLanS;
int nDrive;
/* Find out whether this is an NT server or workstation if necessary */
if (isWorkstation == -1)
{
HKEY hKey;
if (RegOpenKeyEx (HKEY_LOCAL_MACHINE,
"SYSTEM\\CurrentControlSet\\Control\\ProductOptions",
0, KEY_READ, &hKey) == ERROR_SUCCESS)
{
unsigned char szValue[32];
dwSize = sizeof (szValue);
isWorkstation = TRUE;
status = RegQueryValueEx (hKey, "ProductType", 0, NULL,
szValue, &dwSize);
if (status == ERROR_SUCCESS && _stricmp ((char *) szValue, "WinNT"))
/* Note: There are (at least) three cases for
ProductType: WinNT = NT Workstation,
ServerNT = NT Server, LanmanNT = NT Server
acting as a Domain Controller */
isWorkstation = FALSE;
RegCloseKey (hKey);
}
}
/* Initialize the NetAPI32 function pointers if necessary */
if (hNetAPI32 == NULL)
{
/* Obtain a handle to the module containing the Lan Manager
functions */
hNetAPI32 = LoadLibrary ("NETAPI32.DLL");
if (hNetAPI32 != NULL)
{
/* Now get pointers to the functions */
pNetStatisticsGet = (NETSTATISTICSGET) GetProcAddress (hNetAPI32,
"NetStatisticsGet");
pNetApiBufferSize = (NETAPIBUFFERSIZE) GetProcAddress (hNetAPI32,
"NetApiBufferSize");
pNetApiBufferFree = (NETAPIBUFFERFREE) GetProcAddress (hNetAPI32,
"NetApiBufferFree");
/* Make sure we got valid pointers for every NetAPI32
function */
if (pNetStatisticsGet == NULL ||
pNetApiBufferSize == NULL ||
pNetApiBufferFree == NULL)
{
/* Free the library reference and reset the
static handle */
FreeLibrary (hNetAPI32);
hNetAPI32 = NULL;
}
}
}
/* Get network statistics. Note: Both NT Workstation and NT Server
by default will be running both the workstation and server
services. The heuristic below is probably useful though on the
assumption that the majority of the network traffic will be via
the appropriate service */
lpszLanW = (LPWSTR) WIDE ("LanmanWorkstation");
lpszLanS = (LPWSTR) WIDE ("LanmanServer");
if (hNetAPI32 &&
pNetStatisticsGet (NULL,
isWorkstation ? lpszLanW : lpszLanS,
0, 0, &lpBuffer) == 0)
{
pNetApiBufferSize (lpBuffer, &dwSize);
RandaddBuf ((unsigned char *) lpBuffer, dwSize);
pNetApiBufferFree (lpBuffer);
}
/* Get disk I/O statistics for all the hard drives */
for (nDrive = 0;; nDrive++)
{
DISK_PERFORMANCE diskPerformance;
char szDevice[24];
/* Check whether we can access this device */
sprintf (szDevice, "\\\\.\\PhysicalDrive%d", nDrive);
hDevice = CreateFile (szDevice, 0, FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, 0, NULL);
if (hDevice == INVALID_HANDLE_VALUE)
break;
/* Note: This only works if you have turned on the disk
performance counters with 'diskperf -y'. These counters
are off by default */
if (DeviceIoControl (hDevice, IOCTL_DISK_PERFORMANCE, NULL, 0,
&diskPerformance, sizeof (DISK_PERFORMANCE),
&dwSize, NULL))
{
RandaddBuf ((unsigned char *) &diskPerformance, dwSize);
}
CloseHandle (hDevice);
}
// CryptoAPI
for (i = 0; i < 100; i++)
{
if (hCryptProv && CryptGenRandom(hCryptProv, sizeof (buffer), buffer))
RandaddBuf (buffer, sizeof (buffer));
}
burn(buffer, sizeof (buffer));
Randmix();
return TRUE;
}
/* This is the fastpoll function which gathers up info by calling various api's */
BOOL FastPoll (void)
{
int nOriginalRandIndex = nRandIndex;
static BOOL addedFixedItems = FALSE;
FILETIME creationTime, exitTime, kernelTime, userTime;
DWORD minimumWorkingSetSize, maximumWorkingSetSize;
LARGE_INTEGER performanceCount;
MEMORYSTATUS memoryStatus;
HANDLE handle;
POINT point;
/* Get various basic pieces of system information */
RandaddInt32 (GetActiveWindow ()); /* Handle of active window */
RandaddInt32 (GetCapture ()); /* Handle of window with mouse
capture */
RandaddInt32 (GetClipboardOwner ()); /* Handle of clipboard owner */
RandaddInt32 (GetClipboardViewer ()); /* Handle of start of
clpbd.viewer list */
RandaddInt32 (GetCurrentProcess ()); /* Pseudohandle of current
process */
RandaddInt32 (GetCurrentProcessId ()); /* Current process ID */
RandaddInt32 (GetCurrentThread ()); /* Pseudohandle of current
thread */
RandaddInt32 (GetCurrentThreadId ()); /* Current thread ID */
RandaddInt32 (GetCurrentTime ()); /* Milliseconds since Windows
started */
RandaddInt32 (GetDesktopWindow ()); /* Handle of desktop window */
RandaddInt32 (GetFocus ()); /* Handle of window with kb.focus */
RandaddInt32 (GetInputState ()); /* Whether sys.queue has any events */
RandaddInt32 (GetMessagePos ()); /* Cursor pos.for last message */
RandaddInt32 (GetMessageTime ()); /* 1 ms time for last message */
RandaddInt32 (GetOpenClipboardWindow ()); /* Handle of window with
clpbd.open */
RandaddInt32 (GetProcessHeap ()); /* Handle of process heap */
RandaddInt32 (GetProcessWindowStation ()); /* Handle of procs
window station */
RandaddInt32 (GetQueueStatus (QS_ALLEVENTS)); /* Types of events in
input queue */
/* Get multiword system information */
GetCaretPos (&point); /* Current caret position */
RandaddBuf ((unsigned char *) &point, sizeof (POINT));
GetCursorPos (&point); /* Current mouse cursor position */
RandaddBuf ((unsigned char *) &point, sizeof (POINT));
/* Get percent of memory in use, bytes of physical memory, bytes of
free physical memory, bytes in paging file, free bytes in paging
file, user bytes of address space, and free user bytes */
memoryStatus.dwLength = sizeof (MEMORYSTATUS);
GlobalMemoryStatus (&memoryStatus);
RandaddBuf ((unsigned char *) &memoryStatus, sizeof (MEMORYSTATUS));
/* Get thread and process creation time, exit time, time in kernel
mode, and time in user mode in 100ns intervals */
handle = GetCurrentThread ();
GetThreadTimes (handle, &creationTime, &exitTime, &kernelTime, &userTime);
RandaddBuf ((unsigned char *) &creationTime, sizeof (FILETIME));
RandaddBuf ((unsigned char *) &exitTime, sizeof (FILETIME));
RandaddBuf ((unsigned char *) &kernelTime, sizeof (FILETIME));
RandaddBuf ((unsigned char *) &userTime, sizeof (FILETIME));
handle = GetCurrentProcess ();
GetProcessTimes (handle, &creationTime, &exitTime, &kernelTime, &userTime);
RandaddBuf ((unsigned char *) &creationTime, sizeof (FILETIME));
RandaddBuf ((unsigned char *) &exitTime, sizeof (FILETIME));
RandaddBuf ((unsigned char *) &kernelTime, sizeof (FILETIME));
RandaddBuf ((unsigned char *) &userTime, sizeof (FILETIME));
/* Get the minimum and maximum working set size for the current
process */
GetProcessWorkingSetSize (handle, &minimumWorkingSetSize,
&maximumWorkingSetSize);
RandaddInt32 (minimumWorkingSetSize);
RandaddInt32 (maximumWorkingSetSize);
/* The following are fixed for the lifetime of the process so we only
add them once */
if (addedFixedItems == 0)
{
STARTUPINFO startupInfo;
/* Get name of desktop, console window title, new window
position and size, window flags, and handles for stdin,
stdout, and stderr */
startupInfo.cb = sizeof (STARTUPINFO);
GetStartupInfo (&startupInfo);
RandaddBuf ((unsigned char *) &startupInfo, sizeof (STARTUPINFO));
addedFixedItems = TRUE;
}
/* The docs say QPC can fail if appropriate hardware is not
available. It works on 486 & Pentium boxes, but hasn't been tested
for 386 or RISC boxes */
if (QueryPerformanceCounter (&performanceCount))
RandaddBuf ((unsigned char *) &performanceCount, sizeof (LARGE_INTEGER));
else
{
/* Millisecond accuracy at best... */
DWORD dwTicks = GetTickCount ();
RandaddBuf ((unsigned char *) &dwTicks, sizeof (dwTicks));
}
// CryptoAPI
if (hCryptProv && CryptGenRandom(hCryptProv, sizeof (buffer), buffer))
RandaddBuf (buffer, sizeof (buffer));
/* Apply the pool mixing function */
Randmix();
/* Restore the original pool cursor position. If this wasn't done, mouse coordinates
could be written to a limited area of the pool, especially when moving the mouse
uninterruptedly. The severity of the problem would depend on the length of data
written by FastPoll (if it was equal to the size of the pool, mouse coordinates
would be written only to a particular 4-byte area, whenever moving the mouse
uninterruptedly). */
nRandIndex = nOriginalRandIndex;
return TRUE;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -