21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

hKey<br />

Key to use for performing the encryption.<br />

bFinal<br />

Boolean value that should be passed as FALSE for incremental encryption except<br />

for the last piece of plaintext to be encrypted. To encrypt all at once, pass TRUE<br />

for bFinal in the single call to SpcEncrypt( ). When CryptEncrypt( ) gets the final<br />

plaintext to encrypt, it performs any cleanup that is needed to reset the key<br />

object back to a state where a new encryption or decryption operation can be<br />

performed with it.<br />

pbData<br />

Plaintext.<br />

cbData<br />

Pointer to a DWORD type that should hold the length of the plaintext pbData buffer.<br />

If the function returns successfully, it will be modified to hold the number of<br />

bytes returned in the ciphertext buffer.<br />

Decryption works similarly to encryption. The function CryptDecrypt( ) performs<br />

decryption either all at once or incrementally, and it also supports the convenience<br />

function of passing plaintext data to a hash object to compute the hash of the plaintext<br />

as it is decrypted. The primary difference between encryption and decryption is<br />

that when decrypting, the plaintext will never be any longer than the ciphertext, so the<br />

handling of data buffers is less complicated. The following function, SpcDecrypt( ),<br />

mirrors the SpcEncrypt( ) function presented previously.<br />

BYTE *SpcDecrypt(HCRYPTKEY hKey, BOOL bFinal, BYTE *pbData, DWORD *cbData) {<br />

BYTE *pbResult;<br />

DWORD dwBlockLen, dwDataLen;<br />

ALG_ID Algid;<br />

dwDataLen = sizeof(ALG_ID);<br />

if (!CryptGetKeyParam(hKey, KP_ALGID, (BYTE *)&Algid, &dwDataLen, 0)) return 0;<br />

if (GET_ALG_TYPE(Algid) != ALG_TYPE_STREAM) {<br />

dwDataLen = sizeof(DWORD);<br />

if (!CryptGetKeyParam(hKey, KP_BLOCKLEN, (BYTE *)&dwBlockLen, &dwDataLen, 0))<br />

return 0;<br />

dwDataLen = ((*cbData + dwBlockLen - 1) / dwBlockLen) * dwBlockLen;<br />

if (!(pbResult = (BYTE *)LocalAlloc(LMEM_FIXED, dwDataLen))) return 0;<br />

} else {<br />

if (!(pbResult = (BYTE *)LocalAlloc(LMEM_FIXED, *cbData))) return 0;<br />

}<br />

CopyMemory(pbResult, pbData, *cbData);<br />

if (!CryptDecrypt(hKey, 0, bFinal, 0, pbResult, cbData)) {<br />

LocalFree(pbResult);<br />

return 0;<br />

}<br />

return pbResult;<br />

}<br />

Using Symmetric Encryption with Microsoft’s CryptoAPI | 243<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!