21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

*pHwnd = 0;<br />

return TRUE;<br />

}<br />

BOOL SpcGatherKeyboardEntropy(HINSTANCE hInstance, HWND hWndParent,<br />

BYTE *pbOutput, DWORD cbOutput) {<br />

MSG msg;<br />

BOOL bResult = FALSE;<br />

BYTE bLastScanCode = 0, *pbHashData = 0;<br />

HWND hwndDlg;<br />

DWORD cbHashData, dwByteCount = sizeof(DWORD), dwLastTime = 0;<br />

double dEntropy = 0.0;<br />

HCRYPTHASH hHash = 0;<br />

HCRYPTPROV hProvider = 0;<br />

SPC_KEYPRESS KeyPress;<br />

if (!CryptAcquireContext(&hProvider, 0, MS_DEF_PROV, PROV_RSA_FULL,<br />

CRYPT_VERIFYCONTEXT)) goto done;<br />

if (!CryptCreateHash(hProvider, CALG_SHA1, 0, 0, &hHash)) goto done;<br />

if (!CryptGetHashParam(hHash, HP_HASHSIZE, (BYTE *)&cbHashData, &dwByteCount,<br />

0)) goto done;<br />

if (cbOutput > cbHashData) goto done;<br />

if (!(pbHashData = (BYTE *)LocalAlloc(LMEM_FIXED, cbHashData))) goto done;<br />

hwndDlg = CreateDialog(hInstance, MAKEINTRESOURCE(SPC_KEYBOARD_DLGID),<br />

hWndParent, KeyboardEntropyProc);<br />

if (hwndDlg) {<br />

if (hWndParent) EnableWindow(hWndParent, FALSE);<br />

SetWindowLong(hwndDlg, DWL_USER, (LONG)&hwndDlg);<br />

SendDlgItemMessage(hwndDlg, SPC_PROGRESS_BARID, PBM_SETRANGE32, 0,<br />

cbOutput * 8);<br />

while (hwndDlg && GetMessage(&msg, 0, 0, 0) > 0) {<br />

if ((msg.message = = WM_KEYDOWN || msg.message = = WM_KEYUP) &&<br />

dEntropy < cbOutput * 8) {<br />

KeyPress.bScanCode = ((msg.lParam >> 16) & 0x0000000F);<br />

KeyPress.dwTickCount = GetTickCount( );<br />

CryptHashData(hHash, (BYTE *)&KeyPress, sizeof(KeyPress), 0);<br />

if (msg.message = = WM_KEYUP || (bLastScanCode != KeyPress.bScanCode &&<br />

KeyPress.dwTickCount - dwLastTime > 100)) {<br />

bLastScanCode = KeyPress.bScanCode;<br />

dwLastTime = KeyPress.dwTickCount;<br />

dEntropy += SPC_ENTROPY_PER_SAMPLE;<br />

SendDlgItemMessage(hwndDlg, SPC_PROGRESS_BARID, PBM_SETPOS,<br />

(WPARAM)dEntropy, 0);<br />

if (dEntropy >= cbOutput * 8) {<br />

EnableWindow(GetDlgItem(hwndDlg, IDOK), TRUE);<br />

SetFocus(GetDlgItem(hwndDlg, IDOK));<br />

MessageBeep(0xFFFFFFFF);<br />

}<br />

}<br />

continue;<br />

}<br />

if (!IsDialogMessage(hwndDlg, &msg)) {<br />

TranslateMessage(&msg);<br />

DispatchMessage(&msg);<br />

636 | Chapter 11: Random Numbers<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!