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.

HCRYPTKEY SpcGetDerivedKey(HCRYPTPROV hProvider, ALG_ID Algid, LPTSTR password) {<br />

BOOL bResult;<br />

DWORD cbData;<br />

HCRYPTKEY hKey;<br />

HCRYPTHASH hHash;<br />

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

cbData = lstrlen(password) * sizeof(TCHAR);<br />

if (!CryptHashData(hHash, (BYTE *)password, cbData, 0)) {<br />

CryptDestroyHash(hHash);<br />

return 0;<br />

}<br />

bResult = CryptDeriveKey(hProvider, Algid, hHash, CRYPT_EXPORTABLE, &hKey);<br />

CryptDestroyHash(hHash);<br />

return (bResult ? hKey : 0);<br />

}<br />

Importing a key with CryptImportKey( ) is, in most cases, just as easy as generating a<br />

new random key. Most often, you’ll be importing data obtained directly from<br />

CryptExportKey( ), so you’ll already have an encrypted key in the form of a<br />

SIMPLEBLOB, as required by CryptImportKey( ). If you need to import raw key data,<br />

things get a whole lot trickier—see Recipe 5.26 for details.<br />

HCRYPTKEY SpcImportKey(HCRYPTPROV hProvider, BYTE *pbData, DWORD dwDataLen,<br />

HCRYPTKEY hPublicKey) {<br />

HCRYPTKEY hKey;<br />

if (!CryptImportKey(hProvider, pbData, dwDataLen, hPublicKey, CRYPT_EXPORTABLE,<br />

&hKey)) return 0;<br />

return hKey;<br />

}<br />

When a key object is created, the cipher to use is tied to that key, and it must be<br />

specified as an argument to either CryptGenKey( ) or CryptDeriveKey( ). It is not<br />

required as an argument by CryptImportKey( ) because the cipher information is<br />

stored as part of the SIMPLEBLOB structure that is required. Table 5-8 lists the symmetric<br />

ciphers that are available using one of the three Microsoft CSPs.<br />

Table 5-8. Symmetric ciphers supported by Microsoft Cryptographic Service Providers<br />

Cipher<br />

Cryptographic<br />

Service Provider ALG_ID constant Key length Block size<br />

RC2 Base, Enhanced,<br />

AES<br />

CALG_RC2 40 bits 64 bits<br />

RC4 Base CALG_RC4 40 bits n/a<br />

RC4 Enhanced, AES CALG_RC4 128 bits n/a<br />

DES Enhanced, AES CALG_DES 56 bits 64 bits<br />

2-key Triple-DES Enhanced, AES CALG_3DES_112 112 bits (effective) 64 bits<br />

3-key Triple-DES Enhanced, AES CALG_3DES 168 bits (effective) 64 bits<br />

AES AES CALG_AES_128 128 bits 128 bits<br />

240 | Chapter 5: Symmetric Encryption<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!