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