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