mciqtz: Improve MCIQTZ_mciSet traces.
[wine] / dlls / rsaenh / rsaenh.c
1 /*
2  * dlls/rsaenh/rsaenh.c
3  * RSAENH - RSA encryption for Wine
4  *
5  * Copyright 2002 TransGaming Technologies (David Hammerton)
6  * Copyright 2004 Mike McCormack for CodeWeavers
7  * Copyright 2004, 2005 Michael Jung
8  * Copyright 2007 Vijay Kiran Kamuju
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24
25 #include "config.h"
26 #include "wine/port.h"
27 #include "wine/library.h"
28 #include "wine/debug.h"
29
30 #include <stdarg.h>
31 #include <stdio.h>
32
33 #include "windef.h"
34 #include "winbase.h"
35 #include "winreg.h"
36 #include "wincrypt.h"
37 #include "handle.h"
38 #include "implglue.h"
39 #include "objbase.h"
40
41 WINE_DEFAULT_DEBUG_CHANNEL(crypt);
42
43 /******************************************************************************
44  * CRYPTHASH - hash objects
45  */
46 #define RSAENH_MAGIC_HASH           0x85938417u
47 #define RSAENH_MAX_HASH_SIZE        104
48 #define RSAENH_HASHSTATE_HASHING    1
49 #define RSAENH_HASHSTATE_FINISHED   2
50 typedef struct _RSAENH_TLS1PRF_PARAMS
51 {
52     CRYPT_DATA_BLOB blobLabel;
53     CRYPT_DATA_BLOB blobSeed;
54 } RSAENH_TLS1PRF_PARAMS;
55
56 typedef struct tagCRYPTHASH
57 {
58     OBJECTHDR    header;
59     ALG_ID       aiAlgid;
60     HCRYPTKEY    hKey;
61     HCRYPTPROV   hProv;
62     DWORD        dwHashSize;
63     DWORD        dwState;
64     HASH_CONTEXT context;
65     BYTE         abHashValue[RSAENH_MAX_HASH_SIZE];
66     PHMAC_INFO   pHMACInfo;
67     RSAENH_TLS1PRF_PARAMS tpPRFParams;
68 } CRYPTHASH;
69
70 /******************************************************************************
71  * CRYPTKEY - key objects
72  */
73 #define RSAENH_MAGIC_KEY           0x73620457u
74 #define RSAENH_MAX_KEY_SIZE        48
75 #define RSAENH_MAX_BLOCK_SIZE      24
76 #define RSAENH_KEYSTATE_IDLE       0
77 #define RSAENH_KEYSTATE_ENCRYPTING 1
78 #define RSAENH_KEYSTATE_MASTERKEY  2
79 typedef struct _RSAENH_SCHANNEL_INFO 
80 {
81     SCHANNEL_ALG saEncAlg;
82     SCHANNEL_ALG saMACAlg;
83     CRYPT_DATA_BLOB blobClientRandom;
84     CRYPT_DATA_BLOB blobServerRandom;
85 } RSAENH_SCHANNEL_INFO;
86
87 typedef struct tagCRYPTKEY
88 {
89     OBJECTHDR   header;
90     ALG_ID      aiAlgid;
91     HCRYPTPROV  hProv;
92     DWORD       dwMode;
93     DWORD       dwModeBits;
94     DWORD       dwPermissions;
95     DWORD       dwKeyLen;
96     DWORD       dwEffectiveKeyLen;
97     DWORD       dwSaltLen;
98     DWORD       dwBlockLen;
99     DWORD       dwState;
100     KEY_CONTEXT context;    
101     BYTE        abKeyValue[RSAENH_MAX_KEY_SIZE];
102     BYTE        abInitVector[RSAENH_MAX_BLOCK_SIZE];
103     BYTE        abChainVector[RSAENH_MAX_BLOCK_SIZE];
104     RSAENH_SCHANNEL_INFO siSChannelInfo;
105 } CRYPTKEY;
106
107 /******************************************************************************
108  * KEYCONTAINER - key containers
109  */
110 #define RSAENH_PERSONALITY_BASE        0u
111 #define RSAENH_PERSONALITY_STRONG      1u
112 #define RSAENH_PERSONALITY_ENHANCED    2u
113 #define RSAENH_PERSONALITY_SCHANNEL    3u
114 #define RSAENH_PERSONALITY_AES         4u
115
116 #define RSAENH_MAGIC_CONTAINER         0x26384993u
117 typedef struct tagKEYCONTAINER
118 {
119     OBJECTHDR    header;
120     DWORD        dwFlags;
121     DWORD        dwPersonality;
122     DWORD        dwEnumAlgsCtr;
123     DWORD        dwEnumContainersCtr;
124     CHAR         szName[MAX_PATH];
125     CHAR         szProvName[MAX_PATH];
126     HCRYPTKEY    hKeyExchangeKeyPair;
127     HCRYPTKEY    hSignatureKeyPair;
128 } KEYCONTAINER;
129
130 /******************************************************************************
131  * Some magic constants
132  */
133 #define RSAENH_ENCRYPT                    1
134 #define RSAENH_DECRYPT                    0    
135 #define RSAENH_HMAC_DEF_IPAD_CHAR      0x36
136 #define RSAENH_HMAC_DEF_OPAD_CHAR      0x5c
137 #define RSAENH_HMAC_DEF_PAD_LEN          64
138 #define RSAENH_DES_EFFECTIVE_KEYLEN      56
139 #define RSAENH_DES_STORAGE_KEYLEN        64
140 #define RSAENH_3DES112_EFFECTIVE_KEYLEN 112
141 #define RSAENH_3DES112_STORAGE_KEYLEN   128
142 #define RSAENH_3DES_EFFECTIVE_KEYLEN    168
143 #define RSAENH_3DES_STORAGE_KEYLEN      192
144 #define RSAENH_MAGIC_RSA2        0x32415352
145 #define RSAENH_MAGIC_RSA1        0x31415352
146 #define RSAENH_PKC_BLOCKTYPE           0x02
147 #define RSAENH_SSL3_VERSION_MAJOR         3
148 #define RSAENH_SSL3_VERSION_MINOR         0
149 #define RSAENH_TLS1_VERSION_MAJOR         3
150 #define RSAENH_TLS1_VERSION_MINOR         1
151 #define RSAENH_REGKEY "Software\\Wine\\Crypto\\RSA\\%s"
152
153 #define RSAENH_MIN(a,b) ((a)<(b)?(a):(b))
154 /******************************************************************************
155  * aProvEnumAlgsEx - Defines the capabilities of the CSP personalities.
156  */
157 #define RSAENH_MAX_ENUMALGS 24
158 #define RSAENH_PCT1_SSL2_SSL3_TLS1 (CRYPT_FLAG_PCT1|CRYPT_FLAG_SSL2|CRYPT_FLAG_SSL3|CRYPT_FLAG_TLS1)
159 static const PROV_ENUMALGS_EX aProvEnumAlgsEx[5][RSAENH_MAX_ENUMALGS+1] =
160 {
161  {
162   {CALG_RC2,       40, 40,   56,0,                    4,"RC2",     24,"RSA Data Security's RC2"},
163   {CALG_RC4,       40, 40,   56,0,                    4,"RC4",     24,"RSA Data Security's RC4"},
164   {CALG_DES,       56, 56,   56,0,                    4,"DES",     31,"Data Encryption Standard (DES)"},
165   {CALG_SHA,      160,160,  160,CRYPT_FLAG_SIGNING,   6,"SHA-1",   30,"Secure Hash Algorithm (SHA-1)"},
166   {CALG_MD2,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD2",     23,"Message Digest 2 (MD2)"},
167   {CALG_MD4,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD4",     23,"Message Digest 4 (MD4)"},
168   {CALG_MD5,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD5",     23,"Message Digest 5 (MD5)"},
169   {CALG_SSL3_SHAMD5,288,288,288,0,                   12,"SSL3 SHAMD5",12,"SSL3 SHAMD5"},
170   {CALG_MAC,        0,  0,    0,0,                    4,"MAC",     28,"Message Authentication Code"},
171   {CALG_RSA_SIGN, 512,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_SIGN",14,"RSA Signature"},
172   {CALG_RSA_KEYX, 512,384, 1024,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_KEYX",17,"RSA Key Exchange"},
173   {CALG_HMAC,       0,  0,    0,0,                    5,"HMAC",    18,"Hugo's MAC (HMAC)"},
174   {0,               0,  0,    0,0,                    1,"",         1,""}
175  },
176  {
177   {CALG_RC2,      128, 40,  128,0,                    4,"RC2",     24,"RSA Data Security's RC2"},
178   {CALG_RC4,      128, 40,  128,0,                    4,"RC4",     24,"RSA Data Security's RC4"},
179   {CALG_DES,       56, 56,   56,0,                    4,"DES",     31,"Data Encryption Standard (DES)"},
180   {CALG_3DES_112, 112,112,  112,0,                   13,"3DES TWO KEY",19,"Two Key Triple DES"},
181   {CALG_3DES,     168,168,  168,0,                    5,"3DES",    21,"Three Key Triple DES"},
182   {CALG_SHA,      160,160,  160,CRYPT_FLAG_SIGNING,   6,"SHA-1",   30,"Secure Hash Algorithm (SHA-1)"},
183   {CALG_MD2,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD2",     23,"Message Digest 2 (MD2)"},
184   {CALG_MD4,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD4",     23,"Message Digest 4 (MD4)"},
185   {CALG_MD5,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD5",     23,"Message Digest 5 (MD5)"},
186   {CALG_SSL3_SHAMD5,288,288,288,0,                   12,"SSL3 SHAMD5",12,"SSL3 SHAMD5"},
187   {CALG_MAC,        0,  0,    0,0,                    4,"MAC",     28,"Message Authentication Code"},
188   {CALG_RSA_SIGN,1024,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_SIGN",14,"RSA Signature"},
189   {CALG_RSA_KEYX,1024,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_KEYX",17,"RSA Key Exchange"},
190   {CALG_HMAC,       0,  0,    0,0,                    5,"HMAC",    18,"Hugo's MAC (HMAC)"},
191   {0,               0,  0,    0,0,                    1,"",         1,""}
192  },
193  {
194   {CALG_RC2,      128, 40,  128,0,                    4,"RC2",     24,"RSA Data Security's RC2"},
195   {CALG_RC4,      128, 40,  128,0,                    4,"RC4",     24,"RSA Data Security's RC4"},
196   {CALG_DES,       56, 56,   56,0,                    4,"DES",     31,"Data Encryption Standard (DES)"},
197   {CALG_3DES_112, 112,112,  112,0,                   13,"3DES TWO KEY",19,"Two Key Triple DES"},
198   {CALG_3DES,     168,168,  168,0,                    5,"3DES",    21,"Three Key Triple DES"},
199   {CALG_SHA,      160,160,  160,CRYPT_FLAG_SIGNING,   6,"SHA-1",   30,"Secure Hash Algorithm (SHA-1)"},
200   {CALG_MD2,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD2",     23,"Message Digest 2 (MD2)"},
201   {CALG_MD4,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD4",     23,"Message Digest 4 (MD4)"},
202   {CALG_MD5,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD5",     23,"Message Digest 5 (MD5)"},
203   {CALG_SSL3_SHAMD5,288,288,288,0,                   12,"SSL3 SHAMD5",12,"SSL3 SHAMD5"},
204   {CALG_MAC,        0,  0,    0,0,                    4,"MAC",     28,"Message Authentication Code"},
205   {CALG_RSA_SIGN,1024,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_SIGN",14,"RSA Signature"},
206   {CALG_RSA_KEYX,1024,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_KEYX",17,"RSA Key Exchange"},
207   {CALG_HMAC,       0,  0,    0,0,                    5,"HMAC",    18,"Hugo's MAC (HMAC)"},
208   {0,               0,  0,    0,0,                    1,"",         1,""}
209  },
210  {
211   {CALG_RC2,      128, 40,  128,RSAENH_PCT1_SSL2_SSL3_TLS1, 4,"RC2",        24,"RSA Data Security's RC2"},
212   {CALG_RC4,      128, 40,  128,RSAENH_PCT1_SSL2_SSL3_TLS1, 4,"RC4",        24,"RSA Data Security's RC4"},
213   {CALG_DES,       56, 56,   56,RSAENH_PCT1_SSL2_SSL3_TLS1, 4,"DES",        31,"Data Encryption Standard (DES)"},
214   {CALG_3DES_112, 112,112,  112,RSAENH_PCT1_SSL2_SSL3_TLS1,13,"3DES TWO KEY",19,"Two Key Triple DES"},
215   {CALG_3DES,     168,168,  168,RSAENH_PCT1_SSL2_SSL3_TLS1, 5,"3DES",       21,"Three Key Triple DES"},
216   {CALG_SHA,160,160,160,CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1,6,"SHA-1",30,"Secure Hash Algorithm (SHA-1)"},
217   {CALG_MD5,128,128,128,CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1,4,"MD5",23,"Message Digest 5 (MD5)"},
218   {CALG_SSL3_SHAMD5,288,288,288,0,                         12,"SSL3 SHAMD5",12,"SSL3 SHAMD5"},
219   {CALG_MAC,        0,  0,    0,0,                          4,"MAC",        28,"Message Authentication Code"},
220   {CALG_RSA_SIGN,1024,384,16384,CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1,9,"RSA_SIGN",14,"RSA Signature"},
221   {CALG_RSA_KEYX,1024,384,16384,CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1,9,"RSA_KEYX",17,"RSA Key Exchange"},
222   {CALG_HMAC,       0,  0,    0,0,                          5,"HMAC",       18,"Hugo's MAC (HMAC)"},
223   {CALG_PCT1_MASTER,128,128,128,CRYPT_FLAG_PCT1,           12,"PCT1 MASTER",12,"PCT1 Master"},
224   {CALG_SSL2_MASTER,40,40,  192,CRYPT_FLAG_SSL2,           12,"SSL2 MASTER",12,"SSL2 Master"},
225   {CALG_SSL3_MASTER,384,384,384,CRYPT_FLAG_SSL3,           12,"SSL3 MASTER",12,"SSL3 Master"},
226   {CALG_TLS1_MASTER,384,384,384,CRYPT_FLAG_TLS1,           12,"TLS1 MASTER",12,"TLS1 Master"},
227   {CALG_SCHANNEL_MASTER_HASH,0,0,-1,0,                     16,"SCH MASTER HASH",21,"SChannel Master Hash"},
228   {CALG_SCHANNEL_MAC_KEY,0,0,-1,0,                         12,"SCH MAC KEY",17,"SChannel MAC Key"},
229   {CALG_SCHANNEL_ENC_KEY,0,0,-1,0,                         12,"SCH ENC KEY",24,"SChannel Encryption Key"},
230   {CALG_TLS1PRF,    0,  0,   -1,0,                          9,"TLS1 PRF",   28,"TLS1 Pseudo Random Function"},
231   {0,               0,  0,    0,0,                          1,"",            1,""}
232  },
233  {
234   {CALG_RC2,      128, 40,  128,0,                    4,"RC2",     24,"RSA Data Security's RC2"},
235   {CALG_RC4,      128, 40,  128,0,                    4,"RC4",     24,"RSA Data Security's RC4"},
236   {CALG_DES,       56, 56,   56,0,                    4,"DES",     31,"Data Encryption Standard (DES)"},
237   {CALG_3DES_112, 112,112,  112,0,                   13,"3DES TWO KEY",19,"Two Key Triple DES"},
238   {CALG_3DES,     168,168,  168,0,                    5,"3DES",    21,"Three Key Triple DES"},
239   {CALG_AES,      128,128,  128,0,                    4,"AES",     35,"Advanced Encryption Standard (AES)"},
240   {CALG_AES_128,  128,128,  128,0,                    8,"AES-128", 39,"Advanced Encryption Standard (AES-128)"},
241   {CALG_AES_192,  192,192,  192,0,                    8,"AES-192", 39,"Advanced Encryption Standard (AES-192)"},
242   {CALG_AES_256,  256,256,  256,0,                    8,"AES-256", 39,"Advanced Encryption Standard (AES-256)"},
243   {CALG_SHA,      160,160,  160,CRYPT_FLAG_SIGNING,   6,"SHA-1",   30,"Secure Hash Algorithm (SHA-1)"},
244   {CALG_MD2,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD2",     23,"Message Digest 2 (MD2)"},
245   {CALG_MD4,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD4",     23,"Message Digest 4 (MD4)"},
246   {CALG_MD5,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD5",     23,"Message Digest 5 (MD5)"},
247   {CALG_SSL3_SHAMD5,288,288,288,0,                   12,"SSL3 SHAMD5",12,"SSL3 SHAMD5"},
248   {CALG_MAC,        0,  0,    0,0,                    4,"MAC",     28,"Message Authentication Code"},
249   {CALG_RSA_SIGN,1024,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_SIGN",14,"RSA Signature"},
250   {CALG_RSA_KEYX,1024,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_KEYX",17,"RSA Key Exchange"},
251   {CALG_HMAC,       0,  0,    0,0,                    5,"HMAC",    18,"Hugo's MAC (HMAC)"},
252   {0,               0,  0,    0,0,                    1,"",         1,""}
253  }
254 };
255
256 /******************************************************************************
257  * API forward declarations
258  */
259 BOOL WINAPI 
260 RSAENH_CPGetKeyParam(
261     HCRYPTPROV hProv, 
262     HCRYPTKEY hKey, 
263     DWORD dwParam, 
264     BYTE *pbData, 
265     DWORD *pdwDataLen, 
266     DWORD dwFlags
267 );
268
269 BOOL WINAPI 
270 RSAENH_CPEncrypt(
271     HCRYPTPROV hProv, 
272     HCRYPTKEY hKey, 
273     HCRYPTHASH hHash, 
274     BOOL Final, 
275     DWORD dwFlags, 
276     BYTE *pbData,
277     DWORD *pdwDataLen, 
278     DWORD dwBufLen
279 );
280
281 BOOL WINAPI 
282 RSAENH_CPCreateHash(
283     HCRYPTPROV hProv, 
284     ALG_ID Algid, 
285     HCRYPTKEY hKey, 
286     DWORD dwFlags, 
287     HCRYPTHASH *phHash
288 );
289
290 BOOL WINAPI 
291 RSAENH_CPSetHashParam(
292     HCRYPTPROV hProv, 
293     HCRYPTHASH hHash, 
294     DWORD dwParam, 
295     BYTE *pbData, DWORD dwFlags
296 );
297
298 BOOL WINAPI 
299 RSAENH_CPGetHashParam(
300     HCRYPTPROV hProv, 
301     HCRYPTHASH hHash, 
302     DWORD dwParam, 
303     BYTE *pbData, 
304     DWORD *pdwDataLen, 
305     DWORD dwFlags
306 );
307
308 BOOL WINAPI 
309 RSAENH_CPDestroyHash(
310     HCRYPTPROV hProv, 
311     HCRYPTHASH hHash
312 );
313
314 static BOOL crypt_export_key(
315     CRYPTKEY *pCryptKey,
316     HCRYPTKEY hPubKey, 
317     DWORD dwBlobType, 
318     DWORD dwFlags, 
319     BOOL force,
320     BYTE *pbData, 
321     DWORD *pdwDataLen
322 );
323
324 static BOOL import_key(
325     HCRYPTPROV hProv, 
326     CONST BYTE *pbData, 
327     DWORD dwDataLen, 
328     HCRYPTKEY hPubKey, 
329     DWORD dwFlags, 
330     BOOL fStoreKey,
331     HCRYPTKEY *phKey
332 );
333
334 BOOL WINAPI 
335 RSAENH_CPHashData(
336     HCRYPTPROV hProv, 
337     HCRYPTHASH hHash, 
338     CONST BYTE *pbData, 
339     DWORD dwDataLen, 
340     DWORD dwFlags
341 );
342
343 /******************************************************************************
344  * CSP's handle table (used by all acquired key containers)
345  */
346 static struct handle_table handle_table;
347
348 /******************************************************************************
349  * DllMain (RSAENH.@)
350  *
351  * Initializes and destroys the handle table for the CSP's handles.
352  */
353 int WINAPI DllMain(HINSTANCE hInstance, DWORD fdwReason, PVOID pvReserved)
354 {
355     switch (fdwReason)
356     {
357         case DLL_PROCESS_ATTACH:
358             DisableThreadLibraryCalls(hInstance);
359             init_handle_table(&handle_table);
360             break;
361
362         case DLL_PROCESS_DETACH:
363             destroy_handle_table(&handle_table);
364             break;
365     }
366     return 1;
367 }
368
369 /******************************************************************************
370  * copy_param [Internal]
371  *
372  * Helper function that supports the standard WINAPI protocol for querying data
373  * of dynamic size.
374  *
375  * PARAMS
376  *  pbBuffer      [O]   Buffer where the queried parameter is copied to, if it is large enough.
377  *                      May be NUL if the required buffer size is to be queried only.
378  *  pdwBufferSize [I/O] In: Size of the buffer at pbBuffer
379  *                      Out: Size of parameter pbParam
380  *  pbParam       [I]   Parameter value.
381  *  dwParamSize   [I]   Size of pbParam
382  *
383  * RETURN
384  *  Success: TRUE (pbParam was copied into pbBuffer or pbBuffer is NULL)
385  *  Failure: FALSE (pbBuffer is not large enough to hold pbParam). Last error: ERROR_MORE_DATA
386  */
387 static inline BOOL copy_param(
388     BYTE *pbBuffer, DWORD *pdwBufferSize, CONST BYTE *pbParam, DWORD dwParamSize) 
389 {
390     if (pbBuffer) 
391     {
392         if (dwParamSize > *pdwBufferSize) 
393         {
394             SetLastError(ERROR_MORE_DATA);
395             *pdwBufferSize = dwParamSize;
396             return FALSE;
397         }
398         memcpy(pbBuffer, pbParam, dwParamSize);
399     }
400     *pdwBufferSize = dwParamSize;
401     return TRUE;
402 }
403
404 /******************************************************************************
405  * get_algid_info [Internal]
406  *
407  * Query CSP capabilities for a given crypto algorithm.
408  * 
409  * PARAMS
410  *  hProv [I] Handle to a key container of the CSP whose capabilities are to be queried.
411  *  algid [I] Identifier of the crypto algorithm about which information is requested.
412  *
413  * RETURNS
414  *  Success: Pointer to a PROV_ENUMALGS_EX struct containing information about the crypto algorithm.
415  *  Failure: NULL (algid not supported)
416  */
417 static inline const PROV_ENUMALGS_EX* get_algid_info(HCRYPTPROV hProv, ALG_ID algid) {
418     const PROV_ENUMALGS_EX *iterator;
419     KEYCONTAINER *pKeyContainer;
420
421     if (!lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER, (OBJECTHDR**)&pKeyContainer)) {
422         SetLastError(NTE_BAD_UID);
423         return NULL;
424     }
425
426     for (iterator = aProvEnumAlgsEx[pKeyContainer->dwPersonality]; iterator->aiAlgid; iterator++) {
427         if (iterator->aiAlgid == algid) return iterator;
428     }
429
430     SetLastError(NTE_BAD_ALGID);
431     return NULL;
432 }
433
434 /******************************************************************************
435  * copy_data_blob [Internal] 
436  *
437  * deeply copies a DATA_BLOB
438  *
439  * PARAMS
440  *  dst [O] That's where the blob will be copied to
441  *  src [I] Source blob
442  *
443  * RETURNS
444  *  Success: TRUE
445  *  Failure: FALSE (GetLastError() == NTE_NO_MEMORY
446  *
447  * NOTES
448  *  Use free_data_blob to release resources occupied by copy_data_blob.
449  */
450 static inline BOOL copy_data_blob(PCRYPT_DATA_BLOB dst, CONST PCRYPT_DATA_BLOB src) {
451     dst->pbData = HeapAlloc(GetProcessHeap(), 0, src->cbData);
452     if (!dst->pbData) {
453         SetLastError(NTE_NO_MEMORY);
454         return FALSE;
455     }    
456     dst->cbData = src->cbData;
457     memcpy(dst->pbData, src->pbData, src->cbData);
458     return TRUE;
459 }
460
461 /******************************************************************************
462  * concat_data_blobs [Internal]
463  *
464  * Concatenates two blobs
465  *
466  * PARAMS
467  *  dst  [O] The new blob will be copied here
468  *  src1 [I] Prefix blob
469  *  src2 [I] Appendix blob
470  *
471  * RETURNS
472  *  Success: TRUE
473  *  Failure: FALSE (GetLastError() == NTE_NO_MEMORY)
474  *
475  * NOTES
476  *  Release resources occupied by concat_data_blobs with free_data_blobs
477  */
478 static inline BOOL concat_data_blobs(PCRYPT_DATA_BLOB dst, CONST PCRYPT_DATA_BLOB src1, 
479                                      CONST PCRYPT_DATA_BLOB src2) 
480 {
481     dst->cbData = src1->cbData + src2->cbData;
482     dst->pbData = HeapAlloc(GetProcessHeap(), 0, dst->cbData);
483     if (!dst->pbData) {
484         SetLastError(NTE_NO_MEMORY);
485         return FALSE;
486     }
487     memcpy(dst->pbData, src1->pbData, src1->cbData);
488     memcpy(dst->pbData + src1->cbData, src2->pbData, src2->cbData);
489     return TRUE;
490 }
491
492 /******************************************************************************
493  * free_data_blob [Internal]
494  *
495  * releases resource occupied by a dynamically allocated CRYPT_DATA_BLOB
496  * 
497  * PARAMS
498  *  pBlob [I] Heap space occupied by pBlob->pbData is released
499  */
500 static inline void free_data_blob(PCRYPT_DATA_BLOB pBlob) {
501     HeapFree(GetProcessHeap(), 0, pBlob->pbData);
502 }
503
504 /******************************************************************************
505  * init_data_blob [Internal]
506  */
507 static inline void init_data_blob(PCRYPT_DATA_BLOB pBlob) {
508     pBlob->pbData = NULL;
509     pBlob->cbData = 0;
510 }
511
512 /******************************************************************************
513  * free_hmac_info [Internal]
514  *
515  * Deeply free an HMAC_INFO struct.
516  *
517  * PARAMS
518  *  hmac_info [I] Pointer to the HMAC_INFO struct to be freed.
519  *
520  * NOTES
521  *  See Internet RFC 2104 for details on the HMAC algorithm.
522  */
523 static inline void free_hmac_info(PHMAC_INFO hmac_info) {
524     if (!hmac_info) return;
525     HeapFree(GetProcessHeap(), 0, hmac_info->pbInnerString);
526     HeapFree(GetProcessHeap(), 0, hmac_info->pbOuterString);
527     HeapFree(GetProcessHeap(), 0, hmac_info);
528 }
529
530 /******************************************************************************
531  * copy_hmac_info [Internal]
532  *
533  * Deeply copy an HMAC_INFO struct
534  *
535  * PARAMS
536  *  dst [O] Pointer to a location where the pointer to the HMAC_INFO copy will be stored.
537  *  src [I] Pointer to the HMAC_INFO struct to be copied.
538  *
539  * RETURNS
540  *  Success: TRUE
541  *  Failure: FALSE
542  *
543  * NOTES
544  *  See Internet RFC 2104 for details on the HMAC algorithm.
545  */
546 static BOOL copy_hmac_info(PHMAC_INFO *dst, const HMAC_INFO *src) {
547     if (!src) return FALSE;
548     *dst = HeapAlloc(GetProcessHeap(), 0, sizeof(HMAC_INFO));
549     if (!*dst) return FALSE;
550     **dst = *src;
551     (*dst)->pbInnerString = NULL;
552     (*dst)->pbOuterString = NULL;
553     if ((*dst)->cbInnerString == 0) (*dst)->cbInnerString = RSAENH_HMAC_DEF_PAD_LEN;
554     (*dst)->pbInnerString = HeapAlloc(GetProcessHeap(), 0, (*dst)->cbInnerString);
555     if (!(*dst)->pbInnerString) {
556         free_hmac_info(*dst);
557         return FALSE;
558     }
559     if (src->cbInnerString) 
560         memcpy((*dst)->pbInnerString, src->pbInnerString, src->cbInnerString);
561     else 
562         memset((*dst)->pbInnerString, RSAENH_HMAC_DEF_IPAD_CHAR, RSAENH_HMAC_DEF_PAD_LEN);
563     if ((*dst)->cbOuterString == 0) (*dst)->cbOuterString = RSAENH_HMAC_DEF_PAD_LEN;
564     (*dst)->pbOuterString = HeapAlloc(GetProcessHeap(), 0, (*dst)->cbOuterString);
565     if (!(*dst)->pbOuterString) {
566         free_hmac_info(*dst);
567         return FALSE;
568     }
569     if (src->cbOuterString) 
570         memcpy((*dst)->pbOuterString, src->pbOuterString, src->cbOuterString);
571     else 
572         memset((*dst)->pbOuterString, RSAENH_HMAC_DEF_OPAD_CHAR, RSAENH_HMAC_DEF_PAD_LEN);
573     return TRUE;
574 }
575
576 /******************************************************************************
577  * destroy_hash [Internal]
578  *
579  * Destructor for hash objects
580  *
581  * PARAMS
582  *  pCryptHash [I] Pointer to the hash object to be destroyed. 
583  *                 Will be invalid after function returns!
584  */
585 static void destroy_hash(OBJECTHDR *pObject)
586 {
587     CRYPTHASH *pCryptHash = (CRYPTHASH*)pObject;
588         
589     free_hmac_info(pCryptHash->pHMACInfo);
590     free_data_blob(&pCryptHash->tpPRFParams.blobLabel);
591     free_data_blob(&pCryptHash->tpPRFParams.blobSeed);
592     HeapFree(GetProcessHeap(), 0, pCryptHash);
593 }
594
595 /******************************************************************************
596  * init_hash [Internal]
597  *
598  * Initialize (or reset) a hash object
599  *
600  * PARAMS
601  *  pCryptHash    [I] The hash object to be initialized.
602  */
603 static inline BOOL init_hash(CRYPTHASH *pCryptHash) {
604     DWORD dwLen;
605         
606     switch (pCryptHash->aiAlgid) 
607     {
608         case CALG_HMAC:
609             if (pCryptHash->pHMACInfo) { 
610                 const PROV_ENUMALGS_EX *pAlgInfo;
611                 
612                 pAlgInfo = get_algid_info(pCryptHash->hProv, pCryptHash->pHMACInfo->HashAlgid);
613                 if (!pAlgInfo) return FALSE;
614                 pCryptHash->dwHashSize = pAlgInfo->dwDefaultLen >> 3;
615                 init_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context);
616                 update_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
617                                  pCryptHash->pHMACInfo->pbInnerString, 
618                                  pCryptHash->pHMACInfo->cbInnerString);
619             }
620             return TRUE;
621             
622         case CALG_MAC:
623             dwLen = sizeof(DWORD);
624             RSAENH_CPGetKeyParam(pCryptHash->hProv, pCryptHash->hKey, KP_BLOCKLEN, 
625                                  (BYTE*)&pCryptHash->dwHashSize, &dwLen, 0);
626             pCryptHash->dwHashSize >>= 3;
627             return TRUE;
628
629         default:
630             return init_hash_impl(pCryptHash->aiAlgid, &pCryptHash->context);
631     }
632 }
633
634 /******************************************************************************
635  * update_hash [Internal]
636  *
637  * Hashes the given data and updates the hash object's state accordingly
638  *
639  * PARAMS
640  *  pCryptHash [I] Hash object to be updated.
641  *  pbData     [I] Pointer to data stream to be hashed.
642  *  dwDataLen  [I] Length of data stream.
643  */
644 static inline void update_hash(CRYPTHASH *pCryptHash, CONST BYTE *pbData, DWORD dwDataLen) {
645     BYTE *pbTemp;
646
647     switch (pCryptHash->aiAlgid)
648     {
649         case CALG_HMAC:
650             if (pCryptHash->pHMACInfo) 
651                 update_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context, 
652                                  pbData, dwDataLen);
653             break;
654
655         case CALG_MAC:
656             pbTemp = HeapAlloc(GetProcessHeap(), 0, dwDataLen);
657             if (!pbTemp) return;
658             memcpy(pbTemp, pbData, dwDataLen);
659             RSAENH_CPEncrypt(pCryptHash->hProv, pCryptHash->hKey, 0, FALSE, 0,
660                              pbTemp, &dwDataLen, dwDataLen);
661             HeapFree(GetProcessHeap(), 0, pbTemp);
662             break;
663
664         default:
665             update_hash_impl(pCryptHash->aiAlgid, &pCryptHash->context, pbData, dwDataLen);
666     }
667 }
668
669 /******************************************************************************
670  * finalize_hash [Internal]
671  *
672  * Finalizes the hash, after all data has been hashed with update_hash.
673  * No additional data can be hashed afterwards until the hash gets initialized again.
674  *
675  * PARAMS
676  *  pCryptHash [I] Hash object to be finalized.
677  */
678 static inline void finalize_hash(CRYPTHASH *pCryptHash) {
679     DWORD dwDataLen;
680         
681     switch (pCryptHash->aiAlgid)
682     {
683         case CALG_HMAC:
684             if (pCryptHash->pHMACInfo) {
685                 BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
686
687                 finalize_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context, 
688                                    pCryptHash->abHashValue);
689                 memcpy(abHashValue, pCryptHash->abHashValue, pCryptHash->dwHashSize);
690                 init_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context);
691                 update_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
692                                  pCryptHash->pHMACInfo->pbOuterString, 
693                                  pCryptHash->pHMACInfo->cbOuterString);
694                 update_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
695                                  abHashValue, pCryptHash->dwHashSize);
696                 finalize_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
697                                    pCryptHash->abHashValue);
698             } 
699             break;
700
701         case CALG_MAC:
702             dwDataLen = 0;
703             RSAENH_CPEncrypt(pCryptHash->hProv, pCryptHash->hKey, 0, TRUE, 0,
704                              pCryptHash->abHashValue, &dwDataLen, pCryptHash->dwHashSize);
705             break;
706
707         default:
708             finalize_hash_impl(pCryptHash->aiAlgid, &pCryptHash->context, pCryptHash->abHashValue);
709     }
710 }
711
712 /******************************************************************************
713  * destroy_key [Internal]
714  *
715  * Destructor for key objects
716  *
717  * PARAMS
718  *  pCryptKey [I] Pointer to the key object to be destroyed. 
719  *                Will be invalid after function returns!
720  */
721 static void destroy_key(OBJECTHDR *pObject)
722 {
723     CRYPTKEY *pCryptKey = (CRYPTKEY*)pObject;
724         
725     free_key_impl(pCryptKey->aiAlgid, &pCryptKey->context);
726     free_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom);
727     free_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom);
728     HeapFree(GetProcessHeap(), 0, pCryptKey);
729 }
730
731 /******************************************************************************
732  * setup_key [Internal]
733  *
734  * Initialize (or reset) a key object
735  *
736  * PARAMS
737  *  pCryptKey    [I] The key object to be initialized.
738  */
739 static inline void setup_key(CRYPTKEY *pCryptKey) {
740     pCryptKey->dwState = RSAENH_KEYSTATE_IDLE;
741     memcpy(pCryptKey->abChainVector, pCryptKey->abInitVector, sizeof(pCryptKey->abChainVector));
742     setup_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen, 
743                    pCryptKey->dwEffectiveKeyLen, pCryptKey->dwSaltLen,
744                    pCryptKey->abKeyValue);
745 }
746
747 /******************************************************************************
748  * new_key [Internal]
749  *
750  * Creates a new key object without assigning the actual binary key value. 
751  * This is done by CPDeriveKey, CPGenKey or CPImportKey, which call this function.
752  *
753  * PARAMS
754  *  hProv      [I] Handle to the provider to which the created key will belong.
755  *  aiAlgid    [I] The new key shall use the crypto algorithm idenfied by aiAlgid.
756  *  dwFlags    [I] Upper 16 bits give the key length.
757  *                 Lower 16 bits: CRYPT_EXPORTABLE, CRYPT_CREATE_SALT,
758  *                 CRYPT_NO_SALT
759  *  ppCryptKey [O] Pointer to the created key
760  *
761  * RETURNS
762  *  Success: Handle to the created key.
763  *  Failure: INVALID_HANDLE_VALUE
764  */
765 static HCRYPTKEY new_key(HCRYPTPROV hProv, ALG_ID aiAlgid, DWORD dwFlags, CRYPTKEY **ppCryptKey)
766 {
767     HCRYPTKEY hCryptKey;
768     CRYPTKEY *pCryptKey;
769     DWORD dwKeyLen = HIWORD(dwFlags);
770     const PROV_ENUMALGS_EX *peaAlgidInfo;
771
772     *ppCryptKey = NULL;
773     
774     /* 
775      * Retrieve the CSP's capabilities for the given ALG_ID value
776      */
777     peaAlgidInfo = get_algid_info(hProv, aiAlgid);
778     if (!peaAlgidInfo) return (HCRYPTKEY)INVALID_HANDLE_VALUE;
779
780     TRACE("alg = %s, dwKeyLen = %d\n", debugstr_a(peaAlgidInfo->szName),
781           dwKeyLen);
782     /*
783      * Assume the default key length, if none is specified explicitly
784      */
785     if (dwKeyLen == 0) dwKeyLen = peaAlgidInfo->dwDefaultLen;
786     
787     /*
788      * Check if the requested key length is supported by the current CSP.
789      * Adjust key length's for DES algorithms.
790      */
791     switch (aiAlgid) {
792         case CALG_DES:
793             if (dwKeyLen == RSAENH_DES_EFFECTIVE_KEYLEN) {
794                 dwKeyLen = RSAENH_DES_STORAGE_KEYLEN;
795             }
796             if (dwKeyLen != RSAENH_DES_STORAGE_KEYLEN) {
797                 SetLastError(NTE_BAD_FLAGS);
798                 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
799             }
800             break;
801
802         case CALG_3DES_112:
803             if (dwKeyLen == RSAENH_3DES112_EFFECTIVE_KEYLEN) {
804                 dwKeyLen = RSAENH_3DES112_STORAGE_KEYLEN;
805             }
806             if (dwKeyLen != RSAENH_3DES112_STORAGE_KEYLEN) {
807                 SetLastError(NTE_BAD_FLAGS);
808                 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
809             }
810             break;
811
812         case CALG_3DES:
813             if (dwKeyLen == RSAENH_3DES_EFFECTIVE_KEYLEN) {
814                 dwKeyLen = RSAENH_3DES_STORAGE_KEYLEN;
815             }
816             if (dwKeyLen != RSAENH_3DES_STORAGE_KEYLEN) {
817                 SetLastError(NTE_BAD_FLAGS);
818                 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
819             }
820             break;
821         
822         default:
823             if (dwKeyLen % 8 || 
824                 dwKeyLen > peaAlgidInfo->dwMaxLen || 
825                 dwKeyLen < peaAlgidInfo->dwMinLen) 
826             {
827                 TRACE("key len %d out of bounds (%d, %d)\n", dwKeyLen,
828                       peaAlgidInfo->dwMinLen, peaAlgidInfo->dwMaxLen);
829                 SetLastError(NTE_BAD_DATA);
830                 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
831             }
832     }
833
834     hCryptKey = new_object(&handle_table, sizeof(CRYPTKEY), RSAENH_MAGIC_KEY,
835                            destroy_key, (OBJECTHDR**)&pCryptKey);
836     if (hCryptKey != (HCRYPTKEY)INVALID_HANDLE_VALUE)
837     {
838         pCryptKey->aiAlgid = aiAlgid;
839         pCryptKey->hProv = hProv;
840         pCryptKey->dwModeBits = 0;
841         pCryptKey->dwPermissions = CRYPT_ENCRYPT | CRYPT_DECRYPT | CRYPT_READ | CRYPT_WRITE | 
842                                    CRYPT_MAC;
843         if (dwFlags & CRYPT_EXPORTABLE)
844             pCryptKey->dwPermissions |= CRYPT_EXPORT;
845         pCryptKey->dwKeyLen = dwKeyLen >> 3;
846         pCryptKey->dwEffectiveKeyLen = 0;
847         if ((dwFlags & CRYPT_CREATE_SALT) || (dwKeyLen == 40 && !(dwFlags & CRYPT_NO_SALT))) 
848             pCryptKey->dwSaltLen = 16 /*FIXME*/ - pCryptKey->dwKeyLen;
849         else
850             pCryptKey->dwSaltLen = 0;
851         memset(pCryptKey->abKeyValue, 0, sizeof(pCryptKey->abKeyValue));
852         memset(pCryptKey->abInitVector, 0, sizeof(pCryptKey->abInitVector));
853         init_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom);
854         init_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom);
855             
856         switch(aiAlgid)
857         {
858             case CALG_PCT1_MASTER:
859             case CALG_SSL2_MASTER:
860             case CALG_SSL3_MASTER:
861             case CALG_TLS1_MASTER:
862             case CALG_RC4:
863                 pCryptKey->dwBlockLen = 0;
864                 pCryptKey->dwMode = 0;
865                 break;
866
867             case CALG_RC2:
868             case CALG_DES:
869             case CALG_3DES_112:
870             case CALG_3DES:
871                 pCryptKey->dwBlockLen = 8;
872                 pCryptKey->dwMode = CRYPT_MODE_CBC;
873                 break;
874
875             case CALG_AES:
876             case CALG_AES_128:
877             case CALG_AES_192:
878             case CALG_AES_256:
879                 pCryptKey->dwBlockLen = 16;
880                 pCryptKey->dwMode = CRYPT_MODE_ECB;
881                 break;
882
883             case CALG_RSA_KEYX:
884             case CALG_RSA_SIGN:
885                 pCryptKey->dwBlockLen = dwKeyLen >> 3;
886                 pCryptKey->dwMode = 0;
887                 break;
888         }
889
890         *ppCryptKey = pCryptKey;
891     }
892
893     return hCryptKey;
894 }
895
896 /******************************************************************************
897  * map_key_spec_to_key_pair_name [Internal]
898  *
899  * Returns the name of the registry value associated with a key spec.
900  *
901  * PARAMS
902  *  dwKeySpec     [I] AT_KEYEXCHANGE or AT_SIGNATURE
903  *
904  * RETURNS
905  *  Success: Name of registry value.
906  *  Failure: NULL
907  */
908 static LPCSTR map_key_spec_to_key_pair_name(DWORD dwKeySpec)
909 {
910     LPCSTR szValueName;
911
912     switch (dwKeySpec)
913     {
914     case AT_KEYEXCHANGE:
915         szValueName = "KeyExchangeKeyPair";
916         break;
917     case AT_SIGNATURE:
918         szValueName = "SignatureKeyPair";
919         break;
920     default:
921         WARN("invalid key spec %d\n", dwKeySpec);
922         szValueName = NULL;
923     }
924     return szValueName;
925 }
926
927 /******************************************************************************
928  * store_key_pair [Internal]
929  *
930  * Stores a key pair to the registry
931  * 
932  * PARAMS
933  *  hCryptKey     [I] Handle to the key to be stored
934  *  hKey          [I] Registry key where the key pair is to be stored
935  *  dwKeySpec     [I] AT_KEYEXCHANGE or AT_SIGNATURE
936  *  dwFlags       [I] Flags for protecting the key
937  */
938 static void store_key_pair(HCRYPTKEY hCryptKey, HKEY hKey, DWORD dwKeySpec, DWORD dwFlags)
939 {
940     LPCSTR szValueName;
941     DATA_BLOB blobIn, blobOut;
942     CRYPTKEY *pKey;
943     DWORD dwLen;
944     BYTE *pbKey;
945
946     if (!(szValueName = map_key_spec_to_key_pair_name(dwKeySpec)))
947         return;
948     if (lookup_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY,
949                       (OBJECTHDR**)&pKey))
950     {
951         if (crypt_export_key(pKey, 0, PRIVATEKEYBLOB, 0, TRUE, 0, &dwLen))
952         {
953             pbKey = HeapAlloc(GetProcessHeap(), 0, dwLen);
954             if (pbKey)
955             {
956                 if (crypt_export_key(pKey, 0, PRIVATEKEYBLOB, 0, TRUE, pbKey,
957                     &dwLen))
958                 {
959                     blobIn.pbData = pbKey;
960                     blobIn.cbData = dwLen;
961
962                     if (CryptProtectData(&blobIn, NULL, NULL, NULL, NULL,
963                         dwFlags, &blobOut))
964                     {
965                         RegSetValueExA(hKey, szValueName, 0, REG_BINARY,
966                                        blobOut.pbData, blobOut.cbData);
967                         LocalFree(blobOut.pbData);
968                     }
969                 }
970                 HeapFree(GetProcessHeap(), 0, pbKey);
971             }
972         }
973     }
974 }
975
976 /******************************************************************************
977  * map_key_spec_to_permissions_name [Internal]
978  *
979  * Returns the name of the registry value associated with the permissions for
980  * a key spec.
981  *
982  * PARAMS
983  *  dwKeySpec     [I] AT_KEYEXCHANGE or AT_SIGNATURE
984  *
985  * RETURNS
986  *  Success: Name of registry value.
987  *  Failure: NULL
988  */
989 static LPCSTR map_key_spec_to_permissions_name(DWORD dwKeySpec)
990 {
991     LPCSTR szValueName;
992
993     switch (dwKeySpec)
994     {
995     case AT_KEYEXCHANGE:
996         szValueName = "KeyExchangePermissions";
997         break;
998     case AT_SIGNATURE:
999         szValueName = "SignaturePermissions";
1000         break;
1001     default:
1002         WARN("invalid key spec %d\n", dwKeySpec);
1003         szValueName = NULL;
1004     }
1005     return szValueName;
1006 }
1007
1008 /******************************************************************************
1009  * store_key_permissions [Internal]
1010  *
1011  * Stores a key's permissions to the registry
1012  *
1013  * PARAMS
1014  *  hCryptKey     [I] Handle to the key whose permissions are to be stored
1015  *  hKey          [I] Registry key where the key permissions are to be stored
1016  *  dwKeySpec     [I] AT_KEYEXCHANGE or AT_SIGNATURE
1017  */
1018 static void store_key_permissions(HCRYPTKEY hCryptKey, HKEY hKey, DWORD dwKeySpec)
1019 {
1020     LPCSTR szValueName;
1021     CRYPTKEY *pKey;
1022
1023     if (!(szValueName = map_key_spec_to_permissions_name(dwKeySpec)))
1024         return;
1025     if (lookup_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY,
1026                       (OBJECTHDR**)&pKey))
1027         RegSetValueExA(hKey, szValueName, 0, REG_DWORD,
1028                        (BYTE *)&pKey->dwPermissions,
1029                        sizeof(pKey->dwPermissions));
1030 }
1031
1032 /******************************************************************************
1033  * create_container_key [Internal]
1034  *
1035  * Creates the registry key for a key container's persistent storage.
1036  * 
1037  * PARAMS
1038  *  pKeyContainer [I] Pointer to the key container
1039  *  sam           [I] Desired registry access
1040  *  phKey         [O] Returned key
1041  */
1042 static BOOL create_container_key(KEYCONTAINER *pKeyContainer, REGSAM sam, HKEY *phKey)
1043 {
1044     CHAR szRSABase[MAX_PATH];
1045     HKEY hRootKey;
1046
1047     sprintf(szRSABase, RSAENH_REGKEY, pKeyContainer->szName);
1048
1049     if (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET)
1050         hRootKey = HKEY_LOCAL_MACHINE;
1051     else
1052         hRootKey = HKEY_CURRENT_USER;
1053
1054     /* @@ Wine registry key: HKLM\Software\Wine\Crypto\RSA */
1055     /* @@ Wine registry key: HKCU\Software\Wine\Crypto\RSA */
1056     return RegCreateKeyExA(hRootKey, szRSABase, 0, NULL,
1057                            REG_OPTION_NON_VOLATILE, sam, NULL, phKey, NULL)
1058                            == ERROR_SUCCESS;
1059 }
1060
1061 /******************************************************************************
1062  * open_container_key [Internal]
1063  *
1064  * Opens a key container's persistent storage for reading.
1065  *
1066  * PARAMS
1067  *  pszContainerName [I] Name of the container to be opened.  May be the empty
1068  *                       string if the parent key of all containers is to be
1069  *                       opened.
1070  *  dwFlags          [I] Flags indicating which keyset to be opened.
1071  *  phKey            [O] Returned key
1072  */
1073 static BOOL open_container_key(LPCSTR pszContainerName, DWORD dwFlags, HKEY *phKey)
1074 {
1075     CHAR szRSABase[MAX_PATH];
1076     HKEY hRootKey;
1077
1078     sprintf(szRSABase, RSAENH_REGKEY, pszContainerName);
1079
1080     if (dwFlags & CRYPT_MACHINE_KEYSET)
1081         hRootKey = HKEY_LOCAL_MACHINE;
1082     else
1083         hRootKey = HKEY_CURRENT_USER;
1084
1085     /* @@ Wine registry key: HKLM\Software\Wine\Crypto\RSA */
1086     /* @@ Wine registry key: HKCU\Software\Wine\Crypto\RSA */
1087     return RegOpenKeyExA(hRootKey, szRSABase, 0, KEY_READ, phKey) ==
1088                          ERROR_SUCCESS;
1089 }
1090
1091 /******************************************************************************
1092  * delete_container_key [Internal]
1093  *
1094  * Deletes a key container's persistent storage.
1095  *
1096  * PARAMS
1097  *  pszContainerName [I] Name of the container to be opened.
1098  *  dwFlags          [I] Flags indicating which keyset to be opened.
1099  */
1100 static BOOL delete_container_key(LPCSTR pszContainerName, DWORD dwFlags)
1101 {
1102     CHAR szRegKey[MAX_PATH];
1103
1104     if (snprintf(szRegKey, MAX_PATH, RSAENH_REGKEY, pszContainerName) >= MAX_PATH) {
1105         SetLastError(NTE_BAD_KEYSET_PARAM);
1106         return FALSE;
1107     } else {
1108         HKEY hRootKey;
1109         if (dwFlags & CRYPT_MACHINE_KEYSET)
1110             hRootKey = HKEY_LOCAL_MACHINE;
1111         else
1112             hRootKey = HKEY_CURRENT_USER;
1113         if (!RegDeleteKeyA(hRootKey, szRegKey)) {
1114             SetLastError(ERROR_SUCCESS);
1115             return TRUE;
1116         } else {
1117             SetLastError(NTE_BAD_KEYSET);
1118             return FALSE;
1119         }
1120     }
1121 }
1122
1123 /******************************************************************************
1124  * store_key_container_keys [Internal]
1125  *
1126  * Stores key container's keys in a persistent location.
1127  *
1128  * PARAMS
1129  *  pKeyContainer [I] Pointer to the key container whose keys are to be saved
1130  */
1131 static void store_key_container_keys(KEYCONTAINER *pKeyContainer)
1132 {
1133     HKEY hKey;
1134     DWORD dwFlags;
1135
1136     /* On WinXP, persistent keys are stored in a file located at:
1137      * $AppData$\\Microsoft\\Crypto\\RSA\\$SID$\\some_hex_string
1138      */
1139
1140     if (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET)
1141         dwFlags = CRYPTPROTECT_LOCAL_MACHINE;
1142     else
1143         dwFlags = 0;
1144
1145     if (create_container_key(pKeyContainer, KEY_WRITE, &hKey))
1146     {
1147         store_key_pair(pKeyContainer->hKeyExchangeKeyPair, hKey,
1148                        AT_KEYEXCHANGE, dwFlags);
1149         store_key_pair(pKeyContainer->hSignatureKeyPair, hKey,
1150                        AT_SIGNATURE, dwFlags);
1151         RegCloseKey(hKey);
1152     }
1153 }
1154
1155 /******************************************************************************
1156  * store_key_container_permissions [Internal]
1157  *
1158  * Stores key container's key permissions in a persistent location.
1159  *
1160  * PARAMS
1161  *  pKeyContainer [I] Pointer to the key container whose key permissions are to
1162  *                    be saved
1163  */
1164 static void store_key_container_permissions(KEYCONTAINER *pKeyContainer)
1165 {
1166     HKEY hKey;
1167     DWORD dwFlags;
1168
1169     /* On WinXP, persistent keys are stored in a file located at:
1170      * $AppData$\\Microsoft\\Crypto\\RSA\\$SID$\\some_hex_string
1171      */
1172
1173     if (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET)
1174         dwFlags = CRYPTPROTECT_LOCAL_MACHINE;
1175     else
1176         dwFlags = 0;
1177
1178     if (create_container_key(pKeyContainer, KEY_WRITE, &hKey))
1179     {
1180         store_key_permissions(pKeyContainer->hKeyExchangeKeyPair, hKey,
1181                        AT_KEYEXCHANGE);
1182         store_key_permissions(pKeyContainer->hSignatureKeyPair, hKey,
1183                        AT_SIGNATURE);
1184         RegCloseKey(hKey);
1185     }
1186 }
1187
1188 /******************************************************************************
1189  * release_key_container_keys [Internal]
1190  *
1191  * Releases key container's keys.
1192  *
1193  * PARAMS
1194  *  pKeyContainer [I] Pointer to the key container whose keys are to be released.
1195  */
1196 static void release_key_container_keys(KEYCONTAINER *pKeyContainer)
1197 {
1198     release_handle(&handle_table, pKeyContainer->hKeyExchangeKeyPair,
1199                    RSAENH_MAGIC_KEY);
1200     release_handle(&handle_table, pKeyContainer->hSignatureKeyPair,
1201                    RSAENH_MAGIC_KEY);
1202 }
1203
1204 /******************************************************************************
1205  * destroy_key_container [Internal]
1206  *
1207  * Destructor for key containers.
1208  *
1209  * PARAMS
1210  *  pObjectHdr [I] Pointer to the key container to be destroyed.
1211  */
1212 static void destroy_key_container(OBJECTHDR *pObjectHdr)
1213 {
1214     KEYCONTAINER *pKeyContainer = (KEYCONTAINER*)pObjectHdr;
1215
1216     if (!(pKeyContainer->dwFlags & CRYPT_VERIFYCONTEXT))
1217     {
1218         store_key_container_keys(pKeyContainer);
1219         store_key_container_permissions(pKeyContainer);
1220         release_key_container_keys(pKeyContainer);
1221     }
1222     else
1223         release_key_container_keys(pKeyContainer);
1224     HeapFree( GetProcessHeap(), 0, pKeyContainer );
1225 }
1226
1227 /******************************************************************************
1228  * new_key_container [Internal]
1229  *
1230  * Create a new key container. The personality (RSA Base, Strong or Enhanced CP) 
1231  * of the CSP is determined via the pVTable->pszProvName string.
1232  *
1233  * PARAMS
1234  *  pszContainerName [I] Name of the key container.
1235  *  pVTable          [I] Callback functions and context info provided by the OS
1236  *
1237  * RETURNS
1238  *  Success: Handle to the new key container.
1239  *  Failure: INVALID_HANDLE_VALUE
1240  */
1241 static HCRYPTPROV new_key_container(PCCH pszContainerName, DWORD dwFlags, const VTableProvStruc *pVTable)
1242 {
1243     KEYCONTAINER *pKeyContainer;
1244     HCRYPTPROV hKeyContainer;
1245
1246     hKeyContainer = new_object(&handle_table, sizeof(KEYCONTAINER), RSAENH_MAGIC_CONTAINER,
1247                                destroy_key_container, (OBJECTHDR**)&pKeyContainer);
1248     if (hKeyContainer != (HCRYPTPROV)INVALID_HANDLE_VALUE)
1249     {
1250         lstrcpynA(pKeyContainer->szName, pszContainerName, MAX_PATH);
1251         pKeyContainer->dwFlags = dwFlags;
1252         pKeyContainer->dwEnumAlgsCtr = 0;
1253         pKeyContainer->hKeyExchangeKeyPair = (HCRYPTKEY)INVALID_HANDLE_VALUE;
1254         pKeyContainer->hSignatureKeyPair = (HCRYPTKEY)INVALID_HANDLE_VALUE;
1255         if (pVTable && pVTable->pszProvName) {
1256             lstrcpynA(pKeyContainer->szProvName, pVTable->pszProvName, MAX_PATH);
1257             if (!strcmp(pVTable->pszProvName, MS_DEF_PROV_A)) {
1258                 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_BASE;
1259             } else if (!strcmp(pVTable->pszProvName, MS_ENHANCED_PROV_A)) {
1260                 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_ENHANCED;
1261             } else if (!strcmp(pVTable->pszProvName, MS_DEF_RSA_SCHANNEL_PROV_A)) { 
1262                 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_SCHANNEL;
1263             } else if (!strcmp(pVTable->pszProvName, MS_ENH_RSA_AES_PROV_A)) {
1264                 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_AES;
1265             } else {
1266                 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_STRONG;
1267             }
1268         }
1269
1270         /* The new key container has to be inserted into the CSP immediately 
1271          * after creation to be available for CPGetProvParam's PP_ENUMCONTAINERS. */
1272         if (!(dwFlags & CRYPT_VERIFYCONTEXT)) {
1273             HKEY hKey;
1274
1275             if (create_container_key(pKeyContainer, KEY_WRITE, &hKey))
1276                 RegCloseKey(hKey);
1277         }
1278     }
1279
1280     return hKeyContainer;
1281 }
1282
1283 /******************************************************************************
1284  * read_key_value [Internal]
1285  *
1286  * Reads a key pair value from the registry
1287  *
1288  * PARAMS
1289  *  hKeyContainer [I] Crypt provider to use to import the key
1290  *  hKey          [I] Registry key from which to read the key pair
1291  *  dwKeySpec     [I] AT_KEYEXCHANGE or AT_SIGNATURE
1292  *  dwFlags       [I] Flags for unprotecting the key
1293  *  phCryptKey    [O] Returned key
1294  */
1295 static BOOL read_key_value(HCRYPTPROV hKeyContainer, HKEY hKey, DWORD dwKeySpec, DWORD dwFlags, HCRYPTKEY *phCryptKey)
1296 {
1297     LPCSTR szValueName;
1298     DWORD dwValueType, dwLen;
1299     BYTE *pbKey;
1300     DATA_BLOB blobIn, blobOut;
1301     BOOL ret = FALSE;
1302
1303     if (!(szValueName = map_key_spec_to_key_pair_name(dwKeySpec)))
1304         return FALSE;
1305     if (RegQueryValueExA(hKey, szValueName, 0, &dwValueType, NULL, &dwLen) ==
1306         ERROR_SUCCESS)
1307     {
1308         pbKey = HeapAlloc(GetProcessHeap(), 0, dwLen);
1309         if (pbKey)
1310         {
1311             if (RegQueryValueExA(hKey, szValueName, 0, &dwValueType, pbKey, &dwLen) ==
1312                 ERROR_SUCCESS)
1313             {
1314                 blobIn.pbData = pbKey;
1315                 blobIn.cbData = dwLen;
1316
1317                 if (CryptUnprotectData(&blobIn, NULL, NULL, NULL, NULL,
1318                     dwFlags, &blobOut))
1319                 {
1320                     ret = import_key(hKeyContainer, blobOut.pbData, blobOut.cbData, 0, 0,
1321                                      FALSE, phCryptKey);
1322                     LocalFree(blobOut.pbData);
1323                 }
1324             }
1325             HeapFree(GetProcessHeap(), 0, pbKey);
1326         }
1327     }
1328     if (ret)
1329     {
1330         CRYPTKEY *pKey;
1331
1332         if (lookup_handle(&handle_table, *phCryptKey, RSAENH_MAGIC_KEY,
1333                           (OBJECTHDR**)&pKey))
1334         {
1335             if ((szValueName = map_key_spec_to_permissions_name(dwKeySpec)))
1336             {
1337                 dwLen = sizeof(pKey->dwPermissions);
1338                 RegQueryValueExA(hKey, szValueName, 0, NULL,
1339                                  (BYTE *)&pKey->dwPermissions, &dwLen);
1340             }
1341         }
1342     }
1343     return ret;
1344 }
1345
1346 /******************************************************************************
1347  * read_key_container [Internal]
1348  *
1349  * Tries to read the persistent state of the key container (mainly the signature
1350  * and key exchange private keys) given by pszContainerName.
1351  *
1352  * PARAMS
1353  *  pszContainerName [I] Name of the key container to read from the registry
1354  *  pVTable          [I] Pointer to context data provided by the operating system
1355  *
1356  * RETURNS
1357  *  Success: Handle to the key container read from the registry
1358  *  Failure: INVALID_HANDLE_VALUE
1359  */
1360 static HCRYPTPROV read_key_container(PCHAR pszContainerName, DWORD dwFlags, const VTableProvStruc *pVTable)
1361 {
1362     HKEY hKey;
1363     KEYCONTAINER *pKeyContainer;
1364     HCRYPTPROV hKeyContainer;
1365     HCRYPTKEY hCryptKey;
1366
1367     if (!open_container_key(pszContainerName, dwFlags, &hKey))
1368     {
1369         SetLastError(NTE_BAD_KEYSET);
1370         return (HCRYPTPROV)INVALID_HANDLE_VALUE;
1371     }
1372
1373     hKeyContainer = new_key_container(pszContainerName, dwFlags, pVTable);
1374     if (hKeyContainer != (HCRYPTPROV)INVALID_HANDLE_VALUE)
1375     {
1376         DWORD dwProtectFlags = (dwFlags & CRYPT_MACHINE_KEYSET) ?
1377             CRYPTPROTECT_LOCAL_MACHINE : 0;
1378
1379         if (!lookup_handle(&handle_table, hKeyContainer, RSAENH_MAGIC_CONTAINER, 
1380                            (OBJECTHDR**)&pKeyContainer))
1381             return (HCRYPTPROV)INVALID_HANDLE_VALUE;
1382     
1383         /* read_key_value calls import_key, which calls import_private_key,
1384          * which implicitly installs the key value into the appropriate key
1385          * container key.  Thus the ref count is incremented twice, once for
1386          * the output key value, and once for the implicit install, and needs
1387          * to be decremented to balance the two.
1388          */
1389         if (read_key_value(hKeyContainer, hKey, AT_KEYEXCHANGE,
1390             dwProtectFlags, &hCryptKey))
1391             release_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY);
1392         if (read_key_value(hKeyContainer, hKey, AT_SIGNATURE,
1393             dwProtectFlags, &hCryptKey))
1394             release_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY);
1395     }
1396
1397     return hKeyContainer;
1398 }
1399
1400 /******************************************************************************
1401  * build_hash_signature [Internal]
1402  *
1403  * Builds a padded version of a hash to match the length of the RSA key modulus.
1404  *
1405  * PARAMS
1406  *  pbSignature [O] The padded hash object is stored here.
1407  *  dwLen       [I] Length of the pbSignature buffer.
1408  *  aiAlgid     [I] Algorithm identifier of the hash to be padded.
1409  *  abHashValue [I] The value of the hash object.
1410  *  dwHashLen   [I] Length of the hash value.
1411  *  dwFlags     [I] Selection of padding algorithm.
1412  *
1413  * RETURNS
1414  *  Success: TRUE
1415  *  Failure: FALSE (NTE_BAD_ALGID)
1416  */
1417 static BOOL build_hash_signature(BYTE *pbSignature, DWORD dwLen, ALG_ID aiAlgid, 
1418                                  CONST BYTE *abHashValue, DWORD dwHashLen, DWORD dwFlags) 
1419 {
1420     /* These prefixes are meant to be concatenated with hash values of the
1421      * respective kind to form a PKCS #7 DigestInfo. */
1422     static const struct tagOIDDescriptor {
1423         ALG_ID aiAlgid;
1424         DWORD dwLen;
1425         CONST BYTE abOID[18];
1426     } aOIDDescriptor[5] = {
1427         { CALG_MD2, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48,
1428                           0x86, 0xf7, 0x0d, 0x02, 0x02, 0x05, 0x00, 0x04, 0x10 } },
1429         { CALG_MD4, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 
1430                           0x86, 0xf7, 0x0d, 0x02, 0x04, 0x05, 0x00, 0x04, 0x10 } },
1431         { CALG_MD5, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48,
1432                           0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10 } },
1433         { CALG_SHA, 15, { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 
1434                           0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 } },
1435         { 0,        0,  { 0 } }
1436     };
1437     DWORD dwIdxOID, i, j;
1438
1439     for (dwIdxOID = 0; aOIDDescriptor[dwIdxOID].aiAlgid; dwIdxOID++) {
1440         if (aOIDDescriptor[dwIdxOID].aiAlgid == aiAlgid) break;
1441     }
1442     
1443     if (!aOIDDescriptor[dwIdxOID].aiAlgid) {
1444         SetLastError(NTE_BAD_ALGID);
1445         return FALSE;
1446     }
1447
1448     /* Build the padded signature */
1449     if (dwFlags & CRYPT_X931_FORMAT) {
1450         pbSignature[0] = 0x6b;
1451         for (i=1; i < dwLen - dwHashLen - 3; i++) {
1452             pbSignature[i] = 0xbb;
1453         }
1454         pbSignature[i++] = 0xba;
1455         for (j=0; j < dwHashLen; j++, i++) {
1456             pbSignature[i] = abHashValue[j];
1457         }
1458         pbSignature[i++] = 0x33;
1459         pbSignature[i++] = 0xcc;
1460     } else {
1461         pbSignature[0] = 0x00;
1462         pbSignature[1] = 0x01;
1463         if (dwFlags & CRYPT_NOHASHOID) {
1464             for (i=2; i < dwLen - 1 - dwHashLen; i++) {
1465                 pbSignature[i] = 0xff;
1466             }
1467             pbSignature[i++] = 0x00;
1468         } else {
1469             for (i=2; i < dwLen - 1 - aOIDDescriptor[dwIdxOID].dwLen - dwHashLen; i++) {
1470                 pbSignature[i] = 0xff;
1471             }
1472             pbSignature[i++] = 0x00;
1473             for (j=0; j < aOIDDescriptor[dwIdxOID].dwLen; j++) {
1474                 pbSignature[i++] = aOIDDescriptor[dwIdxOID].abOID[j];
1475             }
1476         }
1477         for (j=0; j < dwHashLen; j++) {
1478             pbSignature[i++] = abHashValue[j];
1479         }
1480     }
1481     
1482     return TRUE;
1483 }
1484
1485 /******************************************************************************
1486  * tls1_p [Internal]
1487  *
1488  * This is an implementation of the 'P_hash' helper function for TLS1's PRF.
1489  * It is used exclusively by tls1_prf. For details see RFC 2246, chapter 5.
1490  * The pseudo random stream generated by this function is exclusive or'ed with
1491  * the data in pbBuffer.
1492  *
1493  * PARAMS
1494  *  hHMAC       [I]   HMAC object, which will be used in pseudo random generation
1495  *  pblobSeed   [I]   Seed value
1496  *  pbBuffer    [I/O] Pseudo random stream will be xor'ed to the provided data
1497  *  dwBufferLen [I]   Number of pseudo random bytes desired
1498  *
1499  * RETURNS
1500  *  Success: TRUE
1501  *  Failure: FALSE
1502  */
1503 static BOOL tls1_p(HCRYPTHASH hHMAC, CONST PCRYPT_DATA_BLOB pblobSeed, PBYTE pbBuffer, DWORD dwBufferLen)
1504 {
1505     CRYPTHASH *pHMAC;
1506     BYTE abAi[RSAENH_MAX_HASH_SIZE];
1507     DWORD i = 0;
1508
1509     if (!lookup_handle(&handle_table, hHMAC, RSAENH_MAGIC_HASH, (OBJECTHDR**)&pHMAC)) {
1510         SetLastError(NTE_BAD_HASH);
1511         return FALSE;
1512     }
1513     
1514     /* compute A_1 = HMAC(seed) */
1515     init_hash(pHMAC);
1516     update_hash(pHMAC, pblobSeed->pbData, pblobSeed->cbData);
1517     finalize_hash(pHMAC);
1518     memcpy(abAi, pHMAC->abHashValue, pHMAC->dwHashSize);
1519
1520     do {
1521         /* compute HMAC(A_i + seed) */
1522         init_hash(pHMAC);
1523         update_hash(pHMAC, abAi, pHMAC->dwHashSize);
1524         update_hash(pHMAC, pblobSeed->pbData, pblobSeed->cbData);
1525         finalize_hash(pHMAC);
1526
1527         /* pseudo random stream := CONCAT_{i=1..n} ( HMAC(A_i + seed) ) */
1528         do {
1529             if (i >= dwBufferLen) break;
1530             pbBuffer[i] ^= pHMAC->abHashValue[i % pHMAC->dwHashSize];
1531             i++;
1532         } while (i % pHMAC->dwHashSize);
1533
1534         /* compute A_{i+1} = HMAC(A_i) */
1535         init_hash(pHMAC);
1536         update_hash(pHMAC, abAi, pHMAC->dwHashSize);
1537         finalize_hash(pHMAC);
1538         memcpy(abAi, pHMAC->abHashValue, pHMAC->dwHashSize);
1539     } while (i < dwBufferLen);
1540
1541     return TRUE;
1542 }
1543
1544 /******************************************************************************
1545  * tls1_prf [Internal]
1546  *
1547  * TLS1 pseudo random function as specified in RFC 2246, chapter 5
1548  *
1549  * PARAMS
1550  *  hProv       [I] Key container used to compute the pseudo random stream
1551  *  hSecret     [I] Key that holds the (pre-)master secret
1552  *  pblobLabel  [I] Descriptive label
1553  *  pblobSeed   [I] Seed value
1554  *  pbBuffer    [O] Pseudo random numbers will be stored here
1555  *  dwBufferLen [I] Number of pseudo random bytes desired
1556  *
1557  * RETURNS
1558  *  Success: TRUE
1559  *  Failure: FALSE
1560  */ 
1561 static BOOL tls1_prf(HCRYPTPROV hProv, HCRYPTPROV hSecret, CONST PCRYPT_DATA_BLOB pblobLabel,
1562                      CONST PCRYPT_DATA_BLOB pblobSeed, PBYTE pbBuffer, DWORD dwBufferLen)
1563 {
1564     HMAC_INFO hmacInfo = { 0, NULL, 0, NULL, 0 };
1565     HCRYPTHASH hHMAC = (HCRYPTHASH)INVALID_HANDLE_VALUE;
1566     HCRYPTKEY hHalfSecret = (HCRYPTKEY)INVALID_HANDLE_VALUE;
1567     CRYPTKEY *pHalfSecret, *pSecret;
1568     DWORD dwHalfSecretLen;
1569     BOOL result = FALSE;
1570     CRYPT_DATA_BLOB blobLabelSeed;
1571
1572     TRACE("(hProv=%08lx, hSecret=%08lx, pblobLabel=%p, pblobSeed=%p, pbBuffer=%p, dwBufferLen=%d)\n",
1573           hProv, hSecret, pblobLabel, pblobSeed, pbBuffer, dwBufferLen);
1574
1575     if (!lookup_handle(&handle_table, hSecret, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pSecret)) {
1576         SetLastError(NTE_FAIL);
1577         return FALSE;
1578     }
1579
1580     dwHalfSecretLen = (pSecret->dwKeyLen+1)/2;
1581     
1582     /* concatenation of the label and the seed */
1583     if (!concat_data_blobs(&blobLabelSeed, pblobLabel, pblobSeed)) goto exit;
1584    
1585     /* zero out the buffer, since two random streams will be xor'ed into it. */
1586     memset(pbBuffer, 0, dwBufferLen);
1587    
1588     /* build a 'fake' key, to hold the secret. CALG_SSL2_MASTER is used since it provides
1589      * the biggest range of valid key lengths. */
1590     hHalfSecret = new_key(hProv, CALG_SSL2_MASTER, MAKELONG(0,dwHalfSecretLen*8), &pHalfSecret);
1591     if (hHalfSecret == (HCRYPTKEY)INVALID_HANDLE_VALUE) goto exit;
1592
1593     /* Derive an HMAC_MD5 hash and call the helper function. */
1594     memcpy(pHalfSecret->abKeyValue, pSecret->abKeyValue, dwHalfSecretLen);
1595     if (!RSAENH_CPCreateHash(hProv, CALG_HMAC, hHalfSecret, 0, &hHMAC)) goto exit;
1596     hmacInfo.HashAlgid = CALG_MD5;
1597     if (!RSAENH_CPSetHashParam(hProv, hHMAC, HP_HMAC_INFO, (BYTE*)&hmacInfo, 0)) goto exit;
1598     if (!tls1_p(hHMAC, &blobLabelSeed, pbBuffer, dwBufferLen)) goto exit;
1599
1600     /* Reconfigure to HMAC_SHA hash and call helper function again. */
1601     memcpy(pHalfSecret->abKeyValue, pSecret->abKeyValue + (pSecret->dwKeyLen/2), dwHalfSecretLen);
1602     hmacInfo.HashAlgid = CALG_SHA;
1603     if (!RSAENH_CPSetHashParam(hProv, hHMAC, HP_HMAC_INFO, (BYTE*)&hmacInfo, 0)) goto exit;
1604     if (!tls1_p(hHMAC, &blobLabelSeed, pbBuffer, dwBufferLen)) goto exit;
1605     
1606     result = TRUE;
1607 exit:
1608     release_handle(&handle_table, hHalfSecret, RSAENH_MAGIC_KEY);
1609     if (hHMAC != (HCRYPTHASH)INVALID_HANDLE_VALUE) RSAENH_CPDestroyHash(hProv, hHMAC);
1610     free_data_blob(&blobLabelSeed);
1611     return result;
1612 }
1613
1614 /******************************************************************************
1615  * pad_data [Internal]
1616  *
1617  * Helper function for data padding according to PKCS1 #2
1618  *
1619  * PARAMS
1620  *  abData      [I] The data to be padded
1621  *  dwDataLen   [I] Length of the data 
1622  *  abBuffer    [O] Padded data will be stored here
1623  *  dwBufferLen [I] Length of the buffer (also length of padded data)
1624  *  dwFlags     [I] Padding format (CRYPT_SSL2_FALLBACK)
1625  *
1626  * RETURN
1627  *  Success: TRUE
1628  *  Failure: FALSE (NTE_BAD_LEN, too much data to pad)
1629  */
1630 static BOOL pad_data(CONST BYTE *abData, DWORD dwDataLen, BYTE *abBuffer, DWORD dwBufferLen, 
1631                      DWORD dwFlags)
1632 {
1633     DWORD i;
1634     
1635     /* Ensure there is enough space for PKCS1 #2 padding */
1636     if (dwDataLen > dwBufferLen-11) {
1637         SetLastError(NTE_BAD_LEN);
1638         return FALSE;
1639     }
1640
1641     memmove(abBuffer + dwBufferLen - dwDataLen, abData, dwDataLen);            
1642     
1643     abBuffer[0] = 0x00;
1644     abBuffer[1] = RSAENH_PKC_BLOCKTYPE; 
1645     for (i=2; i < dwBufferLen - dwDataLen - 1; i++) 
1646         do gen_rand_impl(&abBuffer[i], 1); while (!abBuffer[i]);
1647     if (dwFlags & CRYPT_SSL2_FALLBACK) 
1648         for (i-=8; i < dwBufferLen - dwDataLen - 1; i++) 
1649             abBuffer[i] = 0x03;
1650     abBuffer[i] = 0x00;
1651     
1652     return TRUE; 
1653 }
1654
1655 /******************************************************************************
1656  * unpad_data [Internal]
1657  *
1658  * Remove the PKCS1 padding from RSA decrypted data
1659  *
1660  * PARAMS
1661  *  abData      [I]   The padded data
1662  *  dwDataLen   [I]   Length of the padded data
1663  *  abBuffer    [O]   Data without padding will be stored here
1664  *  dwBufferLen [I/O] I: Length of the buffer, O: Length of unpadded data
1665  *  dwFlags     [I]   Currently none defined
1666  *
1667  * RETURNS
1668  *  Success: TRUE
1669  *  Failure: FALSE, (NTE_BAD_DATA, no valid PKCS1 padding or buffer too small)
1670  */
1671 static BOOL unpad_data(CONST BYTE *abData, DWORD dwDataLen, BYTE *abBuffer, DWORD *dwBufferLen, 
1672                        DWORD dwFlags)
1673 {
1674     DWORD i;
1675     
1676     for (i=2; i<dwDataLen; i++)
1677         if (!abData[i])
1678             break;
1679
1680     if ((i == dwDataLen) || (*dwBufferLen < dwDataLen - i - 1) ||
1681         (abData[0] != 0x00) || (abData[1] != RSAENH_PKC_BLOCKTYPE))
1682     {
1683         SetLastError(NTE_BAD_DATA);
1684         return FALSE;
1685     }
1686
1687     *dwBufferLen = dwDataLen - i - 1;
1688     memmove(abBuffer, abData + i + 1, *dwBufferLen);
1689     return TRUE;
1690 }
1691
1692 /******************************************************************************
1693  * CPAcquireContext (RSAENH.@)
1694  *
1695  * Acquire a handle to the key container specified by pszContainer
1696  *
1697  * PARAMS
1698  *  phProv       [O] Pointer to the location the acquired handle will be written to.
1699  *  pszContainer [I] Name of the desired key container. See Notes
1700  *  dwFlags      [I] Flags. See Notes.
1701  *  pVTable      [I] Pointer to a PVTableProvStruct containing callbacks.
1702  * 
1703  * RETURNS
1704  *  Success: TRUE
1705  *  Failure: FALSE
1706  *
1707  * NOTES
1708  *  If pszContainer is NULL or points to a zero length string the user's login 
1709  *  name will be used as the key container name.
1710  *
1711  *  If the CRYPT_NEW_KEYSET flag is set in dwFlags a new keyset will be created.
1712  *  If a keyset with the given name already exists, the function fails and sets
1713  *  last error to NTE_EXISTS. If CRYPT_NEW_KEYSET is not set and the specified
1714  *  key container does not exist, function fails and sets last error to 
1715  *  NTE_BAD_KEYSET.
1716  */                         
1717 BOOL WINAPI RSAENH_CPAcquireContext(HCRYPTPROV *phProv, LPSTR pszContainer,
1718                    DWORD dwFlags, PVTableProvStruc pVTable)
1719 {
1720     CHAR szKeyContainerName[MAX_PATH];
1721
1722     TRACE("(phProv=%p, pszContainer=%s, dwFlags=%08x, pVTable=%p)\n", phProv,
1723           debugstr_a(pszContainer), dwFlags, pVTable);
1724
1725     if (pszContainer && *pszContainer)
1726     {
1727         lstrcpynA(szKeyContainerName, pszContainer, MAX_PATH);
1728     } 
1729     else
1730     {
1731         DWORD dwLen = sizeof(szKeyContainerName);
1732         if (!GetUserNameA(szKeyContainerName, &dwLen)) return FALSE;
1733     }
1734
1735     switch (dwFlags & (CRYPT_NEWKEYSET|CRYPT_VERIFYCONTEXT|CRYPT_DELETEKEYSET)) 
1736     {
1737         case 0:
1738             *phProv = read_key_container(szKeyContainerName, dwFlags, pVTable);
1739             break;
1740
1741         case CRYPT_DELETEKEYSET:
1742             return delete_container_key(szKeyContainerName, dwFlags);
1743
1744         case CRYPT_NEWKEYSET:
1745             *phProv = read_key_container(szKeyContainerName, dwFlags, pVTable);
1746             if (*phProv != (HCRYPTPROV)INVALID_HANDLE_VALUE) 
1747             {
1748                 release_handle(&handle_table, *phProv, RSAENH_MAGIC_CONTAINER);
1749                 TRACE("Can't create new keyset, already exists\n");
1750                 SetLastError(NTE_EXISTS);
1751                 return FALSE;
1752             }
1753             *phProv = new_key_container(szKeyContainerName, dwFlags, pVTable);
1754             break;
1755
1756         case CRYPT_VERIFYCONTEXT|CRYPT_NEWKEYSET:
1757         case CRYPT_VERIFYCONTEXT:
1758             if (pszContainer && *pszContainer) {
1759                 TRACE("pszContainer should be empty\n");
1760                 SetLastError(NTE_BAD_FLAGS);
1761                 return FALSE;
1762             }
1763             *phProv = new_key_container("", dwFlags, pVTable);
1764             break;
1765             
1766         default:
1767             *phProv = (HCRYPTPROV)INVALID_HANDLE_VALUE;
1768             SetLastError(NTE_BAD_FLAGS);
1769             return FALSE;
1770     }
1771                 
1772     if (*phProv != (HCRYPTPROV)INVALID_HANDLE_VALUE) {
1773         SetLastError(ERROR_SUCCESS);
1774         return TRUE;
1775     } else {
1776         return FALSE;
1777     }
1778 }
1779
1780 /******************************************************************************
1781  * CPCreateHash (RSAENH.@)
1782  *
1783  * CPCreateHash creates and initalizes a new hash object.
1784  *
1785  * PARAMS
1786  *  hProv   [I] Handle to the key container to which the new hash will belong.
1787  *  Algid   [I] Identifies the hash algorithm, which will be used for the hash.
1788  *  hKey    [I] Handle to a session key applied for keyed hashes.
1789  *  dwFlags [I] Currently no flags defined. Must be zero.
1790  *  phHash  [O] Points to the location where a handle to the new hash will be stored.
1791  *
1792  * RETURNS
1793  *  Success: TRUE
1794  *  Failure: FALSE
1795  *
1796  * NOTES
1797  *  hKey is a handle to a session key applied in keyed hashes like MAC and HMAC.
1798  *  If a normal hash object is to be created (like e.g. MD2 or SHA1) hKey must be zero.
1799  */
1800 BOOL WINAPI RSAENH_CPCreateHash(HCRYPTPROV hProv, ALG_ID Algid, HCRYPTKEY hKey, DWORD dwFlags, 
1801                                 HCRYPTHASH *phHash)
1802 {
1803     CRYPTKEY *pCryptKey;
1804     CRYPTHASH *pCryptHash;
1805     const PROV_ENUMALGS_EX *peaAlgidInfo;
1806         
1807     TRACE("(hProv=%08lx, Algid=%08x, hKey=%08lx, dwFlags=%08x, phHash=%p)\n", hProv, Algid, hKey,
1808           dwFlags, phHash);
1809
1810     peaAlgidInfo = get_algid_info(hProv, Algid);
1811     if (!peaAlgidInfo) return FALSE;
1812
1813     if (dwFlags)
1814     {
1815         SetLastError(NTE_BAD_FLAGS);
1816         return FALSE;
1817     }
1818
1819     if (Algid == CALG_MAC || Algid == CALG_HMAC || Algid == CALG_SCHANNEL_MASTER_HASH || 
1820         Algid == CALG_TLS1PRF) 
1821     {
1822         if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey)) {
1823             SetLastError(NTE_BAD_KEY);
1824             return FALSE;
1825         }
1826
1827         if ((Algid == CALG_MAC) && (GET_ALG_TYPE(pCryptKey->aiAlgid) != ALG_TYPE_BLOCK)) {
1828             SetLastError(NTE_BAD_KEY);
1829             return FALSE;
1830         }
1831
1832         if ((Algid == CALG_SCHANNEL_MASTER_HASH || Algid == CALG_TLS1PRF) && 
1833             (pCryptKey->aiAlgid != CALG_TLS1_MASTER)) 
1834         {
1835             SetLastError(NTE_BAD_KEY);
1836             return FALSE;
1837         }
1838
1839         if ((Algid == CALG_TLS1PRF) && (pCryptKey->dwState != RSAENH_KEYSTATE_MASTERKEY)) {
1840             SetLastError(NTE_BAD_KEY_STATE);
1841             return FALSE;
1842         }
1843     }
1844
1845     *phHash = new_object(&handle_table, sizeof(CRYPTHASH), RSAENH_MAGIC_HASH,
1846                          destroy_hash, (OBJECTHDR**)&pCryptHash);
1847     if (!pCryptHash) return FALSE;
1848
1849     pCryptHash->aiAlgid = Algid;
1850     pCryptHash->hKey = hKey;
1851     pCryptHash->hProv = hProv;
1852     pCryptHash->dwState = RSAENH_HASHSTATE_HASHING;
1853     pCryptHash->pHMACInfo = NULL;
1854     pCryptHash->dwHashSize = peaAlgidInfo->dwDefaultLen >> 3;
1855     init_data_blob(&pCryptHash->tpPRFParams.blobLabel);
1856     init_data_blob(&pCryptHash->tpPRFParams.blobSeed);
1857
1858     if (Algid == CALG_SCHANNEL_MASTER_HASH) {
1859         static const char keyex[] = "key expansion";
1860         BYTE key_expansion[sizeof keyex];
1861         CRYPT_DATA_BLOB blobRandom, blobKeyExpansion = { 13, key_expansion };
1862
1863         memcpy( key_expansion, keyex, sizeof keyex );
1864         
1865         if (pCryptKey->dwState != RSAENH_KEYSTATE_MASTERKEY) {
1866             static const char msec[] = "master secret";
1867             BYTE master_secret[sizeof msec];
1868             CRYPT_DATA_BLOB blobLabel = { 13, master_secret };
1869             BYTE abKeyValue[48];
1870
1871             memcpy( master_secret, msec, sizeof msec );
1872     
1873             /* See RFC 2246, chapter 8.1 */
1874             if (!concat_data_blobs(&blobRandom, 
1875                                    &pCryptKey->siSChannelInfo.blobClientRandom, 
1876                                    &pCryptKey->siSChannelInfo.blobServerRandom))
1877             {
1878                 return FALSE;
1879             }
1880             tls1_prf(hProv, hKey, &blobLabel, &blobRandom, abKeyValue, 48);
1881             pCryptKey->dwState = RSAENH_KEYSTATE_MASTERKEY; 
1882             memcpy(pCryptKey->abKeyValue, abKeyValue, 48);
1883             free_data_blob(&blobRandom);
1884         }
1885
1886         /* See RFC 2246, chapter 6.3 */
1887         if (!concat_data_blobs(&blobRandom, 
1888                                   &pCryptKey->siSChannelInfo.blobServerRandom, 
1889                                   &pCryptKey->siSChannelInfo.blobClientRandom))
1890         {
1891             return FALSE;
1892         }
1893         tls1_prf(hProv, hKey, &blobKeyExpansion, &blobRandom, pCryptHash->abHashValue, 
1894                  RSAENH_MAX_HASH_SIZE);
1895         free_data_blob(&blobRandom);
1896     }
1897
1898     return init_hash(pCryptHash);
1899 }
1900
1901 /******************************************************************************
1902  * CPDestroyHash (RSAENH.@)
1903  * 
1904  * Releases the handle to a hash object. The object is destroyed if it's reference
1905  * count reaches zero.
1906  *
1907  * PARAMS
1908  *  hProv [I] Handle to the key container to which the hash object belongs.
1909  *  hHash [I] Handle to the hash object to be released.
1910  *
1911  * RETURNS
1912  *  Success: TRUE
1913  *  Failure: FALSE 
1914  */
1915 BOOL WINAPI RSAENH_CPDestroyHash(HCRYPTPROV hProv, HCRYPTHASH hHash)
1916 {
1917     TRACE("(hProv=%08lx, hHash=%08lx)\n", hProv, hHash);
1918      
1919     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
1920     {
1921         SetLastError(NTE_BAD_UID);
1922         return FALSE;
1923     }
1924         
1925     if (!release_handle(&handle_table, hHash, RSAENH_MAGIC_HASH)) 
1926     {
1927         SetLastError(NTE_BAD_HASH);
1928         return FALSE;
1929     }
1930     
1931     return TRUE;
1932 }
1933
1934 /******************************************************************************
1935  * CPDestroyKey (RSAENH.@)
1936  *
1937  * Releases the handle to a key object. The object is destroyed if it's reference
1938  * count reaches zero.
1939  *
1940  * PARAMS
1941  *  hProv [I] Handle to the key container to which the key object belongs.
1942  *  hKey  [I] Handle to the key object to be released.
1943  *
1944  * RETURNS
1945  *  Success: TRUE
1946  *  Failure: FALSE
1947  */
1948 BOOL WINAPI RSAENH_CPDestroyKey(HCRYPTPROV hProv, HCRYPTKEY hKey)
1949 {
1950     TRACE("(hProv=%08lx, hKey=%08lx)\n", hProv, hKey);
1951         
1952     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
1953     {
1954         SetLastError(NTE_BAD_UID);
1955         return FALSE;
1956     }
1957         
1958     if (!release_handle(&handle_table, hKey, RSAENH_MAGIC_KEY)) 
1959     {
1960         SetLastError(NTE_BAD_KEY);
1961         return FALSE;
1962     }
1963     
1964     return TRUE;
1965 }
1966
1967 /******************************************************************************
1968  * CPDuplicateHash (RSAENH.@)
1969  *
1970  * Clones a hash object including it's current state.
1971  *
1972  * PARAMS
1973  *  hUID        [I] Handle to the key container the hash belongs to.
1974  *  hHash       [I] Handle to the hash object to be cloned.
1975  *  pdwReserved [I] Reserved. Must be NULL.
1976  *  dwFlags     [I] No flags are currently defined. Must be 0.
1977  *  phHash      [O] Handle to the cloned hash object.
1978  *
1979  * RETURNS
1980  *  Success: TRUE.
1981  *  Failure: FALSE.
1982  */
1983 BOOL WINAPI RSAENH_CPDuplicateHash(HCRYPTPROV hUID, HCRYPTHASH hHash, DWORD *pdwReserved, 
1984                                    DWORD dwFlags, HCRYPTHASH *phHash)
1985 {
1986     CRYPTHASH *pSrcHash, *pDestHash;
1987     
1988     TRACE("(hUID=%08lx, hHash=%08lx, pdwReserved=%p, dwFlags=%08x, phHash=%p)\n", hUID, hHash,
1989            pdwReserved, dwFlags, phHash);
1990
1991     if (!is_valid_handle(&handle_table, hUID, RSAENH_MAGIC_CONTAINER))
1992     {
1993         SetLastError(NTE_BAD_UID);
1994         return FALSE;
1995     }
1996
1997     if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH, (OBJECTHDR**)&pSrcHash))
1998     {
1999         SetLastError(NTE_BAD_HASH);
2000         return FALSE;
2001     }
2002
2003     if (!phHash || pdwReserved || dwFlags) 
2004     {
2005         SetLastError(ERROR_INVALID_PARAMETER);
2006         return FALSE;
2007     }
2008
2009     *phHash = new_object(&handle_table, sizeof(CRYPTHASH), RSAENH_MAGIC_HASH,
2010                          destroy_hash, (OBJECTHDR**)&pDestHash);
2011     if (*phHash != (HCRYPTHASH)INVALID_HANDLE_VALUE)
2012     {
2013         *pDestHash = *pSrcHash;
2014         duplicate_hash_impl(pSrcHash->aiAlgid, &pSrcHash->context, &pDestHash->context);
2015         copy_hmac_info(&pDestHash->pHMACInfo, pSrcHash->pHMACInfo);
2016         copy_data_blob(&pDestHash->tpPRFParams.blobLabel, &pSrcHash->tpPRFParams.blobLabel);
2017         copy_data_blob(&pDestHash->tpPRFParams.blobSeed, &pSrcHash->tpPRFParams.blobSeed);
2018     }
2019
2020     return *phHash != (HCRYPTHASH)INVALID_HANDLE_VALUE;
2021 }
2022
2023 /******************************************************************************
2024  * CPDuplicateKey (RSAENH.@)
2025  *
2026  * Clones a key object including it's current state.
2027  *
2028  * PARAMS
2029  *  hUID        [I] Handle to the key container the hash belongs to.
2030  *  hKey        [I] Handle to the key object to be cloned.
2031  *  pdwReserved [I] Reserved. Must be NULL.
2032  *  dwFlags     [I] No flags are currently defined. Must be 0.
2033  *  phHash      [O] Handle to the cloned key object.
2034  *
2035  * RETURNS
2036  *  Success: TRUE.
2037  *  Failure: FALSE.
2038  */
2039 BOOL WINAPI RSAENH_CPDuplicateKey(HCRYPTPROV hUID, HCRYPTKEY hKey, DWORD *pdwReserved, 
2040                                   DWORD dwFlags, HCRYPTKEY *phKey)
2041 {
2042     CRYPTKEY *pSrcKey, *pDestKey;
2043     
2044     TRACE("(hUID=%08lx, hKey=%08lx, pdwReserved=%p, dwFlags=%08x, phKey=%p)\n", hUID, hKey,
2045           pdwReserved, dwFlags, phKey);
2046
2047     if (!is_valid_handle(&handle_table, hUID, RSAENH_MAGIC_CONTAINER))
2048     {
2049         SetLastError(NTE_BAD_UID);
2050         return FALSE;
2051     }
2052
2053     if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pSrcKey))
2054     {
2055         SetLastError(NTE_BAD_KEY);
2056         return FALSE;
2057     }
2058
2059     if (!phKey || pdwReserved || dwFlags) 
2060     {
2061         SetLastError(ERROR_INVALID_PARAMETER);
2062         return FALSE;
2063     }
2064
2065     *phKey = new_object(&handle_table, sizeof(CRYPTKEY), RSAENH_MAGIC_KEY, destroy_key,
2066                         (OBJECTHDR**)&pDestKey);
2067     if (*phKey != (HCRYPTKEY)INVALID_HANDLE_VALUE)
2068     {
2069         *pDestKey = *pSrcKey;
2070         copy_data_blob(&pDestKey->siSChannelInfo.blobServerRandom,
2071                        &pSrcKey->siSChannelInfo.blobServerRandom);
2072         copy_data_blob(&pDestKey->siSChannelInfo.blobClientRandom, 
2073                        &pSrcKey->siSChannelInfo.blobClientRandom);
2074         duplicate_key_impl(pSrcKey->aiAlgid, &pSrcKey->context, &pDestKey->context);
2075         return TRUE;
2076     }
2077     else
2078     {
2079         return FALSE;
2080     }
2081 }
2082
2083 /******************************************************************************
2084  * CPEncrypt (RSAENH.@)
2085  *
2086  * Encrypt data.
2087  *
2088  * PARAMS
2089  *  hProv      [I]   The key container hKey and hHash belong to.
2090  *  hKey       [I]   The key used to encrypt the data.
2091  *  hHash      [I]   An optional hash object for parallel hashing. See notes.
2092  *  Final      [I]   Indicates if this is the last block of data to encrypt.
2093  *  dwFlags    [I]   Currently no flags defined. Must be zero.
2094  *  pbData     [I/O] Pointer to the data to encrypt. Encrypted data will also be stored there. 
2095  *  pdwDataLen [I/O] I: Length of data to encrypt, O: Length of encrypted data.
2096  *  dwBufLen   [I]   Size of the buffer at pbData.
2097  *
2098  * RETURNS
2099  *  Success: TRUE.
2100  *  Failure: FALSE.
2101  *
2102  * NOTES
2103  *  If a hash object handle is provided in hHash, it will be updated with the plaintext. 
2104  *  This is useful for message signatures.
2105  *
2106  *  This function uses the standard WINAPI protocol for querying data of dynamic length. 
2107  */
2108 BOOL WINAPI RSAENH_CPEncrypt(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final, 
2109                              DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen, DWORD dwBufLen)
2110 {
2111     CRYPTKEY *pCryptKey;
2112     BYTE *in, out[RSAENH_MAX_BLOCK_SIZE], o[RSAENH_MAX_BLOCK_SIZE];
2113     DWORD dwEncryptedLen, i, j, k;
2114         
2115     TRACE("(hProv=%08lx, hKey=%08lx, hHash=%08lx, Final=%d, dwFlags=%08x, pbData=%p, "
2116           "pdwDataLen=%p, dwBufLen=%d)\n", hProv, hKey, hHash, Final, dwFlags, pbData, pdwDataLen,
2117           dwBufLen);
2118     
2119     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2120     {
2121         SetLastError(NTE_BAD_UID);
2122         return FALSE;
2123     }
2124
2125     if (dwFlags)
2126     {
2127         SetLastError(NTE_BAD_FLAGS);
2128         return FALSE;
2129     }
2130
2131     if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2132     {
2133         SetLastError(NTE_BAD_KEY);
2134         return FALSE;
2135     }
2136
2137     if (pCryptKey->dwState == RSAENH_KEYSTATE_IDLE) 
2138         pCryptKey->dwState = RSAENH_KEYSTATE_ENCRYPTING;
2139
2140     if (pCryptKey->dwState != RSAENH_KEYSTATE_ENCRYPTING) 
2141     {
2142         SetLastError(NTE_BAD_DATA);
2143         return FALSE;
2144     }
2145
2146     if (is_valid_handle(&handle_table, hHash, RSAENH_MAGIC_HASH)) {
2147         if (!RSAENH_CPHashData(hProv, hHash, pbData, *pdwDataLen, 0)) return FALSE;
2148     }
2149     
2150     if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_BLOCK) {
2151         if (!Final && (*pdwDataLen % pCryptKey->dwBlockLen)) {
2152             SetLastError(NTE_BAD_DATA);
2153             return FALSE;
2154         }
2155
2156         dwEncryptedLen = (*pdwDataLen/pCryptKey->dwBlockLen+(Final?1:0))*pCryptKey->dwBlockLen;
2157
2158         if (pbData == NULL) {
2159             *pdwDataLen = dwEncryptedLen;
2160             return TRUE;
2161         }
2162         else if (dwEncryptedLen > dwBufLen) {
2163             *pdwDataLen = dwEncryptedLen;
2164             SetLastError(ERROR_MORE_DATA);
2165             return FALSE;
2166         }
2167
2168         /* Pad final block with length bytes */
2169         for (i=*pdwDataLen; i<dwEncryptedLen; i++) pbData[i] = dwEncryptedLen - *pdwDataLen;
2170         *pdwDataLen = dwEncryptedLen;
2171
2172         for (i=0, in=pbData; i<*pdwDataLen; i+=pCryptKey->dwBlockLen, in+=pCryptKey->dwBlockLen) {
2173             switch (pCryptKey->dwMode) {
2174                 case CRYPT_MODE_ECB:
2175                     encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out, 
2176                                        RSAENH_ENCRYPT);
2177                     break;
2178                 
2179                 case CRYPT_MODE_CBC:
2180                     for (j=0; j<pCryptKey->dwBlockLen; j++) in[j] ^= pCryptKey->abChainVector[j];
2181                     encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out, 
2182                                        RSAENH_ENCRYPT);
2183                     memcpy(pCryptKey->abChainVector, out, pCryptKey->dwBlockLen);
2184                     break;
2185
2186                 case CRYPT_MODE_CFB:
2187                     for (j=0; j<pCryptKey->dwBlockLen; j++) {
2188                         encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, 
2189                                            pCryptKey->abChainVector, o, RSAENH_ENCRYPT);
2190                         out[j] = in[j] ^ o[0];
2191                         for (k=0; k<pCryptKey->dwBlockLen-1; k++) 
2192                             pCryptKey->abChainVector[k] = pCryptKey->abChainVector[k+1];
2193                         pCryptKey->abChainVector[k] = out[j];
2194                     }
2195                     break;
2196                     
2197                 default:
2198                     SetLastError(NTE_BAD_ALGID);
2199                     return FALSE;
2200             }
2201             memcpy(in, out, pCryptKey->dwBlockLen); 
2202         }
2203     } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_STREAM) {
2204         if (pbData == NULL) {
2205             *pdwDataLen = dwBufLen;
2206             return TRUE;
2207         }
2208         encrypt_stream_impl(pCryptKey->aiAlgid, &pCryptKey->context, pbData, *pdwDataLen);
2209     } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_RSA) {
2210         if (pCryptKey->aiAlgid == CALG_RSA_SIGN) {
2211             SetLastError(NTE_BAD_KEY);
2212             return FALSE;
2213         }
2214         if (!pbData) {
2215             *pdwDataLen = pCryptKey->dwBlockLen;
2216             return TRUE;
2217         }
2218         if (dwBufLen < pCryptKey->dwBlockLen) {
2219             SetLastError(ERROR_MORE_DATA);
2220             return FALSE;
2221         }
2222         if (!pad_data(pbData, *pdwDataLen, pbData, pCryptKey->dwBlockLen, dwFlags)) return FALSE;
2223         encrypt_block_impl(pCryptKey->aiAlgid, PK_PUBLIC, &pCryptKey->context, pbData, pbData, RSAENH_ENCRYPT);
2224         *pdwDataLen = pCryptKey->dwBlockLen;
2225         Final = TRUE;
2226     } else {
2227         SetLastError(NTE_BAD_TYPE);
2228         return FALSE;
2229     }
2230
2231     if (Final) setup_key(pCryptKey);
2232
2233     return TRUE;
2234 }
2235
2236 /******************************************************************************
2237  * CPDecrypt (RSAENH.@)
2238  *
2239  * Decrypt data.
2240  *
2241  * PARAMS
2242  *  hProv      [I]   The key container hKey and hHash belong to.
2243  *  hKey       [I]   The key used to decrypt the data.
2244  *  hHash      [I]   An optional hash object for parallel hashing. See notes.
2245  *  Final      [I]   Indicates if this is the last block of data to decrypt.
2246  *  dwFlags    [I]   Currently no flags defined. Must be zero.
2247  *  pbData     [I/O] Pointer to the data to decrypt. Plaintext will also be stored there. 
2248  *  pdwDataLen [I/O] I: Length of ciphertext, O: Length of plaintext.
2249  *
2250  * RETURNS
2251  *  Success: TRUE.
2252  *  Failure: FALSE.
2253  *
2254  * NOTES
2255  *  If a hash object handle is provided in hHash, it will be updated with the plaintext. 
2256  *  This is useful for message signatures.
2257  *
2258  *  This function uses the standard WINAPI protocol for querying data of dynamic length. 
2259  */
2260 BOOL WINAPI RSAENH_CPDecrypt(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final, 
2261                              DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2262 {
2263     CRYPTKEY *pCryptKey;
2264     BYTE *in, out[RSAENH_MAX_BLOCK_SIZE], o[RSAENH_MAX_BLOCK_SIZE];
2265     DWORD i, j, k;
2266     DWORD dwMax;
2267
2268     TRACE("(hProv=%08lx, hKey=%08lx, hHash=%08lx, Final=%d, dwFlags=%08x, pbData=%p, "
2269           "pdwDataLen=%p)\n", hProv, hKey, hHash, Final, dwFlags, pbData, pdwDataLen);
2270     
2271     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2272     {
2273         SetLastError(NTE_BAD_UID);
2274         return FALSE;
2275     }
2276
2277     if (dwFlags)
2278     {
2279         SetLastError(NTE_BAD_FLAGS);
2280         return FALSE;
2281     }
2282
2283     if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2284     {
2285         SetLastError(NTE_BAD_KEY);
2286         return FALSE;
2287     }
2288
2289     if (pCryptKey->dwState == RSAENH_KEYSTATE_IDLE) 
2290         pCryptKey->dwState = RSAENH_KEYSTATE_ENCRYPTING;
2291
2292     if (pCryptKey->dwState != RSAENH_KEYSTATE_ENCRYPTING)
2293     {
2294         SetLastError(NTE_BAD_DATA);
2295         return FALSE;
2296     }
2297
2298     dwMax=*pdwDataLen;
2299
2300     if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_BLOCK) {
2301         for (i=0, in=pbData; i<*pdwDataLen; i+=pCryptKey->dwBlockLen, in+=pCryptKey->dwBlockLen) {
2302             switch (pCryptKey->dwMode) {
2303                 case CRYPT_MODE_ECB:
2304                     encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out, 
2305                                        RSAENH_DECRYPT);
2306                     break;
2307                 
2308                 case CRYPT_MODE_CBC:
2309                     encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out, 
2310                                        RSAENH_DECRYPT);
2311                     for (j=0; j<pCryptKey->dwBlockLen; j++) out[j] ^= pCryptKey->abChainVector[j];
2312                     memcpy(pCryptKey->abChainVector, in, pCryptKey->dwBlockLen);
2313                     break;
2314
2315                 case CRYPT_MODE_CFB:
2316                     for (j=0; j<pCryptKey->dwBlockLen; j++) {
2317                         encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, 
2318                                            pCryptKey->abChainVector, o, RSAENH_ENCRYPT);
2319                         out[j] = in[j] ^ o[0];
2320                         for (k=0; k<pCryptKey->dwBlockLen-1; k++) 
2321                             pCryptKey->abChainVector[k] = pCryptKey->abChainVector[k+1];
2322                         pCryptKey->abChainVector[k] = in[j];
2323                     }
2324                     break;
2325                     
2326                 default:
2327                     SetLastError(NTE_BAD_ALGID);
2328                     return FALSE;
2329             }
2330             memcpy(in, out, pCryptKey->dwBlockLen);
2331         }
2332         if (Final) {
2333             if (pbData[*pdwDataLen-1] &&
2334              pbData[*pdwDataLen-1] <= pCryptKey->dwBlockLen &&
2335              pbData[*pdwDataLen-1] <= *pdwDataLen) {
2336                 BOOL padOkay = TRUE;
2337
2338                 /* check that every bad byte has the same value */
2339                 for (i = 1; padOkay && i < pbData[*pdwDataLen-1]; i++)
2340                     if (pbData[*pdwDataLen - i - 1] != pbData[*pdwDataLen - 1])
2341                         padOkay = FALSE;
2342                 if (padOkay)
2343                     *pdwDataLen -= pbData[*pdwDataLen-1];
2344                 else {
2345                     SetLastError(NTE_BAD_DATA);
2346                     return FALSE;
2347                 }
2348             }
2349             else {
2350                 SetLastError(NTE_BAD_DATA);
2351                 return FALSE;
2352             }
2353         }
2354
2355     } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_STREAM) {
2356         encrypt_stream_impl(pCryptKey->aiAlgid, &pCryptKey->context, pbData, *pdwDataLen);
2357     } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_RSA) {
2358         if (pCryptKey->aiAlgid == CALG_RSA_SIGN) {
2359             SetLastError(NTE_BAD_KEY);
2360             return FALSE;
2361         }
2362         encrypt_block_impl(pCryptKey->aiAlgid, PK_PRIVATE, &pCryptKey->context, pbData, pbData, RSAENH_DECRYPT);
2363         if (!unpad_data(pbData, pCryptKey->dwBlockLen, pbData, pdwDataLen, dwFlags)) return FALSE;
2364         Final = TRUE;
2365     } else {
2366         SetLastError(NTE_BAD_TYPE);
2367         return FALSE;
2368     } 
2369     
2370     if (Final) setup_key(pCryptKey);
2371
2372     if (is_valid_handle(&handle_table, hHash, RSAENH_MAGIC_HASH)) {
2373         if (*pdwDataLen>dwMax ||
2374             !RSAENH_CPHashData(hProv, hHash, pbData, *pdwDataLen, 0)) return FALSE;
2375     }
2376     
2377     return TRUE;
2378 }
2379
2380 static BOOL crypt_export_simple(CRYPTKEY *pCryptKey, CRYPTKEY *pPubKey,
2381     DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2382 {
2383     BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2384     ALG_ID *pAlgid = (ALG_ID*)(pBlobHeader+1);
2385     DWORD dwDataLen;
2386
2387     if (!(GET_ALG_CLASS(pCryptKey->aiAlgid)&(ALG_CLASS_DATA_ENCRYPT|ALG_CLASS_MSG_ENCRYPT))) {
2388         SetLastError(NTE_BAD_KEY); /* FIXME: error code? */
2389         return FALSE;
2390     }
2391
2392     dwDataLen = sizeof(BLOBHEADER) + sizeof(ALG_ID) + pPubKey->dwBlockLen;
2393     if (pbData) {
2394         if (*pdwDataLen < dwDataLen) {
2395             SetLastError(ERROR_MORE_DATA);
2396             *pdwDataLen = dwDataLen;
2397             return FALSE;
2398         }
2399
2400         pBlobHeader->bType = SIMPLEBLOB;
2401         pBlobHeader->bVersion = CUR_BLOB_VERSION;
2402         pBlobHeader->reserved = 0;
2403         pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2404
2405         *pAlgid = pPubKey->aiAlgid;
2406
2407         if (!pad_data(pCryptKey->abKeyValue, pCryptKey->dwKeyLen, (BYTE*)(pAlgid+1),
2408                       pPubKey->dwBlockLen, dwFlags))
2409         {
2410             return FALSE;
2411         }
2412
2413         encrypt_block_impl(pPubKey->aiAlgid, PK_PUBLIC, &pPubKey->context, (BYTE*)(pAlgid+1),
2414                            (BYTE*)(pAlgid+1), RSAENH_ENCRYPT);
2415     }
2416     *pdwDataLen = dwDataLen;
2417     return TRUE;
2418 }
2419
2420 static BOOL crypt_export_public_key(CRYPTKEY *pCryptKey, BYTE *pbData,
2421     DWORD *pdwDataLen)
2422 {
2423     BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2424     RSAPUBKEY *pRSAPubKey = (RSAPUBKEY*)(pBlobHeader+1);
2425     DWORD dwDataLen;
2426
2427     if ((pCryptKey->aiAlgid != CALG_RSA_KEYX) && (pCryptKey->aiAlgid != CALG_RSA_SIGN)) {
2428         SetLastError(NTE_BAD_KEY);
2429         return FALSE;
2430     }
2431
2432     dwDataLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) + pCryptKey->dwKeyLen;
2433     if (pbData) {
2434         if (*pdwDataLen < dwDataLen) {
2435             SetLastError(ERROR_MORE_DATA);
2436             *pdwDataLen = dwDataLen;
2437             return FALSE;
2438         }
2439
2440         pBlobHeader->bType = PUBLICKEYBLOB;
2441         pBlobHeader->bVersion = CUR_BLOB_VERSION;
2442         pBlobHeader->reserved = 0;
2443         pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2444
2445         pRSAPubKey->magic = RSAENH_MAGIC_RSA1;
2446         pRSAPubKey->bitlen = pCryptKey->dwKeyLen << 3;
2447
2448         export_public_key_impl((BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2449                                pCryptKey->dwKeyLen, &pRSAPubKey->pubexp);
2450     }
2451     *pdwDataLen = dwDataLen;
2452     return TRUE;
2453 }
2454
2455 static BOOL crypt_export_private_key(CRYPTKEY *pCryptKey, BOOL force,
2456     BYTE *pbData, DWORD *pdwDataLen)
2457 {
2458     BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2459     RSAPUBKEY *pRSAPubKey = (RSAPUBKEY*)(pBlobHeader+1);
2460     DWORD dwDataLen;
2461
2462     if ((pCryptKey->aiAlgid != CALG_RSA_KEYX) && (pCryptKey->aiAlgid != CALG_RSA_SIGN)) {
2463         SetLastError(NTE_BAD_KEY);
2464         return FALSE;
2465     }
2466     if (!force && !(pCryptKey->dwPermissions & CRYPT_EXPORT))
2467     {
2468         SetLastError(NTE_BAD_KEY_STATE);
2469         return FALSE;
2470     }
2471
2472     dwDataLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) +
2473                 2 * pCryptKey->dwKeyLen + 5 * ((pCryptKey->dwKeyLen + 1) >> 1);
2474     if (pbData) {
2475         if (*pdwDataLen < dwDataLen) {
2476             SetLastError(ERROR_MORE_DATA);
2477             *pdwDataLen = dwDataLen;
2478             return FALSE;
2479         }
2480
2481         pBlobHeader->bType = PRIVATEKEYBLOB;
2482         pBlobHeader->bVersion = CUR_BLOB_VERSION;
2483         pBlobHeader->reserved = 0;
2484         pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2485
2486         pRSAPubKey->magic = RSAENH_MAGIC_RSA2;
2487         pRSAPubKey->bitlen = pCryptKey->dwKeyLen << 3;
2488
2489         export_private_key_impl((BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2490                                 pCryptKey->dwKeyLen, &pRSAPubKey->pubexp);
2491     }
2492     *pdwDataLen = dwDataLen;
2493     return TRUE;
2494 }
2495
2496 static BOOL crypt_export_plaintext_key(CRYPTKEY *pCryptKey, BYTE *pbData,
2497     DWORD *pdwDataLen)
2498 {
2499     BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2500     DWORD *pKeyLen = (DWORD*)(pBlobHeader+1);
2501     BYTE *pbKey = (BYTE*)(pKeyLen+1);
2502     DWORD dwDataLen;
2503
2504     dwDataLen = sizeof(BLOBHEADER) + sizeof(DWORD) + pCryptKey->dwKeyLen;
2505     if (pbData) {
2506         if (*pdwDataLen < dwDataLen) {
2507             SetLastError(ERROR_MORE_DATA);
2508             *pdwDataLen = dwDataLen;
2509             return FALSE;
2510         }
2511
2512         pBlobHeader->bType = PLAINTEXTKEYBLOB;
2513         pBlobHeader->bVersion = CUR_BLOB_VERSION;
2514         pBlobHeader->reserved = 0;
2515         pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2516
2517         *pKeyLen = pCryptKey->dwKeyLen;
2518         memcpy(pbKey, &pCryptKey->abKeyValue, pCryptKey->dwKeyLen);
2519     }
2520     *pdwDataLen = dwDataLen;
2521     return TRUE;
2522 }
2523 /******************************************************************************
2524  * crypt_export_key [Internal]
2525  *
2526  * Export a key into a binary large object (BLOB).  Called by CPExportKey and
2527  * by store_key_pair.
2528  *
2529  * PARAMS
2530  *  pCryptKey  [I]   Key to be exported.
2531  *  hPubKey    [I]   Key used to encrypt sensitive BLOB data.
2532  *  dwBlobType [I]   SIMPLEBLOB, PUBLICKEYBLOB or PRIVATEKEYBLOB.
2533  *  dwFlags    [I]   Currently none defined.
2534  *  force      [I]   If TRUE, the key is written no matter what the key's
2535  *                   permissions are.  Otherwise the key's permissions are
2536  *                   checked before exporting.
2537  *  pbData     [O]   Pointer to a buffer where the BLOB will be written to.
2538  *  pdwDataLen [I/O] I: Size of buffer at pbData, O: Size of BLOB
2539  *
2540  * RETURNS
2541  *  Success: TRUE.
2542  *  Failure: FALSE.
2543  */
2544 static BOOL crypt_export_key(CRYPTKEY *pCryptKey, HCRYPTKEY hPubKey,
2545                              DWORD dwBlobType, DWORD dwFlags, BOOL force,
2546                              BYTE *pbData, DWORD *pdwDataLen)
2547 {
2548     CRYPTKEY *pPubKey;
2549     
2550     if (dwFlags & CRYPT_SSL2_FALLBACK) {
2551         if (pCryptKey->aiAlgid != CALG_SSL2_MASTER) {
2552             SetLastError(NTE_BAD_KEY);
2553             return FALSE;
2554         }
2555     }
2556     
2557     switch ((BYTE)dwBlobType)
2558     {
2559         case SIMPLEBLOB:
2560             if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pPubKey)){
2561                 SetLastError(NTE_BAD_PUBLIC_KEY); /* FIXME: error_code? */
2562                 return FALSE;
2563             }
2564             return crypt_export_simple(pCryptKey, pPubKey, dwFlags, pbData,
2565                                        pdwDataLen);
2566             
2567         case PUBLICKEYBLOB:
2568             if (is_valid_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY)) {
2569                 SetLastError(NTE_BAD_KEY); /* FIXME: error code? */
2570                 return FALSE;
2571             }
2572
2573             return crypt_export_public_key(pCryptKey, pbData, pdwDataLen);
2574
2575         case PRIVATEKEYBLOB:
2576             return crypt_export_private_key(pCryptKey, force, pbData, pdwDataLen);
2577
2578         case PLAINTEXTKEYBLOB:
2579             return crypt_export_plaintext_key(pCryptKey, pbData, pdwDataLen);
2580             
2581         default:
2582             SetLastError(NTE_BAD_TYPE); /* FIXME: error code? */
2583             return FALSE;
2584     }
2585 }
2586
2587 /******************************************************************************
2588  * CPExportKey (RSAENH.@)
2589  *
2590  * Export a key into a binary large object (BLOB).
2591  *
2592  * PARAMS
2593  *  hProv      [I]   Key container from which a key is to be exported.
2594  *  hKey       [I]   Key to be exported.
2595  *  hPubKey    [I]   Key used to encrypt sensitive BLOB data.
2596  *  dwBlobType [I]   SIMPLEBLOB, PUBLICKEYBLOB or PRIVATEKEYBLOB.
2597  *  dwFlags    [I]   Currently none defined.
2598  *  pbData     [O]   Pointer to a buffer where the BLOB will be written to.
2599  *  pdwDataLen [I/O] I: Size of buffer at pbData, O: Size of BLOB
2600  *
2601  * RETURNS
2602  *  Success: TRUE.
2603  *  Failure: FALSE.
2604  */
2605 BOOL WINAPI RSAENH_CPExportKey(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTKEY hPubKey,
2606                                DWORD dwBlobType, DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2607 {
2608     CRYPTKEY *pCryptKey;
2609
2610     TRACE("(hProv=%08lx, hKey=%08lx, hPubKey=%08lx, dwBlobType=%08x, dwFlags=%08x, pbData=%p,"
2611           "pdwDataLen=%p)\n", hProv, hKey, hPubKey, dwBlobType, dwFlags, pbData, pdwDataLen);
2612
2613     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2614     {
2615         SetLastError(NTE_BAD_UID);
2616         return FALSE;
2617     }
2618
2619     if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2620     {
2621         SetLastError(NTE_BAD_KEY);
2622         return FALSE;
2623     }
2624
2625     return crypt_export_key(pCryptKey, hPubKey, dwBlobType, dwFlags, FALSE,
2626         pbData, pdwDataLen);
2627 }
2628
2629 /******************************************************************************
2630  * release_and_install_key [Internal]
2631  *
2632  * Release an existing key, if present, and replaces it with a new one.
2633  *
2634  * PARAMS
2635  *  hProv     [I] Key container into which the key is to be imported.
2636  *  src       [I] Key which will replace *dest
2637  *  dest      [I] Points to key to be released and replaced with src
2638  *  fStoreKey [I] If TRUE, the newly installed key is stored to the registry.
2639  */
2640 static void release_and_install_key(HCRYPTPROV hProv, HCRYPTKEY src,
2641                                     HCRYPTKEY *dest, DWORD fStoreKey)
2642 {
2643     RSAENH_CPDestroyKey(hProv, *dest);
2644     copy_handle(&handle_table, src, RSAENH_MAGIC_KEY, dest);
2645     if (fStoreKey)
2646     {
2647         KEYCONTAINER *pKeyContainer;
2648
2649         if (lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER,
2650                           (OBJECTHDR**)&pKeyContainer))
2651         {
2652             store_key_container_keys(pKeyContainer);
2653             store_key_container_permissions(pKeyContainer);
2654         }
2655     }
2656 }
2657
2658 /******************************************************************************
2659  * import_private_key [Internal]
2660  *
2661  * Import a BLOB'ed private key into a key container.
2662  *
2663  * PARAMS
2664  *  hProv     [I] Key container into which the private key is to be imported.
2665  *  pbData    [I] Pointer to a buffer which holds the private key BLOB.
2666  *  dwDataLen [I] Length of data in buffer at pbData.
2667  *  dwFlags   [I] One of:
2668  *                CRYPT_EXPORTABLE: the imported key is marked exportable
2669  *  fStoreKey [I] If TRUE, the imported key is stored to the registry.
2670  *  phKey     [O] Handle to the imported key.
2671  *
2672  *
2673  * NOTES
2674  *  Assumes the caller has already checked the BLOBHEADER at pbData to ensure
2675  *  it's a PRIVATEKEYBLOB.
2676  *
2677  * RETURNS
2678  *  Success: TRUE.
2679  *  Failure: FALSE.
2680  */
2681 static BOOL import_private_key(HCRYPTPROV hProv, CONST BYTE *pbData, DWORD dwDataLen,
2682                                DWORD dwFlags, BOOL fStoreKey, HCRYPTKEY *phKey)
2683 {
2684     KEYCONTAINER *pKeyContainer;
2685     CRYPTKEY *pCryptKey;
2686     CONST BLOBHEADER *pBlobHeader = (CONST BLOBHEADER*)pbData;
2687     CONST RSAPUBKEY *pRSAPubKey = (CONST RSAPUBKEY*)(pBlobHeader+1);
2688     BOOL ret;
2689
2690     if (!lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER,
2691                        (OBJECTHDR**)&pKeyContainer))
2692     {
2693         SetLastError(NTE_BAD_UID);
2694         return FALSE;
2695     }
2696
2697     if ((dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY)) ||
2698         (pRSAPubKey->magic != RSAENH_MAGIC_RSA2) ||
2699         (dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) +
2700             (2 * pRSAPubKey->bitlen >> 3) + (5 * ((pRSAPubKey->bitlen+8)>>4))))
2701     {
2702         SetLastError(NTE_BAD_DATA);
2703         return FALSE;
2704     }
2705
2706     *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, MAKELONG(0,pRSAPubKey->bitlen), &pCryptKey);
2707     if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
2708     setup_key(pCryptKey);
2709     ret = import_private_key_impl((CONST BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2710                                    pRSAPubKey->bitlen/8, pRSAPubKey->pubexp);
2711     if (ret) {
2712         if (dwFlags & CRYPT_EXPORTABLE)
2713             pCryptKey->dwPermissions |= CRYPT_EXPORT;
2714         switch (pBlobHeader->aiKeyAlg)
2715         {
2716         case AT_SIGNATURE:
2717         case CALG_RSA_SIGN:
2718             TRACE("installing signing key\n");
2719             release_and_install_key(hProv, *phKey, &pKeyContainer->hSignatureKeyPair,
2720                                     fStoreKey);
2721             break;
2722         case AT_KEYEXCHANGE:
2723         case CALG_RSA_KEYX:
2724             TRACE("installing key exchange key\n");
2725             release_and_install_key(hProv, *phKey, &pKeyContainer->hKeyExchangeKeyPair,
2726                                     fStoreKey);
2727             break;
2728         }
2729     }
2730     return ret;
2731 }
2732
2733 /******************************************************************************
2734  * import_public_key [Internal]
2735  *
2736  * Import a BLOB'ed public key into a key container.
2737  *
2738  * PARAMS
2739  *  hProv     [I] Key container into which the public key is to be imported.
2740  *  pbData    [I] Pointer to a buffer which holds the public key BLOB.
2741  *  dwDataLen [I] Length of data in buffer at pbData.
2742  *  dwFlags   [I] One of:
2743  *                CRYPT_EXPORTABLE: the imported key is marked exportable
2744  *  fStoreKey [I] If TRUE, the imported key is stored to the registry.
2745  *  phKey     [O] Handle to the imported key.
2746  *
2747  *
2748  * NOTES
2749  *  Assumes the caller has already checked the BLOBHEADER at pbData to ensure
2750  *  it's a PUBLICKEYBLOB.
2751  *
2752  * RETURNS
2753  *  Success: TRUE.
2754  *  Failure: FALSE.
2755  */
2756 static BOOL import_public_key(HCRYPTPROV hProv, CONST BYTE *pbData, DWORD dwDataLen,
2757                               DWORD dwFlags, BOOL fStoreKey, HCRYPTKEY *phKey)
2758 {
2759     KEYCONTAINER *pKeyContainer;
2760     CRYPTKEY *pCryptKey;
2761     CONST BLOBHEADER *pBlobHeader = (CONST BLOBHEADER*)pbData;
2762     CONST RSAPUBKEY *pRSAPubKey = (CONST RSAPUBKEY*)(pBlobHeader+1);
2763     ALG_ID algID;
2764     BOOL ret;
2765
2766     if (!lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER,
2767                        (OBJECTHDR**)&pKeyContainer))
2768     {
2769         SetLastError(NTE_BAD_UID);
2770         return FALSE;
2771     }
2772
2773     if ((dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY)) ||
2774         (pRSAPubKey->magic != RSAENH_MAGIC_RSA1) ||
2775         (dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) + (pRSAPubKey->bitlen >> 3)))
2776     {
2777         SetLastError(NTE_BAD_DATA);
2778         return FALSE;
2779     }
2780
2781     /* Since this is a public key blob, only the public key is
2782      * available, so only signature verification is possible.
2783      */
2784     algID = pBlobHeader->aiKeyAlg;
2785     *phKey = new_key(hProv, algID, MAKELONG(0,pRSAPubKey->bitlen), &pCryptKey);
2786     if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
2787     setup_key(pCryptKey);
2788     ret = import_public_key_impl((CONST BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2789                                   pRSAPubKey->bitlen >> 3, pRSAPubKey->pubexp);
2790     if (ret) {
2791         if (dwFlags & CRYPT_EXPORTABLE)
2792             pCryptKey->dwPermissions |= CRYPT_EXPORT;
2793         switch (pBlobHeader->aiKeyAlg)
2794         {
2795         case AT_KEYEXCHANGE:
2796         case CALG_RSA_KEYX:
2797             TRACE("installing public key\n");
2798             release_and_install_key(hProv, *phKey, &pKeyContainer->hKeyExchangeKeyPair,
2799                                     fStoreKey);
2800             break;
2801         }
2802     }
2803     return ret;
2804 }
2805
2806 /******************************************************************************
2807  * import_symmetric_key [Internal]
2808  *
2809  * Import a BLOB'ed symmetric key into a key container.
2810  *
2811  * PARAMS
2812  *  hProv     [I] Key container into which the symmetric key is to be imported.
2813  *  pbData    [I] Pointer to a buffer which holds the symmetric key BLOB.
2814  *  dwDataLen [I] Length of data in buffer at pbData.
2815  *  hPubKey   [I] Key used to decrypt sensitive BLOB data.
2816  *  dwFlags   [I] One of:
2817  *                CRYPT_EXPORTABLE: the imported key is marked exportable
2818  *  phKey     [O] Handle to the imported key.
2819  *
2820  *
2821  * NOTES
2822  *  Assumes the caller has already checked the BLOBHEADER at pbData to ensure
2823  *  it's a SIMPLEBLOB.
2824  *
2825  * RETURNS
2826  *  Success: TRUE.
2827  *  Failure: FALSE.
2828  */
2829 static BOOL import_symmetric_key(HCRYPTPROV hProv, CONST BYTE *pbData,
2830                                  DWORD dwDataLen, HCRYPTKEY hPubKey,
2831                                  DWORD dwFlags, HCRYPTKEY *phKey)
2832 {
2833     CRYPTKEY *pCryptKey, *pPubKey;
2834     CONST BLOBHEADER *pBlobHeader = (CONST BLOBHEADER*)pbData;
2835     CONST ALG_ID *pAlgid = (CONST ALG_ID*)(pBlobHeader+1);
2836     CONST BYTE *pbKeyStream = (CONST BYTE*)(pAlgid + 1);
2837     BYTE *pbDecrypted;
2838     DWORD dwKeyLen;
2839
2840     if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pPubKey) ||
2841         pPubKey->aiAlgid != CALG_RSA_KEYX)
2842     {
2843         SetLastError(NTE_BAD_PUBLIC_KEY); /* FIXME: error code? */
2844         return FALSE;
2845     }
2846
2847     if (dwDataLen < sizeof(BLOBHEADER)+sizeof(ALG_ID)+pPubKey->dwBlockLen)
2848     {
2849         SetLastError(NTE_BAD_DATA); /* FIXME: error code */
2850         return FALSE;
2851     }
2852
2853     pbDecrypted = HeapAlloc(GetProcessHeap(), 0, pPubKey->dwBlockLen);
2854     if (!pbDecrypted) return FALSE;
2855     encrypt_block_impl(pPubKey->aiAlgid, PK_PRIVATE, &pPubKey->context, pbKeyStream, pbDecrypted,
2856                        RSAENH_DECRYPT);
2857
2858     dwKeyLen = RSAENH_MAX_KEY_SIZE;
2859     if (!unpad_data(pbDecrypted, pPubKey->dwBlockLen, pbDecrypted, &dwKeyLen, dwFlags)) {
2860         HeapFree(GetProcessHeap(), 0, pbDecrypted);
2861         return FALSE;
2862     }
2863
2864     *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, dwKeyLen<<19, &pCryptKey);
2865     if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
2866     {
2867         HeapFree(GetProcessHeap(), 0, pbDecrypted);
2868         return FALSE;
2869     }
2870     memcpy(pCryptKey->abKeyValue, pbDecrypted, dwKeyLen);
2871     HeapFree(GetProcessHeap(), 0, pbDecrypted);
2872     setup_key(pCryptKey);
2873     if (dwFlags & CRYPT_EXPORTABLE)
2874         pCryptKey->dwPermissions |= CRYPT_EXPORT;
2875     return TRUE;
2876 }
2877
2878 /******************************************************************************
2879  * import_plaintext_key [Internal]
2880  *
2881  * Import a plaintext key into a key container.
2882  *
2883  * PARAMS
2884  *  hProv     [I] Key container into which the symmetric key is to be imported.
2885  *  pbData    [I] Pointer to a buffer which holds the plaintext key BLOB.
2886  *  dwDataLen [I] Length of data in buffer at pbData.
2887  *  dwFlags   [I] One of:
2888  *                CRYPT_EXPORTABLE: the imported key is marked exportable
2889  *  phKey     [O] Handle to the imported key.
2890  *
2891  *
2892  * NOTES
2893  *  Assumes the caller has already checked the BLOBHEADER at pbData to ensure
2894  *  it's a PLAINTEXTKEYBLOB.
2895  *
2896  * RETURNS
2897  *  Success: TRUE.
2898  *  Failure: FALSE.
2899  */
2900 static BOOL import_plaintext_key(HCRYPTPROV hProv, CONST BYTE *pbData,
2901                                  DWORD dwDataLen, DWORD dwFlags,
2902                                  HCRYPTKEY *phKey)
2903 {
2904     CRYPTKEY *pCryptKey;
2905     CONST BLOBHEADER *pBlobHeader = (CONST BLOBHEADER*)pbData;
2906     CONST DWORD *pKeyLen = (CONST DWORD *)(pBlobHeader + 1);
2907     CONST BYTE *pbKeyStream = (CONST BYTE*)(pKeyLen + 1);
2908
2909     if (dwDataLen < sizeof(BLOBHEADER)+sizeof(DWORD)+*pKeyLen)
2910     {
2911         SetLastError(NTE_BAD_DATA); /* FIXME: error code */
2912         return FALSE;
2913     }
2914
2915     *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, *pKeyLen<<19, &pCryptKey);
2916     if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
2917         return FALSE;
2918     memcpy(pCryptKey->abKeyValue, pbKeyStream, *pKeyLen);
2919     setup_key(pCryptKey);
2920     if (dwFlags & CRYPT_EXPORTABLE)
2921         pCryptKey->dwPermissions |= CRYPT_EXPORT;
2922     return TRUE;
2923 }
2924
2925 /******************************************************************************
2926  * import_key [Internal]
2927  *
2928  * Import a BLOB'ed key into a key container, optionally storing the key's
2929  * value to the registry.
2930  *
2931  * PARAMS
2932  *  hProv     [I] Key container into which the key is to be imported.
2933  *  pbData    [I] Pointer to a buffer which holds the BLOB.
2934  *  dwDataLen [I] Length of data in buffer at pbData.
2935  *  hPubKey   [I] Key used to decrypt sensitive BLOB data.
2936  *  dwFlags   [I] One of:
2937  *                CRYPT_EXPORTABLE: the imported key is marked exportable
2938  *  fStoreKey [I] If TRUE, the imported key is stored to the registry.
2939  *  phKey     [O] Handle to the imported key.
2940  *
2941  * RETURNS
2942  *  Success: TRUE.
2943  *  Failure: FALSE.
2944  */
2945 static BOOL import_key(HCRYPTPROV hProv, CONST BYTE *pbData, DWORD dwDataLen,
2946                        HCRYPTKEY hPubKey, DWORD dwFlags, BOOL fStoreKey,
2947                        HCRYPTKEY *phKey)
2948 {
2949     KEYCONTAINER *pKeyContainer;
2950     CONST BLOBHEADER *pBlobHeader = (CONST BLOBHEADER*)pbData;
2951
2952     if (!lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER,
2953                        (OBJECTHDR**)&pKeyContainer)) 
2954     {
2955         SetLastError(NTE_BAD_UID);
2956         return FALSE;
2957     }
2958
2959     if (dwDataLen < sizeof(BLOBHEADER) || 
2960         pBlobHeader->bVersion != CUR_BLOB_VERSION ||
2961         pBlobHeader->reserved != 0) 
2962     {
2963         TRACE("bVersion = %d, reserved = %d\n", pBlobHeader->bVersion,
2964               pBlobHeader->reserved);
2965         SetLastError(NTE_BAD_DATA);
2966         return FALSE;
2967     }
2968
2969     /* If this is a verify-only context, the key is not persisted regardless of
2970      * fStoreKey's original value.
2971      */
2972     fStoreKey = fStoreKey && !(dwFlags & CRYPT_VERIFYCONTEXT);
2973     TRACE("blob type: %x\n", pBlobHeader->bType);
2974     switch (pBlobHeader->bType)
2975     {
2976         case PRIVATEKEYBLOB:    
2977             return import_private_key(hProv, pbData, dwDataLen, dwFlags,
2978                                       fStoreKey, phKey);
2979                 
2980         case PUBLICKEYBLOB:
2981             return import_public_key(hProv, pbData, dwDataLen, dwFlags,
2982                                      fStoreKey, phKey);
2983                 
2984         case SIMPLEBLOB:
2985             return import_symmetric_key(hProv, pbData, dwDataLen, hPubKey,
2986                                         dwFlags, phKey);
2987
2988         case PLAINTEXTKEYBLOB:
2989             return import_plaintext_key(hProv, pbData, dwDataLen, dwFlags,
2990                                         phKey);
2991
2992         default:
2993             SetLastError(NTE_BAD_TYPE); /* FIXME: error code? */
2994             return FALSE;
2995     }
2996 }
2997
2998 /******************************************************************************
2999  * CPImportKey (RSAENH.@)
3000  *
3001  * Import a BLOB'ed key into a key container.
3002  *
3003  * PARAMS
3004  *  hProv     [I] Key container into which the key is to be imported.
3005  *  pbData    [I] Pointer to a buffer which holds the BLOB.
3006  *  dwDataLen [I] Length of data in buffer at pbData.
3007  *  hPubKey   [I] Key used to decrypt sensitive BLOB data.
3008  *  dwFlags   [I] One of:
3009  *                CRYPT_EXPORTABLE: the imported key is marked exportable
3010  *  phKey     [O] Handle to the imported key.
3011  *
3012  * RETURNS
3013  *  Success: TRUE.
3014  *  Failure: FALSE.
3015  */
3016 BOOL WINAPI RSAENH_CPImportKey(HCRYPTPROV hProv, CONST BYTE *pbData, DWORD dwDataLen,
3017                                HCRYPTKEY hPubKey, DWORD dwFlags, HCRYPTKEY *phKey)
3018 {
3019     TRACE("(hProv=%08lx, pbData=%p, dwDataLen=%d, hPubKey=%08lx, dwFlags=%08x, phKey=%p)\n",
3020         hProv, pbData, dwDataLen, hPubKey, dwFlags, phKey);
3021
3022     if (dwFlags & CRYPT_IPSEC_HMAC_KEY)
3023     {
3024         FIXME("unimplemented for CRYPT_IPSEC_HMAC_KEY\n");
3025         SetLastError(NTE_BAD_FLAGS);
3026         return FALSE;
3027     }
3028     return import_key(hProv, pbData, dwDataLen, hPubKey, dwFlags, TRUE, phKey);
3029 }
3030
3031 /******************************************************************************
3032  * CPGenKey (RSAENH.@)
3033  *
3034  * Generate a key in the key container
3035  *
3036  * PARAMS
3037  *  hProv   [I] Key container for which a key is to be generated.
3038  *  Algid   [I] Crypto algorithm identifier for the key to be generated.
3039  *  dwFlags [I] Upper 16 bits: Binary length of key. Lower 16 bits: Flags. See Notes
3040  *  phKey   [O] Handle to the generated key.
3041  *
3042  * RETURNS
3043  *  Success: TRUE.
3044  *  Failure: FALSE.
3045  *
3046  * FIXME
3047  *  Flags currently not considered.
3048  *
3049  * NOTES
3050  *  Private key-exchange- and signature-keys can be generated with Algid AT_KEYEXCHANGE
3051  *  and AT_SIGNATURE values.
3052  */
3053 BOOL WINAPI RSAENH_CPGenKey(HCRYPTPROV hProv, ALG_ID Algid, DWORD dwFlags, HCRYPTKEY *phKey)
3054 {
3055     KEYCONTAINER *pKeyContainer;
3056     CRYPTKEY *pCryptKey;
3057
3058     TRACE("(hProv=%08lx, aiAlgid=%d, dwFlags=%08x, phKey=%p)\n", hProv, Algid, dwFlags, phKey);
3059
3060     if (!lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER,
3061                        (OBJECTHDR**)&pKeyContainer)) 
3062     {
3063         /* MSDN: hProv not containing valid context handle */
3064         SetLastError(NTE_BAD_UID);
3065         return FALSE;
3066     }
3067     
3068     switch (Algid)
3069     {
3070         case AT_SIGNATURE:
3071         case CALG_RSA_SIGN:
3072             *phKey = new_key(hProv, CALG_RSA_SIGN, dwFlags, &pCryptKey);
3073             if (pCryptKey) { 
3074                 new_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen);
3075                 setup_key(pCryptKey);
3076                 release_and_install_key(hProv, *phKey,
3077                                         &pKeyContainer->hSignatureKeyPair,
3078                                         FALSE);
3079             }
3080             break;
3081
3082         case AT_KEYEXCHANGE:
3083         case CALG_RSA_KEYX:
3084             *phKey = new_key(hProv, CALG_RSA_KEYX, dwFlags, &pCryptKey);
3085             if (pCryptKey) { 
3086                 new_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen);
3087                 setup_key(pCryptKey);
3088                 release_and_install_key(hProv, *phKey,
3089                                         &pKeyContainer->hKeyExchangeKeyPair,
3090                                         FALSE);
3091             }
3092             break;
3093             
3094         case CALG_RC2:
3095         case CALG_RC4:
3096         case CALG_DES:
3097         case CALG_3DES_112:
3098         case CALG_3DES:
3099         case CALG_AES:
3100         case CALG_AES_128:
3101         case CALG_AES_192:
3102         case CALG_AES_256:
3103         case CALG_PCT1_MASTER:
3104         case CALG_SSL2_MASTER:
3105         case CALG_SSL3_MASTER:
3106         case CALG_TLS1_MASTER:
3107             *phKey = new_key(hProv, Algid, dwFlags, &pCryptKey);
3108             if (pCryptKey) {
3109                 gen_rand_impl(pCryptKey->abKeyValue, RSAENH_MAX_KEY_SIZE);
3110                 switch (Algid) {
3111                     case CALG_SSL3_MASTER:
3112                         pCryptKey->abKeyValue[0] = RSAENH_SSL3_VERSION_MAJOR;
3113                         pCryptKey->abKeyValue[1] = RSAENH_SSL3_VERSION_MINOR;
3114                         break;
3115
3116                     case CALG_TLS1_MASTER:
3117                         pCryptKey->abKeyValue[0] = RSAENH_TLS1_VERSION_MAJOR;
3118                         pCryptKey->abKeyValue[1] = RSAENH_TLS1_VERSION_MINOR;
3119                         break;
3120                 }
3121                 setup_key(pCryptKey);
3122             }
3123             break;
3124             
3125         default:
3126             /* MSDN: Algorithm not supported specified by Algid */
3127             SetLastError(NTE_BAD_ALGID);
3128             return FALSE;
3129     }
3130             
3131     return *phKey != (HCRYPTKEY)INVALID_HANDLE_VALUE;
3132 }
3133
3134 /******************************************************************************
3135  * CPGenRandom (RSAENH.@)
3136  *
3137  * Generate a random byte stream.
3138  *
3139  * PARAMS
3140  *  hProv    [I] Key container that is used to generate random bytes.
3141  *  dwLen    [I] Specifies the number of requested random data bytes.
3142  *  pbBuffer [O] Random bytes will be stored here.
3143  *
3144  * RETURNS
3145  *  Success: TRUE
3146  *  Failure: FALSE
3147  */
3148 BOOL WINAPI RSAENH_CPGenRandom(HCRYPTPROV hProv, DWORD dwLen, BYTE *pbBuffer)
3149 {
3150     TRACE("(hProv=%08lx, dwLen=%d, pbBuffer=%p)\n", hProv, dwLen, pbBuffer);
3151     
3152     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3153     {
3154         /* MSDN: hProv not containing valid context handle */
3155         SetLastError(NTE_BAD_UID);
3156         return FALSE;
3157     }
3158
3159     return gen_rand_impl(pbBuffer, dwLen);
3160 }
3161
3162 /******************************************************************************
3163  * CPGetHashParam (RSAENH.@)
3164  *
3165  * Query parameters of an hash object.
3166  *
3167  * PARAMS
3168  *  hProv      [I]   The kea container, which the hash belongs to.
3169  *  hHash      [I]   The hash object that is to be queried.
3170  *  dwParam    [I]   Specifies the parameter that is to be queried.
3171  *  pbData     [I]   Pointer to the buffer where the parameter value will be stored.
3172  *  pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
3173  *  dwFlags    [I]   None currently defined.
3174  *
3175  * RETURNS
3176  *  Success: TRUE
3177  *  Failure: FALSE
3178  *
3179  * NOTES
3180  *  Valid dwParams are: HP_ALGID, HP_HASHSIZE, HP_HASHVALUE. The hash will be 
3181  *  finalized if HP_HASHVALUE is queried.
3182  */
3183 BOOL WINAPI RSAENH_CPGetHashParam(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwParam, BYTE *pbData, 
3184                                   DWORD *pdwDataLen, DWORD dwFlags) 
3185 {
3186     CRYPTHASH *pCryptHash;
3187         
3188     TRACE("(hProv=%08lx, hHash=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p, dwFlags=%08x)\n",
3189         hProv, hHash, dwParam, pbData, pdwDataLen, dwFlags);
3190     
3191     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3192     {
3193         SetLastError(NTE_BAD_UID);
3194         return FALSE;
3195     }
3196
3197     if (dwFlags)
3198     {
3199         SetLastError(NTE_BAD_FLAGS);
3200         return FALSE;
3201     }
3202     
3203     if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH,
3204                        (OBJECTHDR**)&pCryptHash))
3205     {
3206         SetLastError(NTE_BAD_HASH);
3207         return FALSE;
3208     }
3209
3210     if (!pdwDataLen)
3211     {
3212         SetLastError(ERROR_INVALID_PARAMETER);
3213         return FALSE;
3214     }
3215     
3216     switch (dwParam)
3217     {
3218         case HP_ALGID:
3219             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptHash->aiAlgid, 
3220                               sizeof(ALG_ID));
3221
3222         case HP_HASHSIZE:
3223             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptHash->dwHashSize, 
3224                               sizeof(DWORD));
3225
3226         case HP_HASHVAL:
3227             if (pCryptHash->aiAlgid == CALG_TLS1PRF) {
3228                 return tls1_prf(hProv, pCryptHash->hKey, &pCryptHash->tpPRFParams.blobLabel,
3229                                 &pCryptHash->tpPRFParams.blobSeed, pbData, *pdwDataLen);
3230             }
3231
3232             if ( pbData == NULL ) {
3233                 *pdwDataLen = pCryptHash->dwHashSize;
3234                 return TRUE;
3235             }
3236
3237             if (pbData && (pCryptHash->dwState != RSAENH_HASHSTATE_FINISHED))
3238             {
3239                 finalize_hash(pCryptHash);
3240                 pCryptHash->dwState = RSAENH_HASHSTATE_FINISHED;
3241             }
3242
3243             return copy_param(pbData, pdwDataLen, pCryptHash->abHashValue,
3244                               pCryptHash->dwHashSize);
3245
3246         default:
3247             SetLastError(NTE_BAD_TYPE);
3248             return FALSE;
3249     }
3250 }
3251
3252 /******************************************************************************
3253  * CPSetKeyParam (RSAENH.@)
3254  *
3255  * Set a parameter of a key object
3256  *
3257  * PARAMS
3258  *  hProv   [I] The key container to which the key belongs.
3259  *  hKey    [I] The key for which a parameter is to be set.
3260  *  dwParam [I] Parameter type. See Notes.
3261  *  pbData  [I] Pointer to the parameter value.
3262  *  dwFlags [I] Currently none defined.
3263  *
3264  * RETURNS
3265  *  Success: TRUE.
3266  *  Failure: FALSE.
3267  *
3268  * NOTES:
3269  *  Defined dwParam types are:
3270  *   - KP_MODE: Values MODE_CBC, MODE_ECB, MODE_CFB.
3271  *   - KP_MODE_BITS: Shift width for cipher feedback mode. (Currently ignored by MS CSP's)
3272  *   - KP_PERMISSIONS: Or'ed combination of CRYPT_ENCRYPT, CRYPT_DECRYPT, 
3273  *                     CRYPT_EXPORT, CRYPT_READ, CRYPT_WRITE, CRYPT_MAC
3274  *   - KP_IV: Initialization vector
3275  */
3276 BOOL WINAPI RSAENH_CPSetKeyParam(HCRYPTPROV hProv, HCRYPTKEY hKey, DWORD dwParam, BYTE *pbData, 
3277                                  DWORD dwFlags)
3278 {
3279     CRYPTKEY *pCryptKey;
3280
3281     TRACE("(hProv=%08lx, hKey=%08lx, dwParam=%08x, pbData=%p, dwFlags=%08x)\n", hProv, hKey,
3282           dwParam, pbData, dwFlags);
3283
3284     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3285     {
3286         SetLastError(NTE_BAD_UID);
3287         return FALSE;
3288     }
3289
3290     if (dwFlags) {
3291         SetLastError(NTE_BAD_FLAGS);
3292         return FALSE;
3293     }
3294     
3295     if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
3296     {
3297         SetLastError(NTE_BAD_KEY);
3298         return FALSE;
3299     }
3300     
3301     switch (dwParam) {
3302         case KP_PADDING:
3303             /* The MS providers only support PKCS5_PADDING */
3304             if (*(DWORD *)pbData != PKCS5_PADDING) {
3305                 SetLastError(NTE_BAD_DATA);
3306                 return FALSE;
3307             }
3308             return TRUE;
3309
3310         case KP_MODE:
3311             pCryptKey->dwMode = *(DWORD*)pbData;
3312             return TRUE;
3313
3314         case KP_MODE_BITS:
3315             pCryptKey->dwModeBits = *(DWORD*)pbData;
3316             return TRUE;
3317
3318         case KP_PERMISSIONS:
3319         {
3320             DWORD perms = *(DWORD *)pbData;
3321
3322             if ((perms & CRYPT_EXPORT) &&
3323                 !(pCryptKey->dwPermissions & CRYPT_EXPORT))
3324             {
3325                 SetLastError(NTE_BAD_DATA);
3326                 return FALSE;
3327             }
3328             else if (!(perms & CRYPT_EXPORT) &&
3329                 (pCryptKey->dwPermissions & CRYPT_EXPORT))
3330             {
3331                 /* Clearing the export permission appears to be ignored,
3332                  * see tests.
3333                  */
3334                 perms |= CRYPT_EXPORT;
3335             }
3336             pCryptKey->dwPermissions = perms;
3337             return TRUE;
3338         }
3339
3340         case KP_IV:
3341             memcpy(pCryptKey->abInitVector, pbData, pCryptKey->dwBlockLen);
3342             setup_key(pCryptKey);
3343             return TRUE;
3344
3345         case KP_SALT_EX:
3346         {
3347             CRYPT_INTEGER_BLOB *blob = (CRYPT_INTEGER_BLOB *)pbData;
3348
3349             /* salt length can't be greater than 184 bits = 24 bytes */
3350             if (blob->cbData > 24)
3351             {
3352                 SetLastError(NTE_BAD_DATA);
3353                 return FALSE;
3354             }
3355             memcpy(pCryptKey->abKeyValue + pCryptKey->dwKeyLen, blob->pbData,
3356                    blob->cbData);
3357             pCryptKey->dwSaltLen = blob->cbData;
3358             setup_key(pCryptKey);
3359             return TRUE;
3360         }
3361
3362         case KP_EFFECTIVE_KEYLEN:
3363             switch (pCryptKey->aiAlgid) {
3364                 case CALG_RC2:
3365                     if (!pbData)
3366                     {
3367                         SetLastError(ERROR_INVALID_PARAMETER);
3368                         return FALSE;
3369                     }
3370                     else if (!*(DWORD *)pbData || *(DWORD *)pbData > 1024)
3371                     {
3372                         SetLastError(NTE_BAD_DATA);
3373                         return FALSE;
3374                     }
3375                     else
3376                     {
3377                         pCryptKey->dwEffectiveKeyLen = *(DWORD *)pbData;
3378                         setup_key(pCryptKey);
3379                     }
3380                     break;
3381                 default:
3382                     SetLastError(NTE_BAD_TYPE);
3383                     return FALSE;
3384             }
3385             return TRUE;
3386
3387         case KP_SCHANNEL_ALG:
3388             switch (((PSCHANNEL_ALG)pbData)->dwUse) {
3389                 case SCHANNEL_ENC_KEY:
3390                     memcpy(&pCryptKey->siSChannelInfo.saEncAlg, pbData, sizeof(SCHANNEL_ALG));
3391                     break;
3392
3393                 case SCHANNEL_MAC_KEY:
3394                     memcpy(&pCryptKey->siSChannelInfo.saMACAlg, pbData, sizeof(SCHANNEL_ALG));
3395                     break;
3396
3397                 default:
3398                     SetLastError(NTE_FAIL); /* FIXME: error code */
3399                     return FALSE;
3400             }
3401             return TRUE;
3402
3403         case KP_CLIENT_RANDOM:
3404             return copy_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom, (PCRYPT_DATA_BLOB)pbData);
3405             
3406         case KP_SERVER_RANDOM:
3407             return copy_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom, (PCRYPT_DATA_BLOB)pbData);
3408
3409         default:
3410             SetLastError(NTE_BAD_TYPE);
3411             return FALSE;
3412     }
3413 }
3414
3415 /******************************************************************************
3416  * CPGetKeyParam (RSAENH.@)
3417  *
3418  * Query a key parameter.
3419  *
3420  * PARAMS
3421  *  hProv      [I]   The key container, which the key belongs to.
3422  *  hHash      [I]   The key object that is to be queried.
3423  *  dwParam    [I]   Specifies the parameter that is to be queried.
3424  *  pbData     [I]   Pointer to the buffer where the parameter value will be stored.
3425  *  pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
3426  *  dwFlags    [I]   None currently defined.
3427  *
3428  * RETURNS
3429  *  Success: TRUE
3430  *  Failure: FALSE
3431  *
3432  * NOTES
3433  *  Defined dwParam types are:
3434  *   - KP_MODE: Values MODE_CBC, MODE_ECB, MODE_CFB.
3435  *   - KP_MODE_BITS: Shift width for cipher feedback mode. 
3436  *                   (Currently ignored by MS CSP's - always eight)
3437  *   - KP_PERMISSIONS: Or'ed combination of CRYPT_ENCRYPT, CRYPT_DECRYPT, 
3438  *                     CRYPT_EXPORT, CRYPT_READ, CRYPT_WRITE, CRYPT_MAC
3439  *   - KP_IV: Initialization vector.
3440  *   - KP_KEYLEN: Bitwidth of the key.
3441  *   - KP_BLOCKLEN: Size of a block cipher block.
3442  *   - KP_SALT: Salt value.
3443  */
3444 BOOL WINAPI RSAENH_CPGetKeyParam(HCRYPTPROV hProv, HCRYPTKEY hKey, DWORD dwParam, BYTE *pbData, 
3445                                  DWORD *pdwDataLen, DWORD dwFlags)
3446 {
3447     CRYPTKEY *pCryptKey;
3448     DWORD dwValue;
3449         
3450     TRACE("(hProv=%08lx, hKey=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p dwFlags=%08x)\n",
3451           hProv, hKey, dwParam, pbData, pdwDataLen, dwFlags);
3452
3453     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3454     {
3455         SetLastError(NTE_BAD_UID);
3456         return FALSE;
3457     }
3458
3459     if (dwFlags) {
3460         SetLastError(NTE_BAD_FLAGS);
3461         return FALSE;
3462     }
3463
3464     if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
3465     {
3466         SetLastError(NTE_BAD_KEY);
3467         return FALSE;
3468     }
3469
3470     switch (dwParam) 
3471     {
3472         case KP_IV:
3473             return copy_param(pbData, pdwDataLen, pCryptKey->abInitVector,
3474                               pCryptKey->dwBlockLen);
3475         
3476         case KP_SALT:
3477             return copy_param(pbData, pdwDataLen, 
3478                     &pCryptKey->abKeyValue[pCryptKey->dwKeyLen], pCryptKey->dwSaltLen);
3479
3480         case KP_PADDING:
3481             dwValue = PKCS5_PADDING;
3482             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwValue, sizeof(DWORD));
3483
3484         case KP_KEYLEN:
3485             dwValue = pCryptKey->dwKeyLen << 3;
3486             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwValue, sizeof(DWORD));
3487         
3488         case KP_EFFECTIVE_KEYLEN:
3489             if (pCryptKey->dwEffectiveKeyLen)
3490                 dwValue = pCryptKey->dwEffectiveKeyLen;
3491             else
3492                 dwValue = pCryptKey->dwKeyLen << 3;
3493             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwValue, sizeof(DWORD));
3494
3495         case KP_BLOCKLEN:
3496             dwValue = pCryptKey->dwBlockLen << 3;
3497             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwValue, sizeof(DWORD));
3498     
3499         case KP_MODE:
3500             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptKey->dwMode, sizeof(DWORD));
3501
3502         case KP_MODE_BITS:
3503             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptKey->dwModeBits, 
3504                               sizeof(DWORD));
3505     
3506         case KP_PERMISSIONS:
3507             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptKey->dwPermissions, 
3508                               sizeof(DWORD));
3509
3510         case KP_ALGID:
3511             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptKey->aiAlgid, sizeof(DWORD));
3512             
3513         default:
3514             SetLastError(NTE_BAD_TYPE);
3515             return FALSE;
3516     }
3517 }
3518                         
3519 /******************************************************************************
3520  * CPGetProvParam (RSAENH.@)
3521  *
3522  * Query a CSP parameter.
3523  *
3524  * PARAMS
3525  *  hProv      [I]   The key container that is to be queried.
3526  *  dwParam    [I]   Specifies the parameter that is to be queried.
3527  *  pbData     [I]   Pointer to the buffer where the parameter value will be stored.
3528  *  pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
3529  *  dwFlags    [I]   CRYPT_FIRST: Start enumeration (for PP_ENUMALGS{_EX}).
3530  *
3531  * RETURNS
3532  *  Success: TRUE
3533  *  Failure: FALSE
3534  * NOTES:
3535  *  Defined dwParam types:
3536  *   - PP_CONTAINER: Name of the key container.
3537  *   - PP_NAME: Name of the cryptographic service provider.
3538  *   - PP_SIG_KEYSIZE_INC: RSA signature keywidth granularity in bits.
3539  *   - PP_KEYX_KEYSIZE_INC: RSA key-exchange keywidth granularity in bits.
3540  *   - PP_ENUMALGS{_EX}: Query provider capabilities.
3541  */
3542 BOOL WINAPI RSAENH_CPGetProvParam(HCRYPTPROV hProv, DWORD dwParam, BYTE *pbData, 
3543                                   DWORD *pdwDataLen, DWORD dwFlags)
3544 {
3545     KEYCONTAINER *pKeyContainer;
3546     PROV_ENUMALGS provEnumalgs;
3547     DWORD dwTemp;
3548     HKEY hKey;
3549    
3550     /* This is for dwParam PP_CRYPT_COUNT_KEY_USE.
3551      * IE6 SP1 asks for it in the 'About' dialog.
3552      * Returning this BLOB seems to satisfy IE. The marked 0x00 seem 
3553      * to be 'don't care's. If you know anything more specific about
3554      * this provider parameter, please report to wine-devel@winehq.org */
3555     static CONST BYTE abWTF[96] = { 
3556         0xb0, 0x25,     0x63,     0x86, 0x9c, 0xab,     0xb6,     0x37, 
3557         0xe8, 0x82, /**/0x00,/**/ 0x72, 0x06, 0xb2, /**/0x00,/**/ 0x3b, 
3558         0x60, 0x35, /**/0x00,/**/ 0x3b, 0x88, 0xce, /**/0x00,/**/ 0x82, 
3559         0xbc, 0x7a, /**/0x00,/**/ 0xb7, 0x4f, 0x7e, /**/0x00,/**/ 0xde, 
3560         0x92, 0xf1, /**/0x00,/**/ 0x83, 0xea, 0x5e, /**/0x00,/**/ 0xc8, 
3561         0x12, 0x1e,     0xd4,     0x06, 0xf7, 0x66, /**/0x00,/**/ 0x01, 
3562         0x29, 0xa4, /**/0x00,/**/ 0xf8, 0x24, 0x0c, /**/0x00,/**/ 0x33, 
3563         0x06, 0x80, /**/0x00,/**/ 0x02, 0x46, 0x0b, /**/0x00,/**/ 0x6d, 
3564         0x5b, 0xca, /**/0x00,/**/ 0x9a, 0x10, 0xf0, /**/0x00,/**/ 0x05, 
3565         0x19, 0xd0, /**/0x00,/**/ 0x2c, 0xf6, 0x27, /**/0x00,/**/ 0xaa, 
3566         0x7c, 0x6f, /**/0x00,/**/ 0xb9, 0xd8, 0x72, /**/0x00,/**/ 0x03, 
3567         0xf3, 0x81, /**/0x00,/**/ 0xfa, 0xe8, 0x26, /**/0x00,/**/ 0xca 
3568     };
3569
3570     TRACE("(hProv=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p, dwFlags=%08x)\n",
3571            hProv, dwParam, pbData, pdwDataLen, dwFlags);
3572
3573     if (!pdwDataLen) {
3574         SetLastError(ERROR_INVALID_PARAMETER);
3575         return FALSE;
3576     }
3577     
3578     if (!lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER,
3579                        (OBJECTHDR**)&pKeyContainer)) 
3580     {
3581         /* MSDN: hProv not containing valid context handle */
3582         SetLastError(NTE_BAD_UID);
3583         return FALSE;
3584     }
3585
3586     switch (dwParam) 
3587     {
3588         case PP_CONTAINER:
3589         case PP_UNIQUE_CONTAINER:/* MSDN says we can return the same value as PP_CONTAINER */
3590             return copy_param(pbData, pdwDataLen, (CONST BYTE*)pKeyContainer->szName, 
3591                               strlen(pKeyContainer->szName)+1);
3592
3593         case PP_NAME:
3594             return copy_param(pbData, pdwDataLen, (CONST BYTE*)pKeyContainer->szProvName, 
3595                               strlen(pKeyContainer->szProvName)+1);
3596
3597         case PP_PROVTYPE:
3598             dwTemp = PROV_RSA_FULL;
3599             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwTemp, sizeof(dwTemp));
3600
3601         case PP_KEYSPEC:
3602             dwTemp = AT_SIGNATURE | AT_KEYEXCHANGE;
3603             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwTemp, sizeof(dwTemp));
3604
3605         case PP_KEYSET_TYPE:
3606             dwTemp = pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET;
3607             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwTemp, sizeof(dwTemp));
3608
3609         case PP_KEYSTORAGE:
3610             dwTemp = CRYPT_SEC_DESCR;
3611             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwTemp, sizeof(dwTemp));
3612
3613         case PP_SIG_KEYSIZE_INC:
3614         case PP_KEYX_KEYSIZE_INC:
3615             dwTemp = 8;
3616             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwTemp, sizeof(dwTemp));
3617
3618         case PP_IMPTYPE:
3619             dwTemp = CRYPT_IMPL_SOFTWARE;
3620             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwTemp, sizeof(dwTemp));
3621
3622         case PP_VERSION:
3623             dwTemp = 0x00000200;
3624             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwTemp, sizeof(dwTemp));
3625             
3626         case PP_ENUMCONTAINERS:
3627             if ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) pKeyContainer->dwEnumContainersCtr = 0;
3628
3629             if (!pbData) {
3630                 *pdwDataLen = (DWORD)MAX_PATH + 1;
3631                 return TRUE;
3632             }
3633  
3634             if (!open_container_key("", dwFlags, &hKey))
3635             {
3636                 SetLastError(ERROR_NO_MORE_ITEMS);
3637                 return FALSE;
3638             }
3639
3640             dwTemp = *pdwDataLen;
3641             switch (RegEnumKeyExA(hKey, pKeyContainer->dwEnumContainersCtr, (LPSTR)pbData, &dwTemp,
3642                     NULL, NULL, NULL, NULL))
3643             {
3644                 case ERROR_MORE_DATA:
3645                     *pdwDataLen = (DWORD)MAX_PATH + 1;
3646  
3647                 case ERROR_SUCCESS:
3648                     pKeyContainer->dwEnumContainersCtr++;
3649                     RegCloseKey(hKey);
3650                     return TRUE;
3651
3652                 case ERROR_NO_MORE_ITEMS:
3653                 default:
3654                     SetLastError(ERROR_NO_MORE_ITEMS);
3655                     RegCloseKey(hKey);
3656                     return FALSE;
3657             }
3658  
3659         case PP_ENUMALGS:
3660         case PP_ENUMALGS_EX:
3661             if (((pKeyContainer->dwEnumAlgsCtr >= RSAENH_MAX_ENUMALGS-1) ||
3662                  (!aProvEnumAlgsEx[pKeyContainer->dwPersonality]
3663                    [pKeyContainer->dwEnumAlgsCtr+1].aiAlgid)) && 
3664                 ((dwFlags & CRYPT_FIRST) != CRYPT_FIRST))
3665             {
3666                 SetLastError(ERROR_NO_MORE_ITEMS);
3667                 return FALSE;
3668             }
3669
3670             if (dwParam == PP_ENUMALGS) {    
3671                 if (pbData && (*pdwDataLen >= sizeof(PROV_ENUMALGS))) 
3672                     pKeyContainer->dwEnumAlgsCtr = ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) ? 
3673                         0 : pKeyContainer->dwEnumAlgsCtr+1;
3674             
3675                 provEnumalgs.aiAlgid = aProvEnumAlgsEx
3676                     [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].aiAlgid;
3677                 provEnumalgs.dwBitLen = aProvEnumAlgsEx
3678                     [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].dwDefaultLen;
3679                 provEnumalgs.dwNameLen = aProvEnumAlgsEx
3680                     [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].dwNameLen;
3681                 memcpy(provEnumalgs.szName, aProvEnumAlgsEx
3682                        [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].szName, 
3683                        20*sizeof(CHAR));
3684             
3685                 return copy_param(pbData, pdwDataLen, (CONST BYTE*)&provEnumalgs, 
3686                                   sizeof(PROV_ENUMALGS));
3687             } else {
3688                 if (pbData && (*pdwDataLen >= sizeof(PROV_ENUMALGS_EX))) 
3689                     pKeyContainer->dwEnumAlgsCtr = ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) ? 
3690                         0 : pKeyContainer->dwEnumAlgsCtr+1;
3691             
3692                 return copy_param(pbData, pdwDataLen, 
3693                                   (CONST BYTE*)&aProvEnumAlgsEx
3694                                       [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr], 
3695                                   sizeof(PROV_ENUMALGS_EX));
3696             }
3697
3698         case PP_CRYPT_COUNT_KEY_USE: /* Asked for by IE About dialog */
3699             return copy_param(pbData, pdwDataLen, abWTF, sizeof(abWTF));
3700
3701         default:
3702             /* MSDN: Unknown parameter number in dwParam */
3703             SetLastError(NTE_BAD_TYPE);
3704             return FALSE;
3705     }
3706 }
3707
3708 /******************************************************************************
3709  * CPDeriveKey (RSAENH.@)
3710  *
3711  * Derives a key from a hash value.
3712  *
3713  * PARAMS
3714  *  hProv     [I] Key container for which a key is to be generated.
3715  *  Algid     [I] Crypto algorithm identifier for the key to be generated.
3716  *  hBaseData [I] Hash from whose value the key will be derived.
3717  *  dwFlags   [I] See Notes.
3718  *  phKey     [O] The generated key.
3719  *
3720  * RETURNS
3721  *  Success: TRUE
3722  *  Failure: FALSE
3723  *
3724  * NOTES
3725  *  Defined flags:
3726  *   - CRYPT_EXPORTABLE: Key can be exported.
3727  *   - CRYPT_NO_SALT: No salt is used for 40 bit keys.
3728  *   - CRYPT_CREATE_SALT: Use remaining bits as salt value.
3729  */
3730 BOOL WINAPI RSAENH_CPDeriveKey(HCRYPTPROV hProv, ALG_ID Algid, HCRYPTHASH hBaseData, 
3731                                DWORD dwFlags, HCRYPTKEY *phKey)
3732 {
3733     CRYPTKEY *pCryptKey, *pMasterKey;
3734     CRYPTHASH *pCryptHash;
3735     BYTE abHashValue[RSAENH_MAX_HASH_SIZE*2];
3736     DWORD dwLen;
3737     
3738     TRACE("(hProv=%08lx, Algid=%d, hBaseData=%08lx, dwFlags=%08x phKey=%p)\n", hProv, Algid,
3739            hBaseData, dwFlags, phKey);
3740     
3741     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3742     {
3743         SetLastError(NTE_BAD_UID);
3744         return FALSE;
3745     }
3746
3747     if (!lookup_handle(&handle_table, hBaseData, RSAENH_MAGIC_HASH,
3748                        (OBJECTHDR**)&pCryptHash))
3749     {
3750         SetLastError(NTE_BAD_HASH);
3751         return FALSE;
3752     }
3753
3754     if (!phKey)
3755     {
3756         SetLastError(ERROR_INVALID_PARAMETER);
3757         return FALSE;
3758     }
3759
3760     switch (GET_ALG_CLASS(Algid))
3761     {
3762         case ALG_CLASS_DATA_ENCRYPT:
3763             *phKey = new_key(hProv, Algid, dwFlags, &pCryptKey);
3764             if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
3765
3766             /* 
3767              * We derive the key material from the hash.
3768              * If the hash value is not large enough for the claimed key, we have to construct
3769              * a larger binary value based on the hash. This is documented in MSDN: CryptDeriveKey.
3770              */
3771             dwLen = RSAENH_MAX_HASH_SIZE;
3772             RSAENH_CPGetHashParam(pCryptHash->hProv, hBaseData, HP_HASHVAL, abHashValue, &dwLen, 0);
3773     
3774             if (dwLen < pCryptKey->dwKeyLen) {
3775                 BYTE pad1[RSAENH_HMAC_DEF_PAD_LEN], pad2[RSAENH_HMAC_DEF_PAD_LEN];
3776                 BYTE old_hashval[RSAENH_MAX_HASH_SIZE];
3777                 DWORD i;
3778
3779                 memcpy(old_hashval, pCryptHash->abHashValue, RSAENH_MAX_HASH_SIZE);
3780             
3781                 for (i=0; i<RSAENH_HMAC_DEF_PAD_LEN; i++) {
3782                     pad1[i] = RSAENH_HMAC_DEF_IPAD_CHAR ^ (i<dwLen ? abHashValue[i] : 0);
3783                     pad2[i] = RSAENH_HMAC_DEF_OPAD_CHAR ^ (i<dwLen ? abHashValue[i] : 0);
3784                 }
3785                 
3786                 init_hash(pCryptHash);
3787                 update_hash(pCryptHash, pad1, RSAENH_HMAC_DEF_PAD_LEN);
3788                 finalize_hash(pCryptHash);
3789                 memcpy(abHashValue, pCryptHash->abHashValue, pCryptHash->dwHashSize);
3790
3791                 init_hash(pCryptHash);
3792                 update_hash(pCryptHash, pad2, RSAENH_HMAC_DEF_PAD_LEN);
3793                 finalize_hash(pCryptHash);
3794                 memcpy(abHashValue+pCryptHash->dwHashSize, pCryptHash->abHashValue, 
3795                        pCryptHash->dwHashSize);
3796
3797                 memcpy(pCryptHash->abHashValue, old_hashval, RSAENH_MAX_HASH_SIZE);
3798             }
3799     
3800             memcpy(pCryptKey->abKeyValue, abHashValue, 
3801                    RSAENH_MIN(pCryptKey->dwKeyLen, sizeof(pCryptKey->abKeyValue)));
3802             break;
3803
3804         case ALG_CLASS_MSG_ENCRYPT:
3805             if (!lookup_handle(&handle_table, pCryptHash->hKey, RSAENH_MAGIC_KEY,
3806                                (OBJECTHDR**)&pMasterKey)) 
3807             {
3808                 SetLastError(NTE_FAIL); /* FIXME error code */
3809                 return FALSE;
3810             }
3811                 
3812             switch (Algid) 
3813             {
3814                 /* See RFC 2246, chapter 6.3 Key calculation */
3815                 case CALG_SCHANNEL_ENC_KEY:
3816                     *phKey = new_key(hProv, pMasterKey->siSChannelInfo.saEncAlg.Algid, 
3817                                      MAKELONG(LOWORD(dwFlags),pMasterKey->siSChannelInfo.saEncAlg.cBits),
3818                                      &pCryptKey);
3819                     if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
3820                     memcpy(pCryptKey->abKeyValue, 
3821                            pCryptHash->abHashValue + (
3822                                2 * (pMasterKey->siSChannelInfo.saMACAlg.cBits / 8) +
3823                                ((dwFlags & CRYPT_SERVER) ? 
3824                                    (pMasterKey->siSChannelInfo.saEncAlg.cBits / 8) : 0)),
3825                            pMasterKey->siSChannelInfo.saEncAlg.cBits / 8);
3826                     memcpy(pCryptKey->abInitVector,
3827                            pCryptHash->abHashValue + (
3828                                2 * (pMasterKey->siSChannelInfo.saMACAlg.cBits / 8) +
3829                                2 * (pMasterKey->siSChannelInfo.saEncAlg.cBits / 8) +
3830                                ((dwFlags & CRYPT_SERVER) ? pCryptKey->dwBlockLen : 0)),
3831                            pCryptKey->dwBlockLen);
3832                     break;
3833                     
3834                 case CALG_SCHANNEL_MAC_KEY:
3835                     *phKey = new_key(hProv, Algid, 
3836                                      MAKELONG(LOWORD(dwFlags),pMasterKey->siSChannelInfo.saMACAlg.cBits),
3837                                      &pCryptKey);
3838                     if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
3839                     memcpy(pCryptKey->abKeyValue,
3840                            pCryptHash->abHashValue + ((dwFlags & CRYPT_SERVER) ? 
3841                                pMasterKey->siSChannelInfo.saMACAlg.cBits / 8 : 0),
3842                            pMasterKey->siSChannelInfo.saMACAlg.cBits / 8);
3843                     break;
3844                     
3845                 default:
3846                     SetLastError(NTE_BAD_ALGID);
3847                     return FALSE;
3848             }
3849             break;
3850
3851         default:
3852             SetLastError(NTE_BAD_ALGID);
3853             return FALSE;
3854     }
3855
3856     setup_key(pCryptKey);
3857     return TRUE;    
3858 }
3859
3860 /******************************************************************************
3861  * CPGetUserKey (RSAENH.@)
3862  *
3863  * Returns a handle to the user's private key-exchange- or signature-key.
3864  *
3865  * PARAMS
3866  *  hProv     [I] The key container from which a user key is requested.
3867  *  dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
3868  *  phUserKey [O] Handle to the requested key or INVALID_HANDLE_VALUE in case of failure.
3869  *
3870  * RETURNS
3871  *  Success: TRUE.
3872  *  Failure: FALSE.
3873  *
3874  * NOTE
3875  *  A newly created key container does not contain private user key. Create them with CPGenKey.
3876  */
3877 BOOL WINAPI RSAENH_CPGetUserKey(HCRYPTPROV hProv, DWORD dwKeySpec, HCRYPTKEY *phUserKey)
3878 {
3879     KEYCONTAINER *pKeyContainer;
3880
3881     TRACE("(hProv=%08lx, dwKeySpec=%08x, phUserKey=%p)\n", hProv, dwKeySpec, phUserKey);
3882     
3883     if (!lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER,
3884                        (OBJECTHDR**)&pKeyContainer)) 
3885     {
3886         /* MSDN: hProv not containing valid context handle */
3887         SetLastError(NTE_BAD_UID);
3888         return FALSE;
3889     }
3890
3891     switch (dwKeySpec)
3892     {
3893         case AT_KEYEXCHANGE:
3894             copy_handle(&handle_table, pKeyContainer->hKeyExchangeKeyPair, RSAENH_MAGIC_KEY, 
3895                         phUserKey);
3896             break;
3897
3898         case AT_SIGNATURE:
3899             copy_handle(&handle_table, pKeyContainer->hSignatureKeyPair, RSAENH_MAGIC_KEY, 
3900                         phUserKey);
3901             break;
3902
3903         default:
3904             *phUserKey = (HCRYPTKEY)INVALID_HANDLE_VALUE;
3905     }
3906
3907     if (*phUserKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
3908     {
3909         /* MSDN: dwKeySpec parameter specifies nonexistent key */
3910         SetLastError(NTE_NO_KEY);
3911         return FALSE;
3912     }
3913
3914     return TRUE;
3915 }
3916
3917 /******************************************************************************
3918  * CPHashData (RSAENH.@)
3919  *
3920  * Updates a hash object with the given data.
3921  *
3922  * PARAMS
3923  *  hProv     [I] Key container to which the hash object belongs.
3924  *  hHash     [I] Hash object which is to be updated.
3925  *  pbData    [I] Pointer to data with which the hash object is to be updated.
3926  *  dwDataLen [I] Length of the data.
3927  *  dwFlags   [I] Currently none defined.
3928  *
3929  * RETURNS
3930  *  Success: TRUE.
3931  *  Failure: FALSE.
3932  *
3933  * NOTES
3934  *  The actual hash value is queried with CPGetHashParam, which will finalize 
3935  *  the hash. Updating a finalized hash will fail with a last error NTE_BAD_HASH_STATE.
3936  */
3937 BOOL WINAPI RSAENH_CPHashData(HCRYPTPROV hProv, HCRYPTHASH hHash, CONST BYTE *pbData, 
3938                               DWORD dwDataLen, DWORD dwFlags)
3939 {
3940     CRYPTHASH *pCryptHash;
3941         
3942     TRACE("(hProv=%08lx, hHash=%08lx, pbData=%p, dwDataLen=%d, dwFlags=%08x)\n",
3943           hProv, hHash, pbData, dwDataLen, dwFlags);
3944
3945     if (dwFlags)
3946     {
3947         SetLastError(NTE_BAD_FLAGS);
3948         return FALSE;
3949     }
3950
3951     if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH,
3952                        (OBJECTHDR**)&pCryptHash))
3953     {
3954         SetLastError(NTE_BAD_HASH);
3955         return FALSE;
3956     }
3957
3958     if (!get_algid_info(hProv, pCryptHash->aiAlgid) || pCryptHash->aiAlgid == CALG_SSL3_SHAMD5)
3959     {
3960         SetLastError(NTE_BAD_ALGID);
3961         return FALSE;
3962     }
3963     
3964     if (pCryptHash->dwState != RSAENH_HASHSTATE_HASHING)
3965     {
3966         SetLastError(NTE_BAD_HASH_STATE);
3967         return FALSE;
3968     }
3969
3970     update_hash(pCryptHash, pbData, dwDataLen);
3971     return TRUE;
3972 }
3973
3974 /******************************************************************************
3975  * CPHashSessionKey (RSAENH.@)
3976  *
3977  * Updates a hash object with the binary representation of a symmetric key.
3978  *
3979  * PARAMS
3980  *  hProv     [I] Key container to which the hash object belongs.
3981  *  hHash     [I] Hash object which is to be updated.
3982  *  hKey      [I] The symmetric key, whose binary value will be added to the hash.
3983  *  dwFlags   [I] CRYPT_LITTLE_ENDIAN, if the binary key value shall be interpreted as little endian.
3984  *
3985  * RETURNS
3986  *  Success: TRUE.
3987  *  Failure: FALSE.
3988  */
3989 BOOL WINAPI RSAENH_CPHashSessionKey(HCRYPTPROV hProv, HCRYPTHASH hHash, HCRYPTKEY hKey, 
3990                                     DWORD dwFlags)
3991 {
3992     BYTE abKeyValue[RSAENH_MAX_KEY_SIZE], bTemp;
3993     CRYPTKEY *pKey;
3994     DWORD i;
3995
3996     TRACE("(hProv=%08lx, hHash=%08lx, hKey=%08lx, dwFlags=%08x)\n", hProv, hHash, hKey, dwFlags);
3997
3998     if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pKey) ||
3999         (GET_ALG_CLASS(pKey->aiAlgid) != ALG_CLASS_DATA_ENCRYPT)) 
4000     {
4001         SetLastError(NTE_BAD_KEY);
4002         return FALSE;
4003     }
4004
4005     if (dwFlags & ~CRYPT_LITTLE_ENDIAN) {
4006         SetLastError(NTE_BAD_FLAGS);
4007         return FALSE;
4008     }
4009
4010     memcpy(abKeyValue, pKey->abKeyValue, pKey->dwKeyLen);
4011     if (!(dwFlags & CRYPT_LITTLE_ENDIAN)) {
4012         for (i=0; i<pKey->dwKeyLen/2; i++) {
4013             bTemp = abKeyValue[i];
4014             abKeyValue[i] = abKeyValue[pKey->dwKeyLen-i-1];
4015             abKeyValue[pKey->dwKeyLen-i-1] = bTemp;
4016         }
4017     }
4018
4019     return RSAENH_CPHashData(hProv, hHash, abKeyValue, pKey->dwKeyLen, 0);
4020 }
4021
4022 /******************************************************************************
4023  * CPReleaseContext (RSAENH.@)
4024  *
4025  * Release a key container.
4026  *
4027  * PARAMS
4028  *  hProv   [I] Key container to be released.
4029  *  dwFlags [I] Currently none defined.
4030  *
4031  * RETURNS
4032  *  Success: TRUE
4033  *  Failure: FALSE
4034  */
4035 BOOL WINAPI RSAENH_CPReleaseContext(HCRYPTPROV hProv, DWORD dwFlags)
4036 {
4037     TRACE("(hProv=%08lx, dwFlags=%08x)\n", hProv, dwFlags);
4038
4039     if (!release_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
4040     {
4041         /* MSDN: hProv not containing valid context handle */
4042         SetLastError(NTE_BAD_UID);
4043         return FALSE;
4044     }
4045
4046     if (dwFlags) {
4047         SetLastError(NTE_BAD_FLAGS);
4048         return FALSE;
4049     }
4050     
4051     return TRUE;
4052 }
4053
4054 /******************************************************************************
4055  * CPSetHashParam (RSAENH.@)
4056  * 
4057  * Set a parameter of a hash object
4058  *
4059  * PARAMS
4060  *  hProv   [I] The key container to which the key belongs.
4061  *  hHash   [I] The hash object for which a parameter is to be set.
4062  *  dwParam [I] Parameter type. See Notes.
4063  *  pbData  [I] Pointer to the parameter value.
4064  *  dwFlags [I] Currently none defined.
4065  *
4066  * RETURNS
4067  *  Success: TRUE.
4068  *  Failure: FALSE.
4069  *
4070  * NOTES
4071  *  Currently only the HP_HMAC_INFO dwParam type is defined. 
4072  *  The HMAC_INFO struct will be deep copied into the hash object.
4073  *  See Internet RFC 2104 for details on the HMAC algorithm.
4074  */
4075 BOOL WINAPI RSAENH_CPSetHashParam(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwParam, 
4076                                   BYTE *pbData, DWORD dwFlags)
4077 {
4078     CRYPTHASH *pCryptHash;
4079     CRYPTKEY *pCryptKey;
4080     DWORD i;
4081
4082     TRACE("(hProv=%08lx, hHash=%08lx, dwParam=%08x, pbData=%p, dwFlags=%08x)\n",
4083            hProv, hHash, dwParam, pbData, dwFlags);
4084
4085     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
4086     {
4087         SetLastError(NTE_BAD_UID);
4088         return FALSE;
4089     }
4090
4091     if (dwFlags) {
4092         SetLastError(NTE_BAD_FLAGS);
4093         return FALSE;
4094     }
4095     
4096     if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH,
4097                        (OBJECTHDR**)&pCryptHash))
4098     {
4099         SetLastError(NTE_BAD_HASH);
4100         return FALSE;
4101     }
4102     
4103     switch (dwParam) {
4104         case HP_HMAC_INFO:
4105             free_hmac_info(pCryptHash->pHMACInfo);
4106             if (!copy_hmac_info(&pCryptHash->pHMACInfo, (PHMAC_INFO)pbData)) return FALSE;
4107
4108             if (!lookup_handle(&handle_table, pCryptHash->hKey, RSAENH_MAGIC_KEY, 
4109                                (OBJECTHDR**)&pCryptKey)) 
4110             {
4111                 SetLastError(NTE_FAIL); /* FIXME: correct error code? */
4112                 return FALSE;
4113             }
4114
4115             for (i=0; i<RSAENH_MIN(pCryptKey->dwKeyLen,pCryptHash->pHMACInfo->cbInnerString); i++) {
4116                 pCryptHash->pHMACInfo->pbInnerString[i] ^= pCryptKey->abKeyValue[i];
4117             }
4118             for (i=0; i<RSAENH_MIN(pCryptKey->dwKeyLen,pCryptHash->pHMACInfo->cbOuterString); i++) {
4119                 pCryptHash->pHMACInfo->pbOuterString[i] ^= pCryptKey->abKeyValue[i];
4120             }
4121             
4122             init_hash(pCryptHash);
4123             return TRUE;
4124
4125         case HP_HASHVAL:
4126             memcpy(pCryptHash->abHashValue, pbData, pCryptHash->dwHashSize);
4127             pCryptHash->dwState = RSAENH_HASHSTATE_FINISHED;
4128             return TRUE;
4129            
4130         case HP_TLS1PRF_SEED:
4131             return copy_data_blob(&pCryptHash->tpPRFParams.blobSeed, (PCRYPT_DATA_BLOB)pbData);
4132
4133         case HP_TLS1PRF_LABEL:
4134             return copy_data_blob(&pCryptHash->tpPRFParams.blobLabel, (PCRYPT_DATA_BLOB)pbData);
4135             
4136         default:
4137             SetLastError(NTE_BAD_TYPE);
4138             return FALSE;
4139     }
4140 }
4141
4142 /******************************************************************************
4143  * CPSetProvParam (RSAENH.@)
4144  */
4145 BOOL WINAPI RSAENH_CPSetProvParam(HCRYPTPROV hProv, DWORD dwParam, BYTE *pbData, DWORD dwFlags)
4146 {
4147     FIXME("(stub)\n");
4148     return FALSE;
4149 }
4150
4151 /******************************************************************************
4152  * CPSignHash (RSAENH.@)
4153  *
4154  * Sign a hash object
4155  *
4156  * PARAMS
4157  *  hProv        [I]   The key container, to which the hash object belongs.
4158  *  hHash        [I]   The hash object to be signed.
4159  *  dwKeySpec    [I]   AT_SIGNATURE or AT_KEYEXCHANGE: Key used to generate the signature.
4160  *  sDescription [I]   Should be NULL for security reasons. 
4161  *  dwFlags      [I]   0, CRYPT_NOHASHOID or CRYPT_X931_FORMAT: Format of the signature.
4162  *  pbSignature  [O]   Buffer, to which the signature will be stored. May be NULL to query SigLen.
4163  *  pdwSigLen    [I/O] Size of the buffer (in), Length of the signature (out)
4164  *
4165  * RETURNS
4166  *  Success: TRUE
4167  *  Failure: FALSE
4168  */
4169 BOOL WINAPI RSAENH_CPSignHash(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwKeySpec, 
4170                               LPCWSTR sDescription, DWORD dwFlags, BYTE *pbSignature, 
4171                               DWORD *pdwSigLen)
4172 {
4173     HCRYPTKEY hCryptKey = (HCRYPTKEY)INVALID_HANDLE_VALUE;
4174     CRYPTKEY *pCryptKey;
4175     DWORD dwHashLen;
4176     BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
4177     ALG_ID aiAlgid;
4178     BOOL ret = FALSE;
4179
4180     TRACE("(hProv=%08lx, hHash=%08lx, dwKeySpec=%08x, sDescription=%s, dwFlags=%08x, "
4181         "pbSignature=%p, pdwSigLen=%p)\n", hProv, hHash, dwKeySpec, debugstr_w(sDescription),
4182         dwFlags, pbSignature, pdwSigLen);
4183
4184     if (dwFlags & ~(CRYPT_NOHASHOID|CRYPT_X931_FORMAT)) {
4185         SetLastError(NTE_BAD_FLAGS);
4186         return FALSE;
4187     }
4188     
4189     if (!RSAENH_CPGetUserKey(hProv, dwKeySpec, &hCryptKey)) return FALSE;
4190             
4191     if (!lookup_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY,
4192                        (OBJECTHDR**)&pCryptKey))
4193     {
4194         SetLastError(NTE_NO_KEY);
4195         goto out;
4196     }
4197
4198     if (!pbSignature) {
4199         *pdwSigLen = pCryptKey->dwKeyLen;
4200         ret = TRUE;
4201         goto out;
4202     }
4203     if (pCryptKey->dwKeyLen > *pdwSigLen)
4204     {
4205         SetLastError(ERROR_MORE_DATA);
4206         *pdwSigLen = pCryptKey->dwKeyLen;
4207         goto out;
4208     }
4209     *pdwSigLen = pCryptKey->dwKeyLen;
4210
4211     if (sDescription) {
4212         if (!RSAENH_CPHashData(hProv, hHash, (CONST BYTE*)sDescription, 
4213                                 (DWORD)lstrlenW(sDescription)*sizeof(WCHAR), 0))
4214         {
4215             goto out;
4216         }
4217     }
4218     
4219     dwHashLen = sizeof(DWORD);
4220     if (!RSAENH_CPGetHashParam(hProv, hHash, HP_ALGID, (BYTE*)&aiAlgid, &dwHashLen, 0)) goto out;
4221     
4222     dwHashLen = RSAENH_MAX_HASH_SIZE;
4223     if (!RSAENH_CPGetHashParam(hProv, hHash, HP_HASHVAL, abHashValue, &dwHashLen, 0)) goto out;
4224  
4225
4226     if (!build_hash_signature(pbSignature, *pdwSigLen, aiAlgid, abHashValue, dwHashLen, dwFlags)) {
4227         goto out;
4228     }
4229
4230     ret = encrypt_block_impl(pCryptKey->aiAlgid, PK_PRIVATE, &pCryptKey->context, pbSignature, pbSignature, RSAENH_ENCRYPT);
4231 out:
4232     RSAENH_CPDestroyKey(hProv, hCryptKey);
4233     return ret;
4234 }
4235
4236 /******************************************************************************
4237  * CPVerifySignature (RSAENH.@)
4238  *
4239  * Verify the signature of a hash object.
4240  * 
4241  * PARAMS
4242  *  hProv        [I] The key container, to which the hash belongs.
4243  *  hHash        [I] The hash for which the signature is verified.
4244  *  pbSignature  [I] The binary signature.
4245  *  dwSigLen     [I] Length of the signature BLOB.
4246  *  hPubKey      [I] Public key used to verify the signature.
4247  *  sDescription [I] Should be NULL for security reasons.
4248  *  dwFlags      [I] 0, CRYPT_NOHASHOID or CRYPT_X931_FORMAT: Format of the signature.
4249  *
4250  * RETURNS
4251  *  Success: TRUE  (Signature is valid)
4252  *  Failure: FALSE (GetLastError() == NTE_BAD_SIGNATURE, if signature is invalid)
4253  */
4254 BOOL WINAPI RSAENH_CPVerifySignature(HCRYPTPROV hProv, HCRYPTHASH hHash, CONST BYTE *pbSignature, 
4255                                      DWORD dwSigLen, HCRYPTKEY hPubKey, LPCWSTR sDescription, 
4256                                      DWORD dwFlags)
4257 {
4258     BYTE *pbConstructed = NULL, *pbDecrypted = NULL;
4259     CRYPTKEY *pCryptKey;
4260     DWORD dwHashLen;
4261     ALG_ID aiAlgid;
4262     BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
4263     BOOL res = FALSE;
4264
4265     TRACE("(hProv=%08lx, hHash=%08lx, pbSignature=%p, dwSigLen=%d, hPubKey=%08lx, sDescription=%s, "
4266           "dwFlags=%08x)\n", hProv, hHash, pbSignature, dwSigLen, hPubKey, debugstr_w(sDescription),
4267           dwFlags);
4268         
4269     if (dwFlags & ~(CRYPT_NOHASHOID|CRYPT_X931_FORMAT)) {
4270         SetLastError(NTE_BAD_FLAGS);
4271         return FALSE;
4272     }
4273     
4274     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
4275     {
4276         SetLastError(NTE_BAD_UID);
4277         return FALSE;
4278     }
4279  
4280     if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY,
4281                        (OBJECTHDR**)&pCryptKey))
4282     {
4283         SetLastError(NTE_BAD_KEY);
4284         return FALSE;
4285     }
4286
4287     /* in Microsoft implementation, the signature length is checked before
4288      * the signature pointer.
4289      */
4290     if (dwSigLen != pCryptKey->dwKeyLen)
4291     {
4292         SetLastError(NTE_BAD_SIGNATURE);
4293         return FALSE;
4294     }
4295
4296     if (!hHash || !pbSignature)
4297     {
4298         SetLastError(ERROR_INVALID_PARAMETER);
4299         return FALSE;
4300     }
4301
4302     if (sDescription) {
4303         if (!RSAENH_CPHashData(hProv, hHash, (CONST BYTE*)sDescription, 
4304                                 (DWORD)lstrlenW(sDescription)*sizeof(WCHAR), 0))
4305         {
4306             return FALSE;
4307         }
4308     }
4309     
4310     dwHashLen = sizeof(DWORD);
4311     if (!RSAENH_CPGetHashParam(hProv, hHash, HP_ALGID, (BYTE*)&aiAlgid, &dwHashLen, 0)) return FALSE;
4312     
4313     dwHashLen = RSAENH_MAX_HASH_SIZE;
4314     if (!RSAENH_CPGetHashParam(hProv, hHash, HP_HASHVAL, abHashValue, &dwHashLen, 0)) return FALSE;
4315
4316     pbConstructed = HeapAlloc(GetProcessHeap(), 0, dwSigLen);
4317     if (!pbConstructed) {
4318         SetLastError(NTE_NO_MEMORY);
4319         goto cleanup;
4320     }
4321
4322     pbDecrypted = HeapAlloc(GetProcessHeap(), 0, dwSigLen);
4323     if (!pbDecrypted) {
4324         SetLastError(NTE_NO_MEMORY);
4325         goto cleanup;
4326     }
4327
4328     if (!encrypt_block_impl(pCryptKey->aiAlgid, PK_PUBLIC, &pCryptKey->context, pbSignature, pbDecrypted, 
4329                             RSAENH_DECRYPT)) 
4330     {
4331         goto cleanup;
4332     }
4333
4334     if (!build_hash_signature(pbConstructed, dwSigLen, aiAlgid, abHashValue, dwHashLen, dwFlags)) {
4335         goto cleanup;
4336     }
4337
4338     if (memcmp(pbDecrypted, pbConstructed, dwSigLen)) {
4339         SetLastError(NTE_BAD_SIGNATURE);
4340         goto cleanup;
4341     }
4342     
4343     res = TRUE;
4344 cleanup:
4345     HeapFree(GetProcessHeap(), 0, pbConstructed);
4346     HeapFree(GetProcessHeap(), 0, pbDecrypted);
4347     return res;
4348 }
4349
4350 static const WCHAR szProviderKeys[6][116] = {
4351     {   'S','o','f','t','w','a','r','e','\\',
4352         'M','i','c','r','o','s','o','f','t','\\','C','r','y','p','t','o','g','r',
4353         'a','p','h','y','\\','D','e','f','a','u','l','t','s','\\','P','r','o','v',
4354         'i','d','e','r','\\','M','i','c','r','o','s','o','f','t',' ','B','a','s',
4355         'e',' ','C','r','y','p','t','o','g','r','a','p','h','i','c',' ','P','r',
4356         'o','v','i','d','e','r',' ','v','1','.','0',0 },
4357     {   'S','o','f','t','w','a','r','e','\\',
4358         'M','i','c','r','o','s','o','f','t','\\','C','r','y','p','t','o','g','r',
4359         'a','p','h','y','\\','D','e','f','a','u','l','t','s','\\','P','r','o','v',
4360         'i','d','e','r','\\','M','i','c','r','o','s','o','f','t',' ',
4361         'E','n','h','a','n','c','e','d',
4362         ' ','C','r','y','p','t','o','g','r','a','p','h','i','c',' ','P','r',
4363         'o','v','i','d','e','r',' ','v','1','.','0',0 },
4364     {   'S','o','f','t','w','a','r','e','\\',
4365         'M','i','c','r','o','s','o','f','t','\\','C','r','y','p','t','o','g','r',
4366         'a','p','h','y','\\','D','e','f','a','u','l','t','s','\\','P','r','o','v',
4367         'i','d','e','r','\\','M','i','c','r','o','s','o','f','t',' ','S','t','r','o','n','g',
4368         ' ','C','r','y','p','t','o','g','r','a','p','h','i','c',' ','P','r',
4369         'o','v','i','d','e','r',0 },
4370     {   'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\',
4371         'C','r','y','p','t','o','g','r','a','p','h','y','\\','D','e','f','a','u','l','t','s','\\',
4372         'P','r','o','v','i','d','e','r','\\','M','i','c','r','o','s','o','f','t',' ',
4373         'R','S','A',' ','S','C','h','a','n','n','e','l',' ',
4374         'C','r','y','p','t','o','g','r','a','p','h','i','c',' ','P','r','o','v','i','d','e','r',0 },
4375     {   'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\',
4376         'C','r','y','p','t','o','g','r','a','p','h','y','\\','D','e','f','a','u','l','t','s','\\',
4377         'P','r','o','v','i','d','e','r','\\','M','i','c','r','o','s','o','f','t',' ',
4378         'E','n','h','a','n','c','e','d',' ','R','S','A',' ','a','n','d',' ','A','E','S',' ',
4379         'C','r','y','p','t','o','g','r','a','p','h','i','c',' ','P','r','o','v','i','d','e','r',0 },
4380     {   'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\',
4381         'C','r','y','p','t','o','g','r','a','p','h','y','\\','D','e','f','a','u','l','t','s','\\',
4382         'P','r','o','v','i','d','e','r','\\','M','i','c','r','o','s','o','f','t',' ',
4383         'E','n','h','a','n','c','e','d',' ','R','S','A',' ','a','n','d',' ','A','E','S',' ',
4384         'C','r','y','p','t','o','g','r','a','p','h','i','c',' ','P','r','o','v','i','d','e','r',
4385         ' ','(','P','r','o','t','o','t','y','p','e',')',0 }
4386 };
4387 static const WCHAR szDefaultKeys[3][65] = {
4388     {   'S','o','f','t','w','a','r','e','\\',
4389         'M','i','c','r','o','s','o','f','t','\\','C','r','y','p','t','o','g','r',
4390         'a','p','h','y','\\','D','e','f','a','u','l','t','s','\\','P','r','o','v',
4391         'i','d','e','r',' ','T','y','p','e','s','\\','T','y','p','e',' ','0','0','1',0 },
4392     {   'S','o','f','t','w','a','r','e','\\',
4393         'M','i','c','r','o','s','o','f','t','\\','C','r','y','p','t','o','g','r',
4394         'a','p','h','y','\\','D','e','f','a','u','l','t','s','\\','P','r','o','v',
4395         'i','d','e','r',' ','T','y','p','e','s','\\','T','y','p','e',' ','0','1','2',0 },
4396     {   'S','o','f','t','w','a','r','e','\\',
4397         'M','i','c','r','o','s','o','f','t','\\','C','r','y','p','t','o','g','r',
4398         'a','p','h','y','\\','D','e','f','a','u','l','t','s','\\','P','r','o','v',
4399         'i','d','e','r',' ','T','y','p','e','s','\\','T','y','p','e',' ','0','2','4',0 }
4400 };
4401
4402
4403 /******************************************************************************
4404  * DllRegisterServer (RSAENH.@)
4405  *
4406  * Dll self registration. 
4407  *
4408  * PARAMS
4409  *
4410  * RETURNS
4411  *  Success: S_OK.
4412  *    Failure: != S_OK
4413  * 
4414  * NOTES
4415  *  Registers the following keys:
4416  *   - HKLM\Software\Microsoft\Cryptography\Defaults\Provider\
4417  *       Microsoft Base Cryptographic Provider v1.0
4418  *   - HKLM\Software\Microsoft\Cryptography\Defaults\Provider\
4419  *       Microsoft Enhanced Cryptographic Provider
4420  *   - HKLM\Software\Microsoft\Cryptography\Defaults\Provider\
4421  *       Microsoft Strong Cryptographpic Provider
4422  *   - HKLM\Software\Microsoft\Cryptography\Defaults\Provider Types\Type 001
4423  */
4424 HRESULT WINAPI DllRegisterServer(void)
4425 {
4426     HKEY key;
4427     DWORD dp;
4428     long apiRet;
4429     int i;
4430
4431     for (i=0; i<6; i++) {
4432         apiRet = RegCreateKeyExW(HKEY_LOCAL_MACHINE, szProviderKeys[i], 0, NULL,
4433             REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &key, &dp);
4434
4435         if (apiRet == ERROR_SUCCESS)
4436         {
4437             if (dp == REG_CREATED_NEW_KEY)
4438             {
4439                 static const WCHAR szImagePath[] = { 'I','m','a','g','e',' ','P','a','t','h',0 };
4440                 static const WCHAR szRSABase[] = { 'r','s','a','e','n','h','.','d','l','l',0 };
4441                 static const WCHAR szType[] = { 'T','y','p','e',0 };
4442                 static const WCHAR szSignature[] = { 'S','i','g','n','a','t','u','r','e',0 };
4443                 DWORD type, sign;
4444
4445                 switch(i)
4446                 {
4447                     case 3:
4448                         type=PROV_RSA_SCHANNEL;
4449                         break;
4450                     case 4:
4451                     case 5:
4452                         type=PROV_RSA_AES;
4453                         break;
4454                     default:
4455                         type=PROV_RSA_FULL;
4456                         break;
4457                 }
4458                 sign = 0xdeadbeef;
4459                 RegSetValueExW(key, szImagePath, 0, REG_SZ, (const BYTE *)szRSABase,
4460                                (lstrlenW(szRSABase) + 1) * sizeof(WCHAR));
4461                 RegSetValueExW(key, szType, 0, REG_DWORD, (LPBYTE)&type, sizeof(type));
4462                 RegSetValueExW(key, szSignature, 0, REG_BINARY, (LPBYTE)&sign, sizeof(sign));
4463             }
4464             RegCloseKey(key);
4465         }
4466     }
4467     
4468     for (i=0; i<3; i++) {
4469         apiRet = RegCreateKeyExW(HKEY_LOCAL_MACHINE, szDefaultKeys[i], 0, NULL,
4470                                  REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &key, &dp);
4471         if (apiRet == ERROR_SUCCESS)
4472         {
4473             if (dp == REG_CREATED_NEW_KEY)
4474             {
4475                 static const WCHAR szName[] = { 'N','a','m','e',0 };
4476                 static const WCHAR szRSAName[3][54] = {
4477                   { 'M','i','c','r','o','s','o','f','t',' ',
4478                     'E','n','h','a','n','c','e','d',' ',
4479                     'C','r','y','p','t','o','g','r','a','p','h','i','c',' ', 
4480                     'P','r','o','v','i','d','e','r',' ','v','1','.','0',0 },
4481                   { 'M','i','c','r','o','s','o','f','t',' ','R','S','A',' ',
4482                     'S','C','h','a','n','n','e','l',' ',
4483                     'C','r','y','p','t','o','g','r','a','p','h','i','c',' ',
4484                     'P','r','o','v','i','d','e','r',0 },
4485                   { 'M','i','c','r','o','s','o','f','t',' ','E','n','h','a','n','c','e','d',' ',
4486                     'R','S','A',' ','a','n','d',' ','A','E','S',' ',
4487                     'C','r','y','p','t','o','g','r','a','p','h','i','c',' ',
4488                     'P','r','o','v','i','d','e','r',0 } };
4489                 static const WCHAR szTypeName[] = { 'T','y','p','e','N','a','m','e',0 };
4490                 static const WCHAR szRSATypeName[3][38] = {
4491                   { 'R','S','A',' ','F','u','l','l',' ',
4492                        '(','S','i','g','n','a','t','u','r','e',' ','a','n','d',' ',
4493                     'K','e','y',' ','E','x','c','h','a','n','g','e',')',0 },
4494                   { 'R','S','A',' ','S','C','h','a','n','n','e','l',0 },
4495                   { 'R','S','A',' ','F','u','l','l',' ','a','n','d',' ','A','E','S',0 } };
4496
4497                 RegSetValueExW(key, szName, 0, REG_SZ,
4498                                 (const BYTE *)szRSAName[i], lstrlenW(szRSAName[i])*sizeof(WCHAR)+sizeof(WCHAR));
4499                 RegSetValueExW(key, szTypeName, 0, REG_SZ, 
4500                                 (const BYTE *)szRSATypeName[i], lstrlenW(szRSATypeName[i])*sizeof(WCHAR)+sizeof(WCHAR));
4501             }
4502         }
4503         RegCloseKey(key);
4504     }
4505     
4506     return HRESULT_FROM_WIN32(apiRet);
4507 }
4508
4509 /******************************************************************************
4510  * DllUnregisterServer (RSAENH.@)
4511  *
4512  * Dll self unregistration. 
4513  *
4514  * PARAMS
4515  *
4516  * RETURNS
4517  *  Success: S_OK
4518  *
4519  * NOTES
4520  *  For the relevant keys see DllRegisterServer.
4521  */
4522 HRESULT WINAPI DllUnregisterServer(void)
4523 {
4524     RegDeleteKeyW(HKEY_LOCAL_MACHINE, szProviderKeys[0]);
4525     RegDeleteKeyW(HKEY_LOCAL_MACHINE, szProviderKeys[1]);
4526     RegDeleteKeyW(HKEY_LOCAL_MACHINE, szProviderKeys[2]);
4527     RegDeleteKeyW(HKEY_LOCAL_MACHINE, szProviderKeys[3]);
4528     RegDeleteKeyW(HKEY_LOCAL_MACHINE, szProviderKeys[4]);
4529     RegDeleteKeyW(HKEY_LOCAL_MACHINE, szProviderKeys[5]);
4530     RegDeleteKeyW(HKEY_LOCAL_MACHINE, szDefaultKeys[0]);
4531     RegDeleteKeyW(HKEY_LOCAL_MACHINE, szDefaultKeys[1]);
4532     RegDeleteKeyW(HKEY_LOCAL_MACHINE, szDefaultKeys[2]);
4533     return S_OK;
4534 }