rsaenh: Allow CRYPT_NEWKEYSET and CRYPT_VERIFYCONTEXT at same time when acquiring...
[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|CRYPT_NEWKEYSET:
1506         case CRYPT_VERIFYCONTEXT:
1507             if (pszContainer) {
1508                 TRACE("pszContainer should be NULL\n");
1509                 SetLastError(NTE_BAD_FLAGS);
1510                 return FALSE;
1511             }
1512             *phProv = new_key_container("", dwFlags, pVTable);
1513             break;
1514             
1515         default:
1516             *phProv = (HCRYPTPROV)INVALID_HANDLE_VALUE;
1517             SetLastError(NTE_BAD_FLAGS);
1518             return FALSE;
1519     }
1520                 
1521     if (*phProv != (HCRYPTPROV)INVALID_HANDLE_VALUE) {
1522         SetLastError(ERROR_SUCCESS);
1523         return TRUE;
1524     } else {
1525         return FALSE;
1526     }
1527 }
1528
1529 /******************************************************************************
1530  * CPCreateHash (RSAENH.@)
1531  *
1532  * CPCreateHash creates and initalizes a new hash object.
1533  *
1534  * PARAMS
1535  *  hProv   [I] Handle to the key container to which the new hash will belong.
1536  *  Algid   [I] Identifies the hash algorithm, which will be used for the hash.
1537  *  hKey    [I] Handle to a session key applied for keyed hashes.
1538  *  dwFlags [I] Currently no flags defined. Must be zero.
1539  *  phHash  [O] Points to the location where a handle to the new hash will be stored.
1540  *
1541  * RETURNS
1542  *  Success: TRUE
1543  *  Failure: FALSE
1544  *
1545  * NOTES
1546  *  hKey is a handle to a session key applied in keyed hashes like MAC and HMAC.
1547  *  If a normal hash object is to be created (like e.g. MD2 or SHA1) hKey must be zero.
1548  */
1549 BOOL WINAPI RSAENH_CPCreateHash(HCRYPTPROV hProv, ALG_ID Algid, HCRYPTKEY hKey, DWORD dwFlags, 
1550                                 HCRYPTHASH *phHash)
1551 {
1552     CRYPTKEY *pCryptKey;
1553     CRYPTHASH *pCryptHash;
1554     const PROV_ENUMALGS_EX *peaAlgidInfo;
1555         
1556     TRACE("(hProv=%08lx, Algid=%08x, hKey=%08lx, dwFlags=%08x, phHash=%p)\n", hProv, Algid, hKey,
1557           dwFlags, phHash);
1558
1559     peaAlgidInfo = get_algid_info(hProv, Algid);
1560     if (!peaAlgidInfo) return FALSE;
1561
1562     if (dwFlags)
1563     {
1564         SetLastError(NTE_BAD_FLAGS);
1565         return FALSE;
1566     }
1567
1568     if (Algid == CALG_MAC || Algid == CALG_HMAC || Algid == CALG_SCHANNEL_MASTER_HASH || 
1569         Algid == CALG_TLS1PRF) 
1570     {
1571         if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey)) {
1572             SetLastError(NTE_BAD_KEY);
1573             return FALSE;
1574         }
1575
1576         if ((Algid == CALG_MAC) && (GET_ALG_TYPE(pCryptKey->aiAlgid) != ALG_TYPE_BLOCK)) {
1577             SetLastError(NTE_BAD_KEY);
1578             return FALSE;
1579         }
1580
1581         if ((Algid == CALG_SCHANNEL_MASTER_HASH || Algid == CALG_TLS1PRF) && 
1582             (pCryptKey->aiAlgid != CALG_TLS1_MASTER)) 
1583         {
1584             SetLastError(NTE_BAD_KEY);
1585             return FALSE;
1586         }
1587
1588         if ((Algid == CALG_TLS1PRF) && (pCryptKey->dwState != RSAENH_KEYSTATE_MASTERKEY)) {
1589             SetLastError(NTE_BAD_KEY_STATE);
1590             return FALSE;
1591         }
1592     }
1593
1594     *phHash = (HCRYPTHASH)new_object(&handle_table, sizeof(CRYPTHASH), RSAENH_MAGIC_HASH,
1595                                      destroy_hash, (OBJECTHDR**)&pCryptHash);
1596     if (!pCryptHash) return FALSE;
1597     
1598     pCryptHash->aiAlgid = Algid;
1599     pCryptHash->hKey = hKey;
1600     pCryptHash->hProv = hProv;
1601     pCryptHash->dwState = RSAENH_HASHSTATE_IDLE;
1602     pCryptHash->pHMACInfo = (PHMAC_INFO)NULL;
1603     pCryptHash->dwHashSize = peaAlgidInfo->dwDefaultLen >> 3;
1604     init_data_blob(&pCryptHash->tpPRFParams.blobLabel);
1605     init_data_blob(&pCryptHash->tpPRFParams.blobSeed);
1606
1607     if (Algid == CALG_SCHANNEL_MASTER_HASH) {
1608         static const char keyex[] = "key expansion";
1609         BYTE key_expansion[sizeof keyex];
1610         CRYPT_DATA_BLOB blobRandom, blobKeyExpansion = { 13, key_expansion };
1611
1612         memcpy( key_expansion, keyex, sizeof keyex );
1613         
1614         if (pCryptKey->dwState != RSAENH_KEYSTATE_MASTERKEY) {
1615             static const char msec[] = "master secret";
1616             BYTE master_secret[sizeof msec];
1617             CRYPT_DATA_BLOB blobLabel = { 13, master_secret };
1618             BYTE abKeyValue[48];
1619
1620             memcpy( master_secret, msec, sizeof msec );
1621     
1622             /* See RFC 2246, chapter 8.1 */
1623             if (!concat_data_blobs(&blobRandom, 
1624                                    &pCryptKey->siSChannelInfo.blobClientRandom, 
1625                                    &pCryptKey->siSChannelInfo.blobServerRandom))
1626             {
1627                 return FALSE;
1628             }
1629             tls1_prf(hProv, hKey, &blobLabel, &blobRandom, abKeyValue, 48);
1630             pCryptKey->dwState = RSAENH_KEYSTATE_MASTERKEY; 
1631             memcpy(pCryptKey->abKeyValue, abKeyValue, 48);
1632             free_data_blob(&blobRandom);
1633         }
1634
1635         /* See RFC 2246, chapter 6.3 */
1636         if (!concat_data_blobs(&blobRandom, 
1637                                   &pCryptKey->siSChannelInfo.blobServerRandom, 
1638                                   &pCryptKey->siSChannelInfo.blobClientRandom))
1639         {
1640             return FALSE;
1641         }
1642         tls1_prf(hProv, hKey, &blobKeyExpansion, &blobRandom, pCryptHash->abHashValue, 
1643                  RSAENH_MAX_HASH_SIZE);
1644         free_data_blob(&blobRandom);
1645     }
1646
1647     return init_hash(pCryptHash);
1648 }
1649
1650 /******************************************************************************
1651  * CPDestroyHash (RSAENH.@)
1652  * 
1653  * Releases the handle to a hash object. The object is destroyed if it's reference
1654  * count reaches zero.
1655  *
1656  * PARAMS
1657  *  hProv [I] Handle to the key container to which the hash object belongs.
1658  *  hHash [I] Handle to the hash object to be released.
1659  *
1660  * RETURNS
1661  *  Success: TRUE
1662  *  Failure: FALSE 
1663  */
1664 BOOL WINAPI RSAENH_CPDestroyHash(HCRYPTPROV hProv, HCRYPTHASH hHash)
1665 {
1666     TRACE("(hProv=%08lx, hHash=%08lx)\n", hProv, hHash);
1667      
1668     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
1669     {
1670         SetLastError(NTE_BAD_UID);
1671         return FALSE;
1672     }
1673         
1674     if (!release_handle(&handle_table, hHash, RSAENH_MAGIC_HASH)) 
1675     {
1676         SetLastError(NTE_BAD_HASH);
1677         return FALSE;
1678     }
1679     
1680     return TRUE;
1681 }
1682
1683 /******************************************************************************
1684  * CPDestroyKey (RSAENH.@)
1685  *
1686  * Releases the handle to a key object. The object is destroyed if it's reference
1687  * count reaches zero.
1688  *
1689  * PARAMS
1690  *  hProv [I] Handle to the key container to which the key object belongs.
1691  *  hKey  [I] Handle to the key object to be released.
1692  *
1693  * RETURNS
1694  *  Success: TRUE
1695  *  Failure: FALSE
1696  */
1697 BOOL WINAPI RSAENH_CPDestroyKey(HCRYPTPROV hProv, HCRYPTKEY hKey)
1698 {
1699     TRACE("(hProv=%08lx, hKey=%08lx)\n", hProv, hKey);
1700         
1701     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
1702     {
1703         SetLastError(NTE_BAD_UID);
1704         return FALSE;
1705     }
1706         
1707     if (!release_handle(&handle_table, hKey, RSAENH_MAGIC_KEY)) 
1708     {
1709         SetLastError(NTE_BAD_KEY);
1710         return FALSE;
1711     }
1712     
1713     return TRUE;
1714 }
1715
1716 /******************************************************************************
1717  * CPDuplicateHash (RSAENH.@)
1718  *
1719  * Clones a hash object including it's current state.
1720  *
1721  * PARAMS
1722  *  hUID        [I] Handle to the key container the hash belongs to.
1723  *  hHash       [I] Handle to the hash object to be cloned.
1724  *  pdwReserved [I] Reserved. Must be NULL.
1725  *  dwFlags     [I] No flags are currently defined. Must be 0.
1726  *  phHash      [O] Handle to the cloned hash object.
1727  *
1728  * RETURNS
1729  *  Success: TRUE.
1730  *  Failure: FALSE.
1731  */
1732 BOOL WINAPI RSAENH_CPDuplicateHash(HCRYPTPROV hUID, HCRYPTHASH hHash, DWORD *pdwReserved, 
1733                                    DWORD dwFlags, HCRYPTHASH *phHash)
1734 {
1735     CRYPTHASH *pSrcHash, *pDestHash;
1736     
1737     TRACE("(hUID=%08lx, hHash=%08lx, pdwReserved=%p, dwFlags=%08x, phHash=%p)\n", hUID, hHash,
1738            pdwReserved, dwFlags, phHash);
1739
1740     if (!is_valid_handle(&handle_table, hUID, RSAENH_MAGIC_CONTAINER))
1741     {
1742         SetLastError(NTE_BAD_UID);
1743         return FALSE;
1744     }
1745
1746     if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH, (OBJECTHDR**)&pSrcHash))
1747     {
1748         SetLastError(NTE_BAD_HASH);
1749         return FALSE;
1750     }
1751
1752     if (!phHash || pdwReserved || dwFlags) 
1753     {
1754         SetLastError(ERROR_INVALID_PARAMETER);
1755         return FALSE;
1756     }
1757
1758     *phHash = (HCRYPTHASH)new_object(&handle_table, sizeof(CRYPTHASH), RSAENH_MAGIC_HASH, 
1759                                      destroy_hash, (OBJECTHDR**)&pDestHash);
1760     if (*phHash != (HCRYPTHASH)INVALID_HANDLE_VALUE)
1761     {
1762         memcpy(pDestHash, pSrcHash, sizeof(CRYPTHASH));
1763         duplicate_hash_impl(pSrcHash->aiAlgid, &pSrcHash->context, &pDestHash->context);
1764         copy_hmac_info(&pDestHash->pHMACInfo, pSrcHash->pHMACInfo);
1765         copy_data_blob(&pDestHash->tpPRFParams.blobLabel, &pSrcHash->tpPRFParams.blobLabel);
1766         copy_data_blob(&pDestHash->tpPRFParams.blobSeed, &pSrcHash->tpPRFParams.blobSeed);
1767     }
1768
1769     return *phHash != (HCRYPTHASH)INVALID_HANDLE_VALUE;
1770 }
1771
1772 /******************************************************************************
1773  * CPDuplicateKey (RSAENH.@)
1774  *
1775  * Clones a key object including it's current state.
1776  *
1777  * PARAMS
1778  *  hUID        [I] Handle to the key container the hash belongs to.
1779  *  hKey        [I] Handle to the key object to be cloned.
1780  *  pdwReserved [I] Reserved. Must be NULL.
1781  *  dwFlags     [I] No flags are currently defined. Must be 0.
1782  *  phHash      [O] Handle to the cloned key object.
1783  *
1784  * RETURNS
1785  *  Success: TRUE.
1786  *  Failure: FALSE.
1787  */
1788 BOOL WINAPI RSAENH_CPDuplicateKey(HCRYPTPROV hUID, HCRYPTKEY hKey, DWORD *pdwReserved, 
1789                                   DWORD dwFlags, HCRYPTKEY *phKey)
1790 {
1791     CRYPTKEY *pSrcKey, *pDestKey;
1792     
1793     TRACE("(hUID=%08lx, hKey=%08lx, pdwReserved=%p, dwFlags=%08x, phKey=%p)\n", hUID, hKey,
1794           pdwReserved, dwFlags, phKey);
1795
1796     if (!is_valid_handle(&handle_table, hUID, RSAENH_MAGIC_CONTAINER))
1797     {
1798         SetLastError(NTE_BAD_UID);
1799         return FALSE;
1800     }
1801
1802     if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pSrcKey))
1803     {
1804         SetLastError(NTE_BAD_KEY);
1805         return FALSE;
1806     }
1807
1808     if (!phKey || pdwReserved || dwFlags) 
1809     {
1810         SetLastError(ERROR_INVALID_PARAMETER);
1811         return FALSE;
1812     }
1813
1814     *phKey = (HCRYPTKEY)new_object(&handle_table, sizeof(CRYPTKEY), RSAENH_MAGIC_KEY, destroy_key, 
1815                                    (OBJECTHDR**)&pDestKey);
1816     if (*phKey != (HCRYPTKEY)INVALID_HANDLE_VALUE)
1817     {
1818         memcpy(pDestKey, pSrcKey, sizeof(CRYPTKEY));
1819         copy_data_blob(&pDestKey->siSChannelInfo.blobServerRandom,
1820                        &pSrcKey->siSChannelInfo.blobServerRandom);
1821         copy_data_blob(&pDestKey->siSChannelInfo.blobClientRandom, 
1822                        &pSrcKey->siSChannelInfo.blobClientRandom);
1823         duplicate_key_impl(pSrcKey->aiAlgid, &pSrcKey->context, &pDestKey->context);
1824         return TRUE;
1825     }
1826     else
1827     {
1828         return FALSE;
1829     }
1830 }
1831
1832 /******************************************************************************
1833  * CPEncrypt (RSAENH.@)
1834  *
1835  * Encrypt data.
1836  *
1837  * PARAMS
1838  *  hProv      [I]   The key container hKey and hHash belong to.
1839  *  hKey       [I]   The key used to encrypt the data.
1840  *  hHash      [I]   An optional hash object for parallel hashing. See notes.
1841  *  Final      [I]   Indicates if this is the last block of data to encrypt.
1842  *  dwFlags    [I]   Currently no flags defined. Must be zero.
1843  *  pbData     [I/O] Pointer to the data to encrypt. Encrypted data will also be stored there. 
1844  *  pdwDataLen [I/O] I: Length of data to encrypt, O: Length of encrypted data.
1845  *  dwBufLen   [I]   Size of the buffer at pbData.
1846  *
1847  * RETURNS
1848  *  Success: TRUE.
1849  *  Failure: FALSE.
1850  *
1851  * NOTES
1852  *  If a hash object handle is provided in hHash, it will be updated with the plaintext. 
1853  *  This is useful for message signatures.
1854  *
1855  *  This function uses the standard WINAPI protocol for querying data of dynamic length. 
1856  */
1857 BOOL WINAPI RSAENH_CPEncrypt(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final, 
1858                              DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen, DWORD dwBufLen)
1859 {
1860     CRYPTKEY *pCryptKey;
1861     BYTE *in, out[RSAENH_MAX_BLOCK_SIZE], o[RSAENH_MAX_BLOCK_SIZE];
1862     DWORD dwEncryptedLen, i, j, k;
1863         
1864     TRACE("(hProv=%08lx, hKey=%08lx, hHash=%08lx, Final=%d, dwFlags=%08x, pbData=%p, "
1865           "pdwDataLen=%p, dwBufLen=%d)\n", hProv, hKey, hHash, Final, dwFlags, pbData, pdwDataLen,
1866           dwBufLen);
1867     
1868     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
1869     {
1870         SetLastError(NTE_BAD_UID);
1871         return FALSE;
1872     }
1873
1874     if (dwFlags)
1875     {
1876         SetLastError(NTE_BAD_FLAGS);
1877         return FALSE;
1878     }
1879
1880     if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
1881     {
1882         SetLastError(NTE_BAD_KEY);
1883         return FALSE;
1884     }
1885
1886     if (pCryptKey->dwState == RSAENH_KEYSTATE_IDLE) 
1887         pCryptKey->dwState = RSAENH_KEYSTATE_ENCRYPTING;
1888
1889     if (pCryptKey->dwState != RSAENH_KEYSTATE_ENCRYPTING) 
1890     {
1891         SetLastError(NTE_BAD_DATA);
1892         return FALSE;
1893     }
1894
1895     if (is_valid_handle(&handle_table, hHash, RSAENH_MAGIC_HASH)) {
1896         if (!RSAENH_CPHashData(hProv, hHash, pbData, *pdwDataLen, 0)) return FALSE;
1897     }
1898     
1899     if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_BLOCK) {
1900         if (!Final && (*pdwDataLen % pCryptKey->dwBlockLen)) {
1901             SetLastError(NTE_BAD_DATA);
1902             return FALSE;
1903         }
1904
1905         dwEncryptedLen = (*pdwDataLen/pCryptKey->dwBlockLen+(Final?1:0))*pCryptKey->dwBlockLen;
1906
1907         if (pbData == NULL) {
1908             *pdwDataLen = dwEncryptedLen;
1909             return TRUE;
1910         }
1911
1912         for (i=*pdwDataLen; i<dwEncryptedLen && i<dwBufLen; i++) pbData[i] = dwEncryptedLen - *pdwDataLen;
1913         *pdwDataLen = dwEncryptedLen; 
1914
1915         if (*pdwDataLen > dwBufLen) 
1916         {
1917             SetLastError(ERROR_MORE_DATA);
1918             return FALSE;
1919         }
1920     
1921         for (i=0, in=pbData; i<*pdwDataLen; i+=pCryptKey->dwBlockLen, in+=pCryptKey->dwBlockLen) {
1922             switch (pCryptKey->dwMode) {
1923                 case CRYPT_MODE_ECB:
1924                     encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out, 
1925                                        RSAENH_ENCRYPT);
1926                     break;
1927                 
1928                 case CRYPT_MODE_CBC:
1929                     for (j=0; j<pCryptKey->dwBlockLen; j++) in[j] ^= pCryptKey->abChainVector[j];
1930                     encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out, 
1931                                        RSAENH_ENCRYPT);
1932                     memcpy(pCryptKey->abChainVector, out, pCryptKey->dwBlockLen);
1933                     break;
1934
1935                 case CRYPT_MODE_CFB:
1936                     for (j=0; j<pCryptKey->dwBlockLen; j++) {
1937                         encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, 
1938                                            pCryptKey->abChainVector, o, RSAENH_ENCRYPT);
1939                         out[j] = in[j] ^ o[0];
1940                         for (k=0; k<pCryptKey->dwBlockLen-1; k++) 
1941                             pCryptKey->abChainVector[k] = pCryptKey->abChainVector[k+1];
1942                         pCryptKey->abChainVector[k] = out[j];
1943                     }
1944                     break;
1945                     
1946                 default:
1947                     SetLastError(NTE_BAD_ALGID);
1948                     return FALSE;
1949             }
1950             memcpy(in, out, pCryptKey->dwBlockLen); 
1951         }
1952     } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_STREAM) {
1953         if (pbData == NULL) {
1954             *pdwDataLen = dwBufLen;
1955             return TRUE;
1956         }
1957         encrypt_stream_impl(pCryptKey->aiAlgid, &pCryptKey->context, pbData, *pdwDataLen);
1958     } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_RSA) {
1959         if (pCryptKey->aiAlgid == CALG_RSA_SIGN) {
1960             SetLastError(NTE_BAD_KEY);
1961             return FALSE;
1962         }
1963         if (!pbData) {
1964             *pdwDataLen = pCryptKey->dwBlockLen;
1965             return TRUE;
1966         }
1967         if (dwBufLen < pCryptKey->dwBlockLen) {
1968             SetLastError(ERROR_MORE_DATA);
1969             return FALSE;
1970         }
1971         if (!pad_data(pbData, *pdwDataLen, pbData, pCryptKey->dwBlockLen, dwFlags)) return FALSE;
1972         encrypt_block_impl(pCryptKey->aiAlgid, PK_PUBLIC, &pCryptKey->context, pbData, pbData, RSAENH_ENCRYPT);
1973         *pdwDataLen = pCryptKey->dwBlockLen;
1974         Final = TRUE;
1975     } else {
1976         SetLastError(NTE_BAD_TYPE);
1977         return FALSE;
1978     }
1979
1980     if (Final) setup_key(pCryptKey);
1981
1982     return TRUE;
1983 }
1984
1985 /******************************************************************************
1986  * CPDecrypt (RSAENH.@)
1987  *
1988  * Decrypt data.
1989  *
1990  * PARAMS
1991  *  hProv      [I]   The key container hKey and hHash belong to.
1992  *  hKey       [I]   The key used to decrypt the data.
1993  *  hHash      [I]   An optional hash object for parallel hashing. See notes.
1994  *  Final      [I]   Indicates if this is the last block of data to decrypt.
1995  *  dwFlags    [I]   Currently no flags defined. Must be zero.
1996  *  pbData     [I/O] Pointer to the data to decrypt. Plaintext will also be stored there. 
1997  *  pdwDataLen [I/O] I: Length of ciphertext, O: Length of plaintext.
1998  *
1999  * RETURNS
2000  *  Success: TRUE.
2001  *  Failure: FALSE.
2002  *
2003  * NOTES
2004  *  If a hash object handle is provided in hHash, it will be updated with the plaintext. 
2005  *  This is useful for message signatures.
2006  *
2007  *  This function uses the standard WINAPI protocol for querying data of dynamic length. 
2008  */
2009 BOOL WINAPI RSAENH_CPDecrypt(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final, 
2010                              DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2011 {
2012     CRYPTKEY *pCryptKey;
2013     BYTE *in, out[RSAENH_MAX_BLOCK_SIZE], o[RSAENH_MAX_BLOCK_SIZE];
2014     DWORD i, j, k;
2015     DWORD dwMax;
2016
2017     TRACE("(hProv=%08lx, hKey=%08lx, hHash=%08lx, Final=%d, dwFlags=%08x, pbData=%p, "
2018           "pdwDataLen=%p)\n", hProv, hKey, hHash, Final, dwFlags, pbData, pdwDataLen);
2019     
2020     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2021     {
2022         SetLastError(NTE_BAD_UID);
2023         return FALSE;
2024     }
2025
2026     if (dwFlags)
2027     {
2028         SetLastError(NTE_BAD_FLAGS);
2029         return FALSE;
2030     }
2031
2032     if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2033     {
2034         SetLastError(NTE_BAD_KEY);
2035         return FALSE;
2036     }
2037
2038     if (pCryptKey->dwState == RSAENH_KEYSTATE_IDLE) 
2039         pCryptKey->dwState = RSAENH_KEYSTATE_DECRYPTING;
2040
2041     if (pCryptKey->dwState != RSAENH_KEYSTATE_DECRYPTING)
2042     {
2043         SetLastError(NTE_BAD_DATA);
2044         return FALSE;
2045     }
2046
2047     dwMax=*pdwDataLen;
2048
2049     if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_BLOCK) {
2050         for (i=0, in=pbData; i<*pdwDataLen; i+=pCryptKey->dwBlockLen, in+=pCryptKey->dwBlockLen) {
2051             switch (pCryptKey->dwMode) {
2052                 case CRYPT_MODE_ECB:
2053                     encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out, 
2054                                        RSAENH_DECRYPT);
2055                     break;
2056                 
2057                 case CRYPT_MODE_CBC:
2058                     encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out, 
2059                                        RSAENH_DECRYPT);
2060                     for (j=0; j<pCryptKey->dwBlockLen; j++) out[j] ^= pCryptKey->abChainVector[j];
2061                     memcpy(pCryptKey->abChainVector, in, pCryptKey->dwBlockLen);
2062                     break;
2063
2064                 case CRYPT_MODE_CFB:
2065                     for (j=0; j<pCryptKey->dwBlockLen; j++) {
2066                         encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, 
2067                                            pCryptKey->abChainVector, o, RSAENH_ENCRYPT);
2068                         out[j] = in[j] ^ o[0];
2069                         for (k=0; k<pCryptKey->dwBlockLen-1; k++) 
2070                             pCryptKey->abChainVector[k] = pCryptKey->abChainVector[k+1];
2071                         pCryptKey->abChainVector[k] = in[j];
2072                     }
2073                     break;
2074                     
2075                 default:
2076                     SetLastError(NTE_BAD_ALGID);
2077                     return FALSE;
2078             }
2079             memcpy(in, out, pCryptKey->dwBlockLen);
2080         }
2081         if (Final) *pdwDataLen -= pbData[*pdwDataLen-1]; 
2082
2083     } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_STREAM) {
2084         encrypt_stream_impl(pCryptKey->aiAlgid, &pCryptKey->context, pbData, *pdwDataLen);
2085     } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_RSA) {
2086         if (pCryptKey->aiAlgid == CALG_RSA_SIGN) {
2087             SetLastError(NTE_BAD_KEY);
2088             return FALSE;
2089         }
2090         encrypt_block_impl(pCryptKey->aiAlgid, PK_PRIVATE, &pCryptKey->context, pbData, pbData, RSAENH_DECRYPT);
2091         if (!unpad_data(pbData, pCryptKey->dwBlockLen, pbData, pdwDataLen, dwFlags)) return FALSE;
2092         Final = TRUE;
2093     } else {
2094         SetLastError(NTE_BAD_TYPE);
2095         return FALSE;
2096     } 
2097     
2098     if (Final) setup_key(pCryptKey);
2099
2100     if (is_valid_handle(&handle_table, hHash, RSAENH_MAGIC_HASH)) {
2101         if (*pdwDataLen>dwMax ||
2102             !RSAENH_CPHashData(hProv, hHash, pbData, *pdwDataLen, 0)) return FALSE;
2103     }
2104     
2105     return TRUE;
2106 }
2107
2108 /******************************************************************************
2109  * CPExportKey (RSAENH.@)
2110  *
2111  * Export a key into a binary large object (BLOB).
2112  *
2113  * PARAMS
2114  *  hProv      [I]   Key container from which a key is to be exported.
2115  *  hKey       [I]   Key to be exported.
2116  *  hPubKey    [I]   Key used to encrypt sensitive BLOB data.
2117  *  dwBlobType [I]   SIMPLEBLOB, PUBLICKEYBLOB or PRIVATEKEYBLOB.
2118  *  dwFlags    [I]   Currently none defined.
2119  *  pbData     [O]   Pointer to a buffer where the BLOB will be written to.
2120  *  pdwDataLen [I/O] I: Size of buffer at pbData, O: Size of BLOB
2121  *
2122  * RETURNS
2123  *  Success: TRUE.
2124  *  Failure: FALSE.
2125  */
2126 BOOL WINAPI RSAENH_CPExportKey(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTKEY hPubKey, 
2127                                DWORD dwBlobType, DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2128 {
2129     CRYPTKEY *pCryptKey, *pPubKey;
2130     BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2131     RSAPUBKEY *pRSAPubKey = (RSAPUBKEY*)(pBlobHeader+1);
2132     ALG_ID *pAlgid = (ALG_ID*)(pBlobHeader+1);
2133     DWORD dwDataLen;
2134     
2135     TRACE("(hProv=%08lx, hKey=%08lx, hPubKey=%08lx, dwBlobType=%08x, dwFlags=%08x, pbData=%p,"
2136           "pdwDataLen=%p)\n", hProv, hKey, hPubKey, dwBlobType, dwFlags, pbData, pdwDataLen);
2137     
2138     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2139     {
2140         SetLastError(NTE_BAD_UID);
2141         return FALSE;
2142     }
2143
2144     if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2145     {
2146         SetLastError(NTE_BAD_KEY);
2147         return FALSE;
2148     }
2149
2150     if (dwFlags & CRYPT_SSL2_FALLBACK) {
2151         if (pCryptKey->aiAlgid != CALG_SSL2_MASTER) {
2152             SetLastError(NTE_BAD_KEY);
2153             return FALSE;
2154         }
2155     }
2156     
2157     switch ((BYTE)dwBlobType)
2158     {
2159         case SIMPLEBLOB:
2160             if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pPubKey)){
2161                 SetLastError(NTE_BAD_PUBLIC_KEY); /* FIXME: error_code? */
2162                 return FALSE;
2163             }
2164
2165             if (!(GET_ALG_CLASS(pCryptKey->aiAlgid)&(ALG_CLASS_DATA_ENCRYPT|ALG_CLASS_MSG_ENCRYPT))) {
2166                 SetLastError(NTE_BAD_KEY); /* FIXME: error code? */
2167                 return FALSE;
2168             }
2169
2170             dwDataLen = sizeof(BLOBHEADER) + sizeof(ALG_ID) + pPubKey->dwBlockLen;
2171             if (pbData) {
2172                 if (*pdwDataLen < dwDataLen) {
2173                     SetLastError(ERROR_MORE_DATA);
2174                     *pdwDataLen = dwDataLen;
2175                     return FALSE;
2176                 }
2177
2178                 pBlobHeader->bType = SIMPLEBLOB;
2179                 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2180                 pBlobHeader->reserved = 0;
2181                 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2182
2183                 *pAlgid = pPubKey->aiAlgid;
2184        
2185                 if (!pad_data(pCryptKey->abKeyValue, pCryptKey->dwKeyLen, (BYTE*)(pAlgid+1), 
2186                               pPubKey->dwBlockLen, dwFlags))
2187                 {
2188                     return FALSE;
2189                 }
2190                 
2191                 encrypt_block_impl(pPubKey->aiAlgid, PK_PUBLIC, &pPubKey->context, (BYTE*)(pAlgid+1), 
2192                                    (BYTE*)(pAlgid+1), RSAENH_ENCRYPT); 
2193             }
2194             *pdwDataLen = dwDataLen;
2195             return TRUE;
2196             
2197         case PUBLICKEYBLOB:
2198             if (is_valid_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY)) {
2199                 SetLastError(NTE_BAD_KEY); /* FIXME: error code? */
2200                 return FALSE;
2201             }
2202
2203             if ((pCryptKey->aiAlgid != CALG_RSA_KEYX) && (pCryptKey->aiAlgid != CALG_RSA_SIGN)) {
2204                 SetLastError(NTE_BAD_KEY);
2205                 return FALSE;
2206             }
2207
2208             dwDataLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) + pCryptKey->dwKeyLen;
2209             if (pbData) {
2210                 if (*pdwDataLen < dwDataLen) {
2211                     SetLastError(ERROR_MORE_DATA);
2212                     *pdwDataLen = dwDataLen;
2213                     return FALSE;
2214                 }
2215
2216                 pBlobHeader->bType = PUBLICKEYBLOB;
2217                 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2218                 pBlobHeader->reserved = 0;
2219                 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2220
2221                 pRSAPubKey->magic = RSAENH_MAGIC_RSA1; 
2222                 pRSAPubKey->bitlen = pCryptKey->dwKeyLen << 3;
2223         
2224                 export_public_key_impl((BYTE*)(pRSAPubKey+1), &pCryptKey->context, 
2225                                        pCryptKey->dwKeyLen, &pRSAPubKey->pubexp);
2226             }
2227             *pdwDataLen = dwDataLen;
2228             return TRUE;
2229
2230         case PRIVATEKEYBLOB:
2231             if ((pCryptKey->aiAlgid != CALG_RSA_KEYX) && (pCryptKey->aiAlgid != CALG_RSA_SIGN)) {
2232                 SetLastError(NTE_BAD_KEY);
2233                 return FALSE;
2234             }
2235     
2236             dwDataLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) + 
2237                         2 * pCryptKey->dwKeyLen + 5 * ((pCryptKey->dwKeyLen + 1) >> 1);
2238             if (pbData) {
2239                 if (*pdwDataLen < dwDataLen) {
2240                     SetLastError(ERROR_MORE_DATA);
2241                     *pdwDataLen = dwDataLen;
2242                     return FALSE;
2243                 }
2244                 
2245                 pBlobHeader->bType = PRIVATEKEYBLOB;
2246                 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2247                 pBlobHeader->reserved = 0;
2248                 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2249
2250                 pRSAPubKey->magic = RSAENH_MAGIC_RSA2;
2251                 pRSAPubKey->bitlen = pCryptKey->dwKeyLen << 3;
2252                 
2253                 export_private_key_impl((BYTE*)(pRSAPubKey+1), &pCryptKey->context, 
2254                                         pCryptKey->dwKeyLen, &pRSAPubKey->pubexp);
2255             }
2256             *pdwDataLen = dwDataLen;
2257             return TRUE;
2258             
2259         default:
2260             SetLastError(NTE_BAD_TYPE); /* FIXME: error code? */
2261             return FALSE;
2262     }
2263 }
2264
2265 /******************************************************************************
2266  * CPImportKey (RSAENH.@)
2267  *
2268  * Import a BLOB'ed key into a key container.
2269  *
2270  * PARAMS
2271  *  hProv     [I] Key container into which the key is to be imported.
2272  *  pbData    [I] Pointer to a buffer which holds the BLOB.
2273  *  dwDataLen [I] Length of data in buffer at pbData.
2274  *  hPubKey   [I] Key used to decrypt sensitive BLOB data.
2275  *  dwFlags   [I] Currently none defined.
2276  *  phKey     [O] Handle to the imported key.
2277  *
2278  * RETURNS
2279  *  Success: TRUE.
2280  *  Failure: FALSE.
2281  */
2282 BOOL WINAPI RSAENH_CPImportKey(HCRYPTPROV hProv, CONST BYTE *pbData, DWORD dwDataLen, 
2283                                HCRYPTKEY hPubKey, DWORD dwFlags, HCRYPTKEY *phKey)
2284 {
2285     KEYCONTAINER *pKeyContainer;
2286     CRYPTKEY *pCryptKey, *pPubKey;
2287     CONST BLOBHEADER *pBlobHeader = (CONST BLOBHEADER*)pbData;
2288     CONST RSAPUBKEY *pRSAPubKey = (CONST RSAPUBKEY*)(pBlobHeader+1);
2289     CONST ALG_ID *pAlgid = (CONST ALG_ID*)(pBlobHeader+1);
2290     CONST BYTE *pbKeyStream = (CONST BYTE*)(pAlgid + 1);
2291     ALG_ID algID;
2292     BYTE *pbDecrypted;
2293     DWORD dwKeyLen;
2294     BOOL ret;
2295
2296     TRACE("(hProv=%08lx, pbData=%p, dwDataLen=%d, hPubKey=%08lx, dwFlags=%08x, phKey=%p)\n",
2297         hProv, pbData, dwDataLen, hPubKey, dwFlags, phKey);
2298     
2299     if (!lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER,
2300                        (OBJECTHDR**)&pKeyContainer)) 
2301     {
2302         SetLastError(NTE_BAD_UID);
2303         return FALSE;
2304     }
2305
2306     if (dwDataLen < sizeof(BLOBHEADER) || 
2307         pBlobHeader->bVersion != CUR_BLOB_VERSION ||
2308         pBlobHeader->reserved != 0) 
2309     {
2310         SetLastError(NTE_BAD_DATA);
2311         return FALSE;
2312     }
2313
2314     switch (pBlobHeader->bType)
2315     {
2316         case PRIVATEKEYBLOB:    
2317             if ((dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY)) || 
2318                 (pRSAPubKey->magic != RSAENH_MAGIC_RSA2) ||
2319                 (dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) + 
2320                     (2 * pRSAPubKey->bitlen >> 3) + (5 * ((pRSAPubKey->bitlen+8)>>4)))) 
2321             {
2322                 SetLastError(NTE_BAD_DATA);
2323                 return FALSE;
2324             }
2325     
2326             *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, MAKELONG(0,pRSAPubKey->bitlen), &pCryptKey);
2327             if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
2328             setup_key(pCryptKey);
2329             ret = import_private_key_impl((CONST BYTE*)(pRSAPubKey+1), &pCryptKey->context, 
2330                                            pRSAPubKey->bitlen/8, pRSAPubKey->pubexp);
2331             if (ret) {
2332                 switch (pBlobHeader->aiKeyAlg)
2333                 {
2334                 case AT_SIGNATURE:
2335                 case CALG_RSA_SIGN:
2336                     TRACE("installing signing key\n");
2337                     RSAENH_CPDestroyKey(hProv, pKeyContainer->hSignatureKeyPair);
2338                     copy_handle(&handle_table, *phKey, RSAENH_MAGIC_KEY,
2339                                 &pKeyContainer->hSignatureKeyPair);
2340                     break;
2341                 case AT_KEYEXCHANGE:
2342                 case CALG_RSA_KEYX:
2343                     TRACE("installing key exchange key\n");
2344                     RSAENH_CPDestroyKey(hProv, pKeyContainer->hKeyExchangeKeyPair);
2345                     copy_handle(&handle_table, *phKey, RSAENH_MAGIC_KEY,
2346                                 &pKeyContainer->hKeyExchangeKeyPair);
2347                     break;
2348                 }
2349             }
2350             return ret;
2351                 
2352         case PUBLICKEYBLOB:
2353             if ((dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY)) || 
2354                 (pRSAPubKey->magic != RSAENH_MAGIC_RSA1) ||
2355                 (dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) + (pRSAPubKey->bitlen >> 3))) 
2356             {
2357                 SetLastError(NTE_BAD_DATA);
2358                 return FALSE;
2359             }
2360     
2361             /* Since this is a public key blob, only the public key is
2362              * available, so only signature verification is possible.
2363              */
2364             algID = pBlobHeader->aiKeyAlg;
2365             *phKey = new_key(hProv, algID, MAKELONG(0,pRSAPubKey->bitlen), &pCryptKey); 
2366             if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE; 
2367             setup_key(pCryptKey);
2368             ret = import_public_key_impl((CONST BYTE*)(pRSAPubKey+1), &pCryptKey->context, 
2369                                           pRSAPubKey->bitlen >> 3, pRSAPubKey->pubexp);
2370             if (ret) {
2371                 switch (pBlobHeader->aiKeyAlg)
2372                 {
2373                 case AT_KEYEXCHANGE:
2374                 case CALG_RSA_KEYX:
2375                     TRACE("installing public key\n");
2376                     RSAENH_CPDestroyKey(hProv, pKeyContainer->hKeyExchangeKeyPair);
2377                     copy_handle(&handle_table, *phKey, RSAENH_MAGIC_KEY,
2378                                 &pKeyContainer->hKeyExchangeKeyPair);
2379                     break;
2380                 }
2381             }
2382             return ret;
2383                 
2384         case SIMPLEBLOB:
2385             if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pPubKey) ||
2386                 pPubKey->aiAlgid != CALG_RSA_KEYX) 
2387             {
2388                 SetLastError(NTE_BAD_PUBLIC_KEY); /* FIXME: error code? */
2389                 return FALSE;
2390             }
2391
2392             if (dwDataLen < sizeof(BLOBHEADER)+sizeof(ALG_ID)+pPubKey->dwBlockLen) 
2393             {
2394                 SetLastError(NTE_BAD_DATA); /* FIXME: error code */
2395                 return FALSE;
2396             }
2397
2398             pbDecrypted = HeapAlloc(GetProcessHeap(), 0, pPubKey->dwBlockLen);
2399             if (!pbDecrypted) return FALSE;
2400             encrypt_block_impl(pPubKey->aiAlgid, PK_PRIVATE, &pPubKey->context, pbKeyStream, pbDecrypted, 
2401                                RSAENH_DECRYPT);
2402
2403             dwKeyLen = RSAENH_MAX_KEY_SIZE;
2404             if (!unpad_data(pbDecrypted, pPubKey->dwBlockLen, pbDecrypted, &dwKeyLen, dwFlags)) {
2405                 HeapFree(GetProcessHeap(), 0, pbDecrypted);
2406                 return FALSE;
2407             }
2408             
2409             *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, dwKeyLen<<19, &pCryptKey);
2410             if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
2411             {
2412                 HeapFree(GetProcessHeap(), 0, pbDecrypted);
2413                 return FALSE;
2414             }
2415             memcpy(pCryptKey->abKeyValue, pbDecrypted, dwKeyLen);
2416             HeapFree(GetProcessHeap(), 0, pbDecrypted);
2417             setup_key(pCryptKey);
2418             return TRUE;
2419
2420         default:
2421             SetLastError(NTE_BAD_TYPE); /* FIXME: error code? */
2422             return FALSE;
2423     }
2424 }
2425
2426 /******************************************************************************
2427  * CPGenKey (RSAENH.@)
2428  *
2429  * Generate a key in the key container
2430  *
2431  * PARAMS
2432  *  hProv   [I] Key container for which a key is to be generated.
2433  *  Algid   [I] Crypto algorithm identifier for the key to be generated.
2434  *  dwFlags [I] Upper 16 bits: Binary length of key. Lower 16 bits: Flags. See Notes
2435  *  phKey   [O] Handle to the generated key.
2436  *
2437  * RETURNS
2438  *  Success: TRUE.
2439  *  Failure: FALSE.
2440  *
2441  * FIXME
2442  *  Flags currently not considered.
2443  *
2444  * NOTES
2445  *  Private key-exchange- and signature-keys can be generated with Algid AT_KEYEXCHANGE
2446  *  and AT_SIGNATURE values.
2447  */
2448 BOOL WINAPI RSAENH_CPGenKey(HCRYPTPROV hProv, ALG_ID Algid, DWORD dwFlags, HCRYPTKEY *phKey)
2449 {
2450     KEYCONTAINER *pKeyContainer;
2451     CRYPTKEY *pCryptKey;
2452
2453     TRACE("(hProv=%08lx, aiAlgid=%d, dwFlags=%08x, phKey=%p)\n", hProv, Algid, dwFlags, phKey);
2454
2455     if (!lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER,
2456                        (OBJECTHDR**)&pKeyContainer)) 
2457     {
2458         /* MSDN: hProv not containing valid context handle */
2459         SetLastError(NTE_BAD_UID);
2460         return FALSE;
2461     }
2462     
2463     switch (Algid)
2464     {
2465         case AT_SIGNATURE:
2466         case CALG_RSA_SIGN:
2467             *phKey = new_key(hProv, CALG_RSA_SIGN, dwFlags, &pCryptKey);
2468             if (pCryptKey) { 
2469                 new_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen);
2470                 setup_key(pCryptKey);
2471                 if (Algid == AT_SIGNATURE) {
2472                     RSAENH_CPDestroyKey(hProv, pKeyContainer->hSignatureKeyPair);
2473                     copy_handle(&handle_table, *phKey, RSAENH_MAGIC_KEY,
2474                                 &pKeyContainer->hSignatureKeyPair);
2475                 }
2476             }
2477             break;
2478
2479         case AT_KEYEXCHANGE:
2480         case CALG_RSA_KEYX:
2481             *phKey = new_key(hProv, CALG_RSA_KEYX, dwFlags, &pCryptKey);
2482             if (pCryptKey) { 
2483                 new_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen);
2484                 setup_key(pCryptKey);
2485                 if (Algid == AT_KEYEXCHANGE) {
2486                     RSAENH_CPDestroyKey(hProv, pKeyContainer->hKeyExchangeKeyPair);
2487                     copy_handle(&handle_table, *phKey, RSAENH_MAGIC_KEY,
2488                                 &pKeyContainer->hKeyExchangeKeyPair);
2489                 }
2490             }
2491             break;
2492             
2493         case CALG_RC2:
2494         case CALG_RC4:
2495         case CALG_DES:
2496         case CALG_3DES_112:
2497         case CALG_3DES:
2498         case CALG_PCT1_MASTER:
2499         case CALG_SSL2_MASTER:
2500         case CALG_SSL3_MASTER:
2501         case CALG_TLS1_MASTER:
2502             *phKey = new_key(hProv, Algid, dwFlags, &pCryptKey);
2503             if (pCryptKey) {
2504                 gen_rand_impl(pCryptKey->abKeyValue, RSAENH_MAX_KEY_SIZE);
2505                 switch (Algid) {
2506                     case CALG_SSL3_MASTER:
2507                         pCryptKey->abKeyValue[0] = RSAENH_SSL3_VERSION_MAJOR;
2508                         pCryptKey->abKeyValue[1] = RSAENH_SSL3_VERSION_MINOR;
2509                         break;
2510
2511                     case CALG_TLS1_MASTER:
2512                         pCryptKey->abKeyValue[0] = RSAENH_TLS1_VERSION_MAJOR;
2513                         pCryptKey->abKeyValue[1] = RSAENH_TLS1_VERSION_MINOR;
2514                         break;
2515                 }
2516                 setup_key(pCryptKey);
2517             }
2518             break;
2519             
2520         default:
2521             /* MSDN: Algorithm not supported specified by Algid */
2522             SetLastError(NTE_BAD_ALGID);
2523             return FALSE;
2524     }
2525             
2526     return *phKey != (HCRYPTKEY)INVALID_HANDLE_VALUE;
2527 }
2528
2529 /******************************************************************************
2530  * CPGenRandom (RSAENH.@)
2531  *
2532  * Generate a random byte stream.
2533  *
2534  * PARAMS
2535  *  hProv    [I] Key container that is used to generate random bytes.
2536  *  dwLen    [I] Specifies the number of requested random data bytes.
2537  *  pbBuffer [O] Random bytes will be stored here.
2538  *
2539  * RETURNS
2540  *  Success: TRUE
2541  *  Failure: FALSE
2542  */
2543 BOOL WINAPI RSAENH_CPGenRandom(HCRYPTPROV hProv, DWORD dwLen, BYTE *pbBuffer)
2544 {
2545     TRACE("(hProv=%08lx, dwLen=%d, pbBuffer=%p)\n", hProv, dwLen, pbBuffer);
2546     
2547     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2548     {
2549         /* MSDN: hProv not containing valid context handle */
2550         SetLastError(NTE_BAD_UID);
2551         return FALSE;
2552     }
2553
2554     return gen_rand_impl(pbBuffer, dwLen);
2555 }
2556
2557 /******************************************************************************
2558  * CPGetHashParam (RSAENH.@)
2559  *
2560  * Query parameters of an hash object.
2561  *
2562  * PARAMS
2563  *  hProv      [I]   The kea container, which the hash belongs to.
2564  *  hHash      [I]   The hash object that is to be queried.
2565  *  dwParam    [I]   Specifies the parameter that is to be queried.
2566  *  pbData     [I]   Pointer to the buffer where the parameter value will be stored.
2567  *  pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
2568  *  dwFlags    [I]   None currently defined.
2569  *
2570  * RETURNS
2571  *  Success: TRUE
2572  *  Failure: FALSE
2573  *
2574  * NOTES
2575  *  Valid dwParams are: HP_ALGID, HP_HASHSIZE, HP_HASHVALUE. The hash will be 
2576  *  finalized if HP_HASHVALUE is queried.
2577  */
2578 BOOL WINAPI RSAENH_CPGetHashParam(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwParam, BYTE *pbData, 
2579                                   DWORD *pdwDataLen, DWORD dwFlags) 
2580 {
2581     CRYPTHASH *pCryptHash;
2582         
2583     TRACE("(hProv=%08lx, hHash=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p, dwFlags=%08x)\n",
2584         hProv, hHash, dwParam, pbData, pdwDataLen, dwFlags);
2585     
2586     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2587     {
2588         SetLastError(NTE_BAD_UID);
2589         return FALSE;
2590     }
2591
2592     if (dwFlags)
2593     {
2594         SetLastError(NTE_BAD_FLAGS);
2595         return FALSE;
2596     }
2597     
2598     if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH,
2599                        (OBJECTHDR**)&pCryptHash))
2600     {
2601         SetLastError(NTE_BAD_HASH);
2602         return FALSE;
2603     }
2604
2605     if (!pdwDataLen)
2606     {
2607         SetLastError(ERROR_INVALID_PARAMETER);
2608         return FALSE;
2609     }
2610     
2611     switch (dwParam)
2612     {
2613         case HP_ALGID:
2614             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptHash->aiAlgid, 
2615                               sizeof(ALG_ID));
2616
2617         case HP_HASHSIZE:
2618             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptHash->dwHashSize, 
2619                               sizeof(DWORD));
2620
2621         case HP_HASHVAL:
2622             if (pCryptHash->aiAlgid == CALG_TLS1PRF) {
2623                 return tls1_prf(hProv, pCryptHash->hKey, &pCryptHash->tpPRFParams.blobLabel,
2624                                 &pCryptHash->tpPRFParams.blobSeed, pbData, *pdwDataLen);
2625             }
2626
2627             if ( pbData == NULL ) {
2628                 *pdwDataLen = pCryptHash->dwHashSize;
2629                 return TRUE;
2630             }
2631
2632             if (pCryptHash->dwState == RSAENH_HASHSTATE_IDLE) {
2633                 SetLastError(NTE_BAD_HASH_STATE);
2634                 return FALSE;
2635             }
2636             
2637             if (pbData && (pCryptHash->dwState != RSAENH_HASHSTATE_FINISHED))
2638             {
2639                 finalize_hash(pCryptHash);
2640                 pCryptHash->dwState = RSAENH_HASHSTATE_FINISHED;
2641             }
2642             
2643             return copy_param(pbData, pdwDataLen, (CONST BYTE*)pCryptHash->abHashValue, 
2644                               pCryptHash->dwHashSize);
2645
2646         default:
2647             SetLastError(NTE_BAD_TYPE);
2648             return FALSE;
2649     }
2650 }
2651
2652 /******************************************************************************
2653  * CPSetKeyParam (RSAENH.@)
2654  *
2655  * Set a parameter of a key object
2656  *
2657  * PARAMS
2658  *  hProv   [I] The key container to which the key belongs.
2659  *  hKey    [I] The key for which a parameter is to be set.
2660  *  dwParam [I] Parameter type. See Notes.
2661  *  pbData  [I] Pointer to the parameter value.
2662  *  dwFlags [I] Currently none defined.
2663  *
2664  * RETURNS
2665  *  Success: TRUE.
2666  *  Failure: FALSE.
2667  *
2668  * NOTES:
2669  *  Defined dwParam types are:
2670  *   - KP_MODE: Values MODE_CBC, MODE_ECB, MODE_CFB.
2671  *   - KP_MODE_BITS: Shift width for cipher feedback mode. (Currently ignored by MS CSP's)
2672  *   - KP_PERMISSIONS: Or'ed combination of CRYPT_ENCRYPT, CRYPT_DECRYPT, 
2673  *                     CRYPT_EXPORT, CRYPT_READ, CRYPT_WRITE, CRYPT_MAC
2674  *   - KP_IV: Initialization vector
2675  */
2676 BOOL WINAPI RSAENH_CPSetKeyParam(HCRYPTPROV hProv, HCRYPTKEY hKey, DWORD dwParam, BYTE *pbData, 
2677                                  DWORD dwFlags)
2678 {
2679     CRYPTKEY *pCryptKey;
2680
2681     TRACE("(hProv=%08lx, hKey=%08lx, dwParam=%08x, pbData=%p, dwFlags=%08x)\n", hProv, hKey,
2682           dwParam, pbData, dwFlags);
2683
2684     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2685     {
2686         SetLastError(NTE_BAD_UID);
2687         return FALSE;
2688     }
2689
2690     if (dwFlags) {
2691         SetLastError(NTE_BAD_FLAGS);
2692         return FALSE;
2693     }
2694     
2695     if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2696     {
2697         SetLastError(NTE_BAD_KEY);
2698         return FALSE;
2699     }
2700     
2701     switch (dwParam) {
2702         case KP_MODE:
2703             pCryptKey->dwMode = *(DWORD*)pbData;
2704             return TRUE;
2705
2706         case KP_MODE_BITS:
2707             pCryptKey->dwModeBits = *(DWORD*)pbData;
2708             return TRUE;
2709
2710         case KP_PERMISSIONS:
2711             pCryptKey->dwPermissions = *(DWORD*)pbData;
2712             return TRUE;
2713
2714         case KP_IV:
2715             memcpy(pCryptKey->abInitVector, pbData, pCryptKey->dwBlockLen);
2716             return TRUE;
2717
2718         case KP_SCHANNEL_ALG:
2719             switch (((PSCHANNEL_ALG)pbData)->dwUse) {
2720                 case SCHANNEL_ENC_KEY:
2721                     memcpy(&pCryptKey->siSChannelInfo.saEncAlg, pbData, sizeof(SCHANNEL_ALG));
2722                     break;
2723
2724                 case SCHANNEL_MAC_KEY:
2725                     memcpy(&pCryptKey->siSChannelInfo.saMACAlg, pbData, sizeof(SCHANNEL_ALG));
2726                     break;
2727
2728                 default:
2729                     SetLastError(NTE_FAIL); /* FIXME: error code */
2730                     return FALSE;
2731             }
2732             return TRUE;
2733
2734         case KP_CLIENT_RANDOM:
2735             return copy_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom, (PCRYPT_DATA_BLOB)pbData);
2736             
2737         case KP_SERVER_RANDOM:
2738             return copy_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom, (PCRYPT_DATA_BLOB)pbData);
2739
2740         default:
2741             SetLastError(NTE_BAD_TYPE);
2742             return FALSE;
2743     }
2744 }
2745
2746 /******************************************************************************
2747  * CPGetKeyParam (RSAENH.@)
2748  *
2749  * Query a key parameter.
2750  *
2751  * PARAMS
2752  *  hProv      [I]   The key container, which the key belongs to.
2753  *  hHash      [I]   The key object that is to be queried.
2754  *  dwParam    [I]   Specifies the parameter that is to be queried.
2755  *  pbData     [I]   Pointer to the buffer where the parameter value will be stored.
2756  *  pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
2757  *  dwFlags    [I]   None currently defined.
2758  *
2759  * RETURNS
2760  *  Success: TRUE
2761  *  Failure: FALSE
2762  *
2763  * NOTES
2764  *  Defined dwParam types are:
2765  *   - KP_MODE: Values MODE_CBC, MODE_ECB, MODE_CFB.
2766  *   - KP_MODE_BITS: Shift width for cipher feedback mode. 
2767  *                   (Currently ignored by MS CSP's - always eight)
2768  *   - KP_PERMISSIONS: Or'ed combination of CRYPT_ENCRYPT, CRYPT_DECRYPT, 
2769  *                     CRYPT_EXPORT, CRYPT_READ, CRYPT_WRITE, CRYPT_MAC
2770  *   - KP_IV: Initialization vector.
2771  *   - KP_KEYLEN: Bitwidth of the key.
2772  *   - KP_BLOCKLEN: Size of a block cipher block.
2773  *   - KP_SALT: Salt value.
2774  */
2775 BOOL WINAPI RSAENH_CPGetKeyParam(HCRYPTPROV hProv, HCRYPTKEY hKey, DWORD dwParam, BYTE *pbData, 
2776                                  DWORD *pdwDataLen, DWORD dwFlags)
2777 {
2778     CRYPTKEY *pCryptKey;
2779     DWORD dwBitLen;
2780         
2781     TRACE("(hProv=%08lx, hKey=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p dwFlags=%08x)\n",
2782           hProv, hKey, dwParam, pbData, pdwDataLen, dwFlags);
2783
2784     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2785     {
2786         SetLastError(NTE_BAD_UID);
2787         return FALSE;
2788     }
2789
2790     if (dwFlags) {
2791         SetLastError(NTE_BAD_FLAGS);
2792         return FALSE;
2793     }
2794
2795     if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2796     {
2797         SetLastError(NTE_BAD_KEY);
2798         return FALSE;
2799     }
2800
2801     switch (dwParam) 
2802     {
2803         case KP_IV:
2804             return copy_param(pbData, pdwDataLen, (CONST BYTE*)pCryptKey->abInitVector, 
2805                               pCryptKey->dwBlockLen);
2806         
2807         case KP_SALT:
2808             return copy_param(pbData, pdwDataLen, 
2809                     (CONST BYTE*)&pCryptKey->abKeyValue[pCryptKey->dwKeyLen], pCryptKey->dwSaltLen);
2810         
2811         case KP_KEYLEN:
2812             dwBitLen = pCryptKey->dwKeyLen << 3;
2813             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwBitLen, sizeof(DWORD));
2814         
2815         case KP_BLOCKLEN:
2816             dwBitLen = pCryptKey->dwBlockLen << 3;
2817             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwBitLen, sizeof(DWORD));
2818     
2819         case KP_MODE:
2820             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptKey->dwMode, sizeof(DWORD));
2821
2822         case KP_MODE_BITS:
2823             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptKey->dwModeBits, 
2824                               sizeof(DWORD));
2825     
2826         case KP_PERMISSIONS:
2827             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptKey->dwPermissions, 
2828                               sizeof(DWORD));
2829
2830         case KP_ALGID:
2831             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptKey->aiAlgid, sizeof(DWORD));
2832             
2833         default:
2834             SetLastError(NTE_BAD_TYPE);
2835             return FALSE;
2836     }
2837 }
2838                         
2839 /******************************************************************************
2840  * CPGetProvParam (RSAENH.@)
2841  *
2842  * Query a CSP parameter.
2843  *
2844  * PARAMS
2845  *  hProv      [I]   The key container that is to be queried.
2846  *  dwParam    [I]   Specifies the parameter that is to be queried.
2847  *  pbData     [I]   Pointer to the buffer where the parameter value will be stored.
2848  *  pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
2849  *  dwFlags    [I]   CRYPT_FIRST: Start enumeration (for PP_ENUMALGS{_EX}).
2850  *
2851  * RETURNS
2852  *  Success: TRUE
2853  *  Failure: FALSE
2854  * NOTES:
2855  *  Defined dwParam types:
2856  *   - PP_CONTAINER: Name of the key container.
2857  *   - PP_NAME: Name of the cryptographic service provider.
2858  *   - PP_SIG_KEYSIZE_INC: RSA signature keywidth granularity in bits.
2859  *   - PP_KEYX_KEYSIZE_INC: RSA key-exchange keywidth granularity in bits.
2860  *   - PP_ENUMALGS{_EX}: Query provider capabilities.
2861  */
2862 BOOL WINAPI RSAENH_CPGetProvParam(HCRYPTPROV hProv, DWORD dwParam, BYTE *pbData, 
2863                                   DWORD *pdwDataLen, DWORD dwFlags)
2864 {
2865     KEYCONTAINER *pKeyContainer;
2866     PROV_ENUMALGS provEnumalgs;
2867     DWORD dwTemp;
2868     CHAR szRSABase[MAX_PATH];
2869     HKEY hKey, hRootKey;
2870    
2871     /* This is for dwParam 41, which does not seem to be documented
2872      * on MSDN. IE6 SP1 asks for it in the 'About' dialog, however.
2873      * Returning this BLOB seems to satisfy IE. The marked 0x00 seem 
2874      * to be 'don't care's. If you know anything more specific about
2875      * provider parameter 41, please report to wine-devel@winehq.org */
2876     static CONST BYTE abWTF[96] = { 
2877         0xb0, 0x25,     0x63,     0x86, 0x9c, 0xab,     0xb6,     0x37, 
2878         0xe8, 0x82, /**/0x00,/**/ 0x72, 0x06, 0xb2, /**/0x00,/**/ 0x3b, 
2879         0x60, 0x35, /**/0x00,/**/ 0x3b, 0x88, 0xce, /**/0x00,/**/ 0x82, 
2880         0xbc, 0x7a, /**/0x00,/**/ 0xb7, 0x4f, 0x7e, /**/0x00,/**/ 0xde, 
2881         0x92, 0xf1, /**/0x00,/**/ 0x83, 0xea, 0x5e, /**/0x00,/**/ 0xc8, 
2882         0x12, 0x1e,     0xd4,     0x06, 0xf7, 0x66, /**/0x00,/**/ 0x01, 
2883         0x29, 0xa4, /**/0x00,/**/ 0xf8, 0x24, 0x0c, /**/0x00,/**/ 0x33, 
2884         0x06, 0x80, /**/0x00,/**/ 0x02, 0x46, 0x0b, /**/0x00,/**/ 0x6d, 
2885         0x5b, 0xca, /**/0x00,/**/ 0x9a, 0x10, 0xf0, /**/0x00,/**/ 0x05, 
2886         0x19, 0xd0, /**/0x00,/**/ 0x2c, 0xf6, 0x27, /**/0x00,/**/ 0xaa, 
2887         0x7c, 0x6f, /**/0x00,/**/ 0xb9, 0xd8, 0x72, /**/0x00,/**/ 0x03, 
2888         0xf3, 0x81, /**/0x00,/**/ 0xfa, 0xe8, 0x26, /**/0x00,/**/ 0xca 
2889     };
2890
2891     TRACE("(hProv=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p, dwFlags=%08x)\n",
2892            hProv, dwParam, pbData, pdwDataLen, dwFlags);
2893
2894     if (!pdwDataLen) {
2895         SetLastError(ERROR_INVALID_PARAMETER);
2896         return FALSE;
2897     }
2898     
2899     if (!lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER,
2900                        (OBJECTHDR**)&pKeyContainer)) 
2901     {
2902         /* MSDN: hProv not containing valid context handle */
2903         SetLastError(NTE_BAD_UID);
2904         return FALSE;
2905     }
2906
2907     switch (dwParam) 
2908     {
2909         case PP_CONTAINER:
2910         case PP_UNIQUE_CONTAINER:/* MSDN says we can return the same value as PP_CONTAINER */
2911             return copy_param(pbData, pdwDataLen, (CONST BYTE*)pKeyContainer->szName, 
2912                               strlen(pKeyContainer->szName)+1);
2913
2914         case PP_NAME:
2915             return copy_param(pbData, pdwDataLen, (CONST BYTE*)pKeyContainer->szProvName, 
2916                               strlen(pKeyContainer->szProvName)+1);
2917
2918         case PP_PROVTYPE:
2919             dwTemp = PROV_RSA_FULL;
2920             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwTemp, sizeof(dwTemp));
2921
2922         case PP_KEYSPEC:
2923             dwTemp = AT_SIGNATURE | AT_KEYEXCHANGE;
2924             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwTemp, sizeof(dwTemp));
2925
2926         case PP_KEYSET_TYPE:
2927             dwTemp = pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET;
2928             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwTemp, sizeof(dwTemp));
2929
2930         case PP_KEYSTORAGE:
2931             dwTemp = CRYPT_SEC_DESCR;
2932             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwTemp, sizeof(dwTemp));
2933
2934         case PP_SIG_KEYSIZE_INC:
2935         case PP_KEYX_KEYSIZE_INC:
2936             dwTemp = 8;
2937             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwTemp, sizeof(dwTemp));
2938
2939         case PP_IMPTYPE:
2940             dwTemp = CRYPT_IMPL_SOFTWARE;
2941             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwTemp, sizeof(dwTemp));
2942
2943         case PP_VERSION:
2944             dwTemp = 0x00000200;
2945             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwTemp, sizeof(dwTemp));
2946             
2947         case PP_ENUMCONTAINERS:
2948             if ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) pKeyContainer->dwEnumContainersCtr = 0;
2949
2950             if (!pbData) {
2951                 *pdwDataLen = (DWORD)MAX_PATH + 1;
2952                 return TRUE;
2953             }
2954  
2955             sprintf(szRSABase, RSAENH_REGKEY, "");
2956
2957             if (dwFlags & CRYPT_MACHINE_KEYSET) {
2958                 hRootKey = HKEY_LOCAL_MACHINE;
2959             } else {
2960                 hRootKey = HKEY_CURRENT_USER;
2961             }
2962
2963             if (RegOpenKeyExA(hRootKey, szRSABase, 0, KEY_READ, &hKey) != ERROR_SUCCESS)
2964             {
2965                 SetLastError(ERROR_NO_MORE_ITEMS);
2966                 return FALSE;
2967             }
2968
2969             dwTemp = *pdwDataLen;
2970             switch (RegEnumKeyExA(hKey, pKeyContainer->dwEnumContainersCtr, (LPSTR)pbData, &dwTemp,
2971                     NULL, NULL, NULL, NULL))
2972             {
2973                 case ERROR_MORE_DATA:
2974                     *pdwDataLen = (DWORD)MAX_PATH + 1;
2975  
2976                 case ERROR_SUCCESS:
2977                     pKeyContainer->dwEnumContainersCtr++;
2978                     RegCloseKey(hKey);
2979                     return TRUE;
2980
2981                 case ERROR_NO_MORE_ITEMS:
2982                 default:
2983                     SetLastError(ERROR_NO_MORE_ITEMS);
2984                     RegCloseKey(hKey);
2985                     return FALSE;
2986             }
2987  
2988         case PP_ENUMALGS:
2989         case PP_ENUMALGS_EX:
2990             if (((pKeyContainer->dwEnumAlgsCtr >= RSAENH_MAX_ENUMALGS-1) ||
2991                  (!aProvEnumAlgsEx[pKeyContainer->dwPersonality]
2992                    [pKeyContainer->dwEnumAlgsCtr+1].aiAlgid)) && 
2993                 ((dwFlags & CRYPT_FIRST) != CRYPT_FIRST))
2994             {
2995                 SetLastError(ERROR_NO_MORE_ITEMS);
2996                 return FALSE;
2997             }
2998
2999             if (dwParam == PP_ENUMALGS) {    
3000                 if (pbData && (*pdwDataLen >= sizeof(PROV_ENUMALGS))) 
3001                     pKeyContainer->dwEnumAlgsCtr = ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) ? 
3002                         0 : pKeyContainer->dwEnumAlgsCtr+1;
3003             
3004                 provEnumalgs.aiAlgid = aProvEnumAlgsEx
3005                     [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].aiAlgid;
3006                 provEnumalgs.dwBitLen = aProvEnumAlgsEx
3007                     [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].dwDefaultLen;
3008                 provEnumalgs.dwNameLen = aProvEnumAlgsEx
3009                     [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].dwNameLen;
3010                 memcpy(provEnumalgs.szName, aProvEnumAlgsEx
3011                        [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].szName, 
3012                        20*sizeof(CHAR));
3013             
3014                 return copy_param(pbData, pdwDataLen, (CONST BYTE*)&provEnumalgs, 
3015                                   sizeof(PROV_ENUMALGS));
3016             } else {
3017                 if (pbData && (*pdwDataLen >= sizeof(PROV_ENUMALGS_EX))) 
3018                     pKeyContainer->dwEnumAlgsCtr = ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) ? 
3019                         0 : pKeyContainer->dwEnumAlgsCtr+1;
3020             
3021                 return copy_param(pbData, pdwDataLen, 
3022                                   (CONST BYTE*)&aProvEnumAlgsEx
3023                                       [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr], 
3024                                   sizeof(PROV_ENUMALGS_EX));
3025             }
3026
3027         case 41: /* Undocumented. Asked for by IE About dialog */
3028             return copy_param(pbData, pdwDataLen, abWTF, sizeof(abWTF));
3029
3030         default:
3031             /* MSDN: Unknown parameter number in dwParam */
3032             SetLastError(NTE_BAD_TYPE);
3033             return FALSE;
3034     }
3035 }
3036
3037 /******************************************************************************
3038  * CPDeriveKey (RSAENH.@)
3039  *
3040  * Derives a key from a hash value.
3041  *
3042  * PARAMS
3043  *  hProv     [I] Key container for which a key is to be generated.
3044  *  Algid     [I] Crypto algorithm identifier for the key to be generated.
3045  *  hBaseData [I] Hash from whose value the key will be derived.
3046  *  dwFlags   [I] See Notes.
3047  *  phKey     [O] The generated key.
3048  *
3049  * RETURNS
3050  *  Success: TRUE
3051  *  Failure: FALSE
3052  *
3053  * NOTES
3054  *  Defined flags:
3055  *   - CRYPT_EXPORTABLE: Key can be exported.
3056  *   - CRYPT_NO_SALT: No salt is used for 40 bit keys.
3057  *   - CRYPT_CREATE_SALT: Use remaining bits as salt value.
3058  */
3059 BOOL WINAPI RSAENH_CPDeriveKey(HCRYPTPROV hProv, ALG_ID Algid, HCRYPTHASH hBaseData, 
3060                                DWORD dwFlags, HCRYPTKEY *phKey)
3061 {
3062     CRYPTKEY *pCryptKey, *pMasterKey;
3063     CRYPTHASH *pCryptHash;
3064     BYTE abHashValue[RSAENH_MAX_HASH_SIZE*2];
3065     DWORD dwLen;
3066     
3067     TRACE("(hProv=%08lx, Algid=%d, hBaseData=%08lx, dwFlags=%08x phKey=%p)\n", hProv, Algid,
3068            hBaseData, dwFlags, phKey);
3069     
3070     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3071     {
3072         SetLastError(NTE_BAD_UID);
3073         return FALSE;
3074     }
3075
3076     if (!lookup_handle(&handle_table, hBaseData, RSAENH_MAGIC_HASH,
3077                        (OBJECTHDR**)&pCryptHash))
3078     {
3079         SetLastError(NTE_BAD_HASH);
3080         return FALSE;
3081     }
3082
3083     if (!phKey)
3084     {
3085         SetLastError(ERROR_INVALID_PARAMETER);
3086         return FALSE;
3087     }
3088
3089     switch (GET_ALG_CLASS(Algid))
3090     {
3091         case ALG_CLASS_DATA_ENCRYPT:
3092             *phKey = new_key(hProv, Algid, dwFlags, &pCryptKey);
3093             if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
3094
3095             /* 
3096              * We derive the key material from the hash.
3097              * If the hash value is not large enough for the claimed key, we have to construct
3098              * a larger binary value based on the hash. This is documented in MSDN: CryptDeriveKey.
3099              */
3100             dwLen = RSAENH_MAX_HASH_SIZE;
3101             RSAENH_CPGetHashParam(pCryptHash->hProv, hBaseData, HP_HASHVAL, abHashValue, &dwLen, 0);
3102     
3103             if (dwLen < pCryptKey->dwKeyLen) {
3104                 BYTE pad1[RSAENH_HMAC_DEF_PAD_LEN], pad2[RSAENH_HMAC_DEF_PAD_LEN];
3105                 BYTE old_hashval[RSAENH_MAX_HASH_SIZE];
3106                 DWORD i;
3107
3108                 memcpy(old_hashval, pCryptHash->abHashValue, RSAENH_MAX_HASH_SIZE);
3109             
3110                 for (i=0; i<RSAENH_HMAC_DEF_PAD_LEN; i++) {
3111                     pad1[i] = RSAENH_HMAC_DEF_IPAD_CHAR ^ (i<dwLen ? abHashValue[i] : 0);
3112                     pad2[i] = RSAENH_HMAC_DEF_OPAD_CHAR ^ (i<dwLen ? abHashValue[i] : 0);
3113                 }
3114                 
3115                 init_hash(pCryptHash);
3116                 update_hash(pCryptHash, pad1, RSAENH_HMAC_DEF_PAD_LEN);
3117                 finalize_hash(pCryptHash);
3118                 memcpy(abHashValue, pCryptHash->abHashValue, pCryptHash->dwHashSize);
3119
3120                 init_hash(pCryptHash);
3121                 update_hash(pCryptHash, pad2, RSAENH_HMAC_DEF_PAD_LEN);
3122                 finalize_hash(pCryptHash);
3123                 memcpy(abHashValue+pCryptHash->dwHashSize, pCryptHash->abHashValue, 
3124                        pCryptHash->dwHashSize);
3125
3126                 memcpy(pCryptHash->abHashValue, old_hashval, RSAENH_MAX_HASH_SIZE);
3127             }
3128     
3129             memcpy(pCryptKey->abKeyValue, abHashValue, 
3130                    RSAENH_MIN(pCryptKey->dwKeyLen, sizeof(pCryptKey->abKeyValue)));
3131             break;
3132
3133         case ALG_CLASS_MSG_ENCRYPT:
3134             if (!lookup_handle(&handle_table, pCryptHash->hKey, RSAENH_MAGIC_KEY,
3135                                (OBJECTHDR**)&pMasterKey)) 
3136             {
3137                 SetLastError(NTE_FAIL); /* FIXME error code */
3138                 return FALSE;
3139             }
3140                 
3141             switch (Algid) 
3142             {
3143                 /* See RFC 2246, chapter 6.3 Key calculation */
3144                 case CALG_SCHANNEL_ENC_KEY:
3145                     *phKey = new_key(hProv, pMasterKey->siSChannelInfo.saEncAlg.Algid, 
3146                                      MAKELONG(LOWORD(dwFlags),pMasterKey->siSChannelInfo.saEncAlg.cBits),
3147                                      &pCryptKey);
3148                     if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
3149                     memcpy(pCryptKey->abKeyValue, 
3150                            pCryptHash->abHashValue + (
3151                                2 * (pMasterKey->siSChannelInfo.saMACAlg.cBits / 8) +
3152                                ((dwFlags & CRYPT_SERVER) ? 
3153                                    (pMasterKey->siSChannelInfo.saEncAlg.cBits / 8) : 0)),
3154                            pMasterKey->siSChannelInfo.saEncAlg.cBits / 8);
3155                     memcpy(pCryptKey->abInitVector,
3156                            pCryptHash->abHashValue + (
3157                                2 * (pMasterKey->siSChannelInfo.saMACAlg.cBits / 8) +
3158                                2 * (pMasterKey->siSChannelInfo.saEncAlg.cBits / 8) +
3159                                ((dwFlags & CRYPT_SERVER) ? pCryptKey->dwBlockLen : 0)),
3160                            pCryptKey->dwBlockLen);
3161                     break;
3162                     
3163                 case CALG_SCHANNEL_MAC_KEY:
3164                     *phKey = new_key(hProv, Algid, 
3165                                      MAKELONG(LOWORD(dwFlags),pMasterKey->siSChannelInfo.saMACAlg.cBits),
3166                                      &pCryptKey);
3167                     if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
3168                     memcpy(pCryptKey->abKeyValue,
3169                            pCryptHash->abHashValue + ((dwFlags & CRYPT_SERVER) ? 
3170                                pMasterKey->siSChannelInfo.saMACAlg.cBits / 8 : 0),
3171                            pMasterKey->siSChannelInfo.saMACAlg.cBits / 8);
3172                     break;
3173                     
3174                 default:
3175                     SetLastError(NTE_BAD_ALGID);
3176                     return FALSE;
3177             }
3178             break;
3179
3180         default:
3181             SetLastError(NTE_BAD_ALGID);
3182             return FALSE;
3183     }
3184
3185     setup_key(pCryptKey);
3186     return TRUE;    
3187 }
3188
3189 /******************************************************************************
3190  * CPGetUserKey (RSAENH.@)
3191  *
3192  * Returns a handle to the user's private key-exchange- or signature-key.
3193  *
3194  * PARAMS
3195  *  hProv     [I] The key container from which a user key is requested.
3196  *  dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
3197  *  phUserKey [O] Handle to the requested key or INVALID_HANDLE_VALUE in case of failure.
3198  *
3199  * RETURNS
3200  *  Success: TRUE.
3201  *  Failure: FALSE.
3202  *
3203  * NOTE
3204  *  A newly created key container does not contain private user key. Create them with CPGenKey.
3205  */
3206 BOOL WINAPI RSAENH_CPGetUserKey(HCRYPTPROV hProv, DWORD dwKeySpec, HCRYPTKEY *phUserKey)
3207 {
3208     KEYCONTAINER *pKeyContainer;
3209
3210     TRACE("(hProv=%08lx, dwKeySpec=%08x, phUserKey=%p)\n", hProv, dwKeySpec, phUserKey);
3211     
3212     if (!lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER,
3213                        (OBJECTHDR**)&pKeyContainer)) 
3214     {
3215         /* MSDN: hProv not containing valid context handle */
3216         SetLastError(NTE_BAD_UID);
3217         return FALSE;
3218     }
3219
3220     switch (dwKeySpec)
3221     {
3222         case AT_KEYEXCHANGE:
3223             copy_handle(&handle_table, pKeyContainer->hKeyExchangeKeyPair, RSAENH_MAGIC_KEY, 
3224                         phUserKey);
3225             break;
3226
3227         case AT_SIGNATURE:
3228             copy_handle(&handle_table, pKeyContainer->hSignatureKeyPair, RSAENH_MAGIC_KEY, 
3229                         phUserKey);
3230             break;
3231
3232         default:
3233             *phUserKey = (HCRYPTKEY)INVALID_HANDLE_VALUE;
3234     }
3235
3236     if (*phUserKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
3237     {
3238         /* MSDN: dwKeySpec parameter specifies nonexistent key */
3239         SetLastError(NTE_NO_KEY);
3240         return FALSE;
3241     }
3242
3243     return TRUE;
3244 }
3245
3246 /******************************************************************************
3247  * CPHashData (RSAENH.@)
3248  *
3249  * Updates a hash object with the given data.
3250  *
3251  * PARAMS
3252  *  hProv     [I] Key container to which the hash object belongs.
3253  *  hHash     [I] Hash object which is to be updated.
3254  *  pbData    [I] Pointer to data with which the hash object is to be updated.
3255  *  dwDataLen [I] Length of the data.
3256  *  dwFlags   [I] Currently none defined.
3257  *
3258  * RETURNS
3259  *  Success: TRUE.
3260  *  Failure: FALSE.
3261  *
3262  * NOTES
3263  *  The actual hash value is queried with CPGetHashParam, which will finalize 
3264  *  the hash. Updating a finalized hash will fail with a last error NTE_BAD_HASH_STATE.
3265  */
3266 BOOL WINAPI RSAENH_CPHashData(HCRYPTPROV hProv, HCRYPTHASH hHash, CONST BYTE *pbData, 
3267                               DWORD dwDataLen, DWORD dwFlags)
3268 {
3269     CRYPTHASH *pCryptHash;
3270         
3271     TRACE("(hProv=%08lx, hHash=%08lx, pbData=%p, dwDataLen=%d, dwFlags=%08x)\n",
3272           hProv, hHash, pbData, dwDataLen, dwFlags);
3273
3274     if (dwFlags)
3275     {
3276         SetLastError(NTE_BAD_FLAGS);
3277         return FALSE;
3278     }
3279
3280     if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH,
3281                        (OBJECTHDR**)&pCryptHash))
3282     {
3283         SetLastError(NTE_BAD_HASH);
3284         return FALSE;
3285     }
3286
3287     if (!get_algid_info(hProv, pCryptHash->aiAlgid) || pCryptHash->aiAlgid == CALG_SSL3_SHAMD5)
3288     {
3289         SetLastError(NTE_BAD_ALGID);
3290         return FALSE;
3291     }
3292     
3293     if (pCryptHash->dwState == RSAENH_HASHSTATE_IDLE)
3294         pCryptHash->dwState = RSAENH_HASHSTATE_HASHING;
3295     
3296     if (pCryptHash->dwState != RSAENH_HASHSTATE_HASHING)
3297     {
3298         SetLastError(NTE_BAD_HASH_STATE);
3299         return FALSE;
3300     }
3301
3302     update_hash(pCryptHash, pbData, dwDataLen);
3303     return TRUE;
3304 }
3305
3306 /******************************************************************************
3307  * CPHashSessionKey (RSAENH.@)
3308  *
3309  * Updates a hash object with the binary representation of a symmetric key.
3310  *
3311  * PARAMS
3312  *  hProv     [I] Key container to which the hash object belongs.
3313  *  hHash     [I] Hash object which is to be updated.
3314  *  hKey      [I] The symmetric key, whose binary value will be added to the hash.
3315  *  dwFlags   [I] CRYPT_LITTLE_ENDIAN, if the binary key value shall be interpreted as little endian.
3316  *
3317  * RETURNS
3318  *  Success: TRUE.
3319  *  Failure: FALSE.
3320  */
3321 BOOL WINAPI RSAENH_CPHashSessionKey(HCRYPTPROV hProv, HCRYPTHASH hHash, HCRYPTKEY hKey, 
3322                                     DWORD dwFlags)
3323 {
3324     BYTE abKeyValue[RSAENH_MAX_KEY_SIZE], bTemp;
3325     CRYPTKEY *pKey;
3326     DWORD i;
3327
3328     TRACE("(hProv=%08lx, hHash=%08lx, hKey=%08lx, dwFlags=%08x)\n", hProv, hHash, hKey, dwFlags);
3329
3330     if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pKey) ||
3331         (GET_ALG_CLASS(pKey->aiAlgid) != ALG_CLASS_DATA_ENCRYPT)) 
3332     {
3333         SetLastError(NTE_BAD_KEY);
3334         return FALSE;
3335     }
3336
3337     if (dwFlags & ~CRYPT_LITTLE_ENDIAN) {
3338         SetLastError(NTE_BAD_FLAGS);
3339         return FALSE;
3340     }
3341
3342     memcpy(abKeyValue, pKey->abKeyValue, pKey->dwKeyLen);
3343     if (!(dwFlags & CRYPT_LITTLE_ENDIAN)) {
3344         for (i=0; i<pKey->dwKeyLen/2; i++) {
3345             bTemp = abKeyValue[i];
3346             abKeyValue[i] = abKeyValue[pKey->dwKeyLen-i-1];
3347             abKeyValue[pKey->dwKeyLen-i-1] = bTemp;
3348         }
3349     }
3350
3351     return RSAENH_CPHashData(hProv, hHash, abKeyValue, pKey->dwKeyLen, 0);
3352 }
3353
3354 /******************************************************************************
3355  * CPReleaseContext (RSAENH.@)
3356  *
3357  * Release a key container.
3358  *
3359  * PARAMS
3360  *  hProv   [I] Key container to be released.
3361  *  dwFlags [I] Currently none defined.
3362  *
3363  * RETURNS
3364  *  Success: TRUE
3365  *  Failure: FALSE
3366  */
3367 BOOL WINAPI RSAENH_CPReleaseContext(HCRYPTPROV hProv, DWORD dwFlags)
3368 {
3369     TRACE("(hProv=%08lx, dwFlags=%08x)\n", hProv, dwFlags);
3370
3371     if (!release_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3372     {
3373         /* MSDN: hProv not containing valid context handle */
3374         SetLastError(NTE_BAD_UID);
3375         return FALSE;
3376     }
3377
3378     if (dwFlags) {
3379         SetLastError(NTE_BAD_FLAGS);
3380         return FALSE;
3381     }
3382     
3383     return TRUE;
3384 }
3385
3386 /******************************************************************************
3387  * CPSetHashParam (RSAENH.@)
3388  * 
3389  * Set a parameter of a hash object
3390  *
3391  * PARAMS
3392  *  hProv   [I] The key container to which the key belongs.
3393  *  hHash   [I] The hash object for which a parameter is to be set.
3394  *  dwParam [I] Parameter type. See Notes.
3395  *  pbData  [I] Pointer to the parameter value.
3396  *  dwFlags [I] Currently none defined.
3397  *
3398  * RETURNS
3399  *  Success: TRUE.
3400  *  Failure: FALSE.
3401  *
3402  * NOTES
3403  *  Currently only the HP_HMAC_INFO dwParam type is defined. 
3404  *  The HMAC_INFO struct will be deep copied into the hash object.
3405  *  See Internet RFC 2104 for details on the HMAC algorithm.
3406  */
3407 BOOL WINAPI RSAENH_CPSetHashParam(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwParam, 
3408                                   BYTE *pbData, DWORD dwFlags)
3409 {
3410     CRYPTHASH *pCryptHash;
3411     CRYPTKEY *pCryptKey;
3412     int i;
3413
3414     TRACE("(hProv=%08lx, hHash=%08lx, dwParam=%08x, pbData=%p, dwFlags=%08x)\n",
3415            hProv, hHash, dwParam, pbData, dwFlags);
3416
3417     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3418     {
3419         SetLastError(NTE_BAD_UID);
3420         return FALSE;
3421     }
3422
3423     if (dwFlags) {
3424         SetLastError(NTE_BAD_FLAGS);
3425         return FALSE;
3426     }
3427     
3428     if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH,
3429                        (OBJECTHDR**)&pCryptHash))
3430     {
3431         SetLastError(NTE_BAD_HASH);
3432         return FALSE;
3433     }
3434     
3435     switch (dwParam) {
3436         case HP_HMAC_INFO:
3437             free_hmac_info(pCryptHash->pHMACInfo);
3438             if (!copy_hmac_info(&pCryptHash->pHMACInfo, (PHMAC_INFO)pbData)) return FALSE;
3439
3440             if (!lookup_handle(&handle_table, pCryptHash->hKey, RSAENH_MAGIC_KEY, 
3441                                (OBJECTHDR**)&pCryptKey)) 
3442             {
3443                 SetLastError(NTE_FAIL); /* FIXME: correct error code? */
3444                 return FALSE;
3445             }
3446
3447             for (i=0; i<RSAENH_MIN(pCryptKey->dwKeyLen,pCryptHash->pHMACInfo->cbInnerString); i++) {
3448                 pCryptHash->pHMACInfo->pbInnerString[i] ^= pCryptKey->abKeyValue[i];
3449             }
3450             for (i=0; i<RSAENH_MIN(pCryptKey->dwKeyLen,pCryptHash->pHMACInfo->cbOuterString); i++) {
3451                 pCryptHash->pHMACInfo->pbOuterString[i] ^= pCryptKey->abKeyValue[i];
3452             }
3453             
3454             init_hash(pCryptHash);
3455             return TRUE;
3456
3457         case HP_HASHVAL:
3458             memcpy(pCryptHash->abHashValue, pbData, pCryptHash->dwHashSize);
3459             pCryptHash->dwState = RSAENH_HASHSTATE_FINISHED;
3460             return TRUE;
3461            
3462         case HP_TLS1PRF_SEED:
3463             return copy_data_blob(&pCryptHash->tpPRFParams.blobSeed, (PCRYPT_DATA_BLOB)pbData);
3464
3465         case HP_TLS1PRF_LABEL:
3466             return copy_data_blob(&pCryptHash->tpPRFParams.blobLabel, (PCRYPT_DATA_BLOB)pbData);
3467             
3468         default:
3469             SetLastError(NTE_BAD_TYPE);
3470             return FALSE;
3471     }
3472 }
3473
3474 /******************************************************************************
3475  * CPSetProvParam (RSAENH.@)
3476  */
3477 BOOL WINAPI RSAENH_CPSetProvParam(HCRYPTPROV hProv, DWORD dwParam, BYTE *pbData, DWORD dwFlags)
3478 {
3479     FIXME("(stub)\n");
3480     return FALSE;
3481 }
3482
3483 /******************************************************************************
3484  * CPSignHash (RSAENH.@)
3485  *
3486  * Sign a hash object
3487  *
3488  * PARAMS
3489  *  hProv        [I]   The key container, to which the hash object belongs.
3490  *  hHash        [I]   The hash object to be signed.
3491  *  dwKeySpec    [I]   AT_SIGNATURE or AT_KEYEXCHANGE: Key used to generate the signature.
3492  *  sDescription [I]   Should be NULL for security reasons. 
3493  *  dwFlags      [I]   0, CRYPT_NOHASHOID or CRYPT_X931_FORMAT: Format of the signature.
3494  *  pbSignature  [O]   Buffer, to which the signature will be stored. May be NULL to query SigLen.
3495  *  pdwSigLen    [I/O] Size of the buffer (in), Length of the signature (out)
3496  *
3497  * RETURNS
3498  *  Success: TRUE
3499  *  Failure: FALSE
3500  */
3501 BOOL WINAPI RSAENH_CPSignHash(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwKeySpec, 
3502                               LPCWSTR sDescription, DWORD dwFlags, BYTE *pbSignature, 
3503                               DWORD *pdwSigLen)
3504 {
3505     HCRYPTKEY hCryptKey;
3506     CRYPTKEY *pCryptKey;
3507     DWORD dwHashLen;
3508     BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
3509     ALG_ID aiAlgid;
3510
3511     TRACE("(hProv=%08lx, hHash=%08lx, dwKeySpec=%08x, sDescription=%s, dwFlags=%08x, "
3512         "pbSignature=%p, pdwSigLen=%p)\n", hProv, hHash, dwKeySpec, debugstr_w(sDescription),
3513         dwFlags, pbSignature, pdwSigLen);
3514
3515     if (dwFlags & ~(CRYPT_NOHASHOID|CRYPT_X931_FORMAT)) {
3516         SetLastError(NTE_BAD_FLAGS);
3517         return FALSE;
3518     }
3519     
3520     if (!RSAENH_CPGetUserKey(hProv, dwKeySpec, &hCryptKey)) return FALSE;
3521             
3522     if (!lookup_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY,
3523                        (OBJECTHDR**)&pCryptKey))
3524     {
3525         SetLastError(NTE_NO_KEY);
3526         return FALSE;
3527     }
3528
3529     if (!pbSignature) {
3530         *pdwSigLen = pCryptKey->dwKeyLen;
3531         return TRUE;
3532     }
3533     if (pCryptKey->dwKeyLen > *pdwSigLen)
3534     {
3535         SetLastError(ERROR_MORE_DATA);
3536         *pdwSigLen = pCryptKey->dwKeyLen;
3537         return FALSE;
3538     }
3539     *pdwSigLen = pCryptKey->dwKeyLen;
3540
3541     if (sDescription) {
3542         if (!RSAENH_CPHashData(hProv, hHash, (CONST BYTE*)sDescription, 
3543                                 (DWORD)lstrlenW(sDescription)*sizeof(WCHAR), 0))
3544         {
3545             return FALSE;
3546         }
3547     }
3548     
3549     dwHashLen = sizeof(DWORD);
3550     if (!RSAENH_CPGetHashParam(hProv, hHash, HP_ALGID, (BYTE*)&aiAlgid, &dwHashLen, 0)) return FALSE;
3551     
3552     dwHashLen = RSAENH_MAX_HASH_SIZE;
3553     if (!RSAENH_CPGetHashParam(hProv, hHash, HP_HASHVAL, abHashValue, &dwHashLen, 0)) return FALSE;
3554  
3555
3556     if (!build_hash_signature(pbSignature, *pdwSigLen, aiAlgid, abHashValue, dwHashLen, dwFlags)) {
3557         return FALSE;
3558     }
3559
3560     return encrypt_block_impl(pCryptKey->aiAlgid, PK_PRIVATE, &pCryptKey->context, pbSignature, pbSignature, RSAENH_ENCRYPT);
3561 }
3562
3563 /******************************************************************************
3564  * CPVerifySignature (RSAENH.@)
3565  *
3566  * Verify the signature of a hash object.
3567  * 
3568  * PARAMS
3569  *  hProv        [I] The key container, to which the hash belongs.
3570  *  hHash        [I] The hash for which the signature is verified.
3571  *  pbSignature  [I] The binary signature.
3572  *  dwSigLen     [I] Length of the signature BLOB.
3573  *  hPubKey      [I] Public key used to verify the signature.
3574  *  sDescription [I] Should be NULL for security reasons.
3575  *  dwFlags      [I] 0, CRYPT_NOHASHOID or CRYPT_X931_FORMAT: Format of the signature.
3576  *
3577  * RETURNS
3578  *  Success: TRUE  (Signature is valid)
3579  *  Failure: FALSE (GetLastError() == NTE_BAD_SIGNATURE, if signature is invalid)
3580  */
3581 BOOL WINAPI RSAENH_CPVerifySignature(HCRYPTPROV hProv, HCRYPTHASH hHash, CONST BYTE *pbSignature, 
3582                                      DWORD dwSigLen, HCRYPTKEY hPubKey, LPCWSTR sDescription, 
3583                                      DWORD dwFlags)
3584 {
3585     BYTE *pbConstructed = NULL, *pbDecrypted = NULL;
3586     CRYPTKEY *pCryptKey;
3587     DWORD dwHashLen;
3588     ALG_ID aiAlgid;
3589     BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
3590     BOOL res = FALSE;
3591
3592     TRACE("(hProv=%08lx, hHash=%08lx, pbSignature=%p, dwSigLen=%d, hPubKey=%08lx, sDescription=%s, "
3593           "dwFlags=%08x)\n", hProv, hHash, pbSignature, dwSigLen, hPubKey, debugstr_w(sDescription),
3594           dwFlags);
3595         
3596     if (dwFlags & ~(CRYPT_NOHASHOID|CRYPT_X931_FORMAT)) {
3597         SetLastError(NTE_BAD_FLAGS);
3598         return FALSE;
3599     }
3600     
3601     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3602     {
3603         SetLastError(NTE_BAD_UID);
3604         return FALSE;
3605     }
3606  
3607     if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY,
3608                        (OBJECTHDR**)&pCryptKey))
3609     {
3610         SetLastError(NTE_BAD_KEY);
3611         return FALSE;
3612     }
3613
3614     /* in Microsoft implementation, the signature length is checked before
3615      * the signature pointer.
3616      */
3617     if (dwSigLen != pCryptKey->dwKeyLen)
3618     {
3619         SetLastError(NTE_BAD_SIGNATURE);
3620         return FALSE;
3621     }
3622
3623     if (!hHash || !pbSignature)
3624     {
3625         SetLastError(ERROR_INVALID_PARAMETER);
3626         return FALSE;
3627     }
3628
3629     if (sDescription) {
3630         if (!RSAENH_CPHashData(hProv, hHash, (CONST BYTE*)sDescription, 
3631                                 (DWORD)lstrlenW(sDescription)*sizeof(WCHAR), 0))
3632         {
3633             return FALSE;
3634         }
3635     }
3636     
3637     dwHashLen = sizeof(DWORD);
3638     if (!RSAENH_CPGetHashParam(hProv, hHash, HP_ALGID, (BYTE*)&aiAlgid, &dwHashLen, 0)) return FALSE;
3639     
3640     dwHashLen = RSAENH_MAX_HASH_SIZE;
3641     if (!RSAENH_CPGetHashParam(hProv, hHash, HP_HASHVAL, abHashValue, &dwHashLen, 0)) return FALSE;
3642
3643     pbConstructed = HeapAlloc(GetProcessHeap(), 0, dwSigLen);
3644     if (!pbConstructed) {
3645         SetLastError(NTE_NO_MEMORY);
3646         goto cleanup;
3647     }
3648
3649     pbDecrypted = HeapAlloc(GetProcessHeap(), 0, dwSigLen);
3650     if (!pbDecrypted) {
3651         SetLastError(NTE_NO_MEMORY);
3652         goto cleanup;
3653     }
3654
3655     if (!encrypt_block_impl(pCryptKey->aiAlgid, PK_PUBLIC, &pCryptKey->context, pbSignature, pbDecrypted, 
3656                             RSAENH_DECRYPT)) 
3657     {
3658         goto cleanup;
3659     }
3660
3661     if (!build_hash_signature(pbConstructed, dwSigLen, aiAlgid, abHashValue, dwHashLen, dwFlags)) {
3662         goto cleanup;
3663     }
3664
3665     if (memcmp(pbDecrypted, pbConstructed, dwSigLen)) {
3666         SetLastError(NTE_BAD_SIGNATURE);
3667         goto cleanup;
3668     }
3669     
3670     res = TRUE;
3671 cleanup:
3672     HeapFree(GetProcessHeap(), 0, pbConstructed);
3673     HeapFree(GetProcessHeap(), 0, pbDecrypted);
3674     return res;
3675 }
3676
3677 static const WCHAR szProviderKeys[4][97] = {
3678     {   'S','o','f','t','w','a','r','e','\\',
3679         'M','i','c','r','o','s','o','f','t','\\','C','r','y','p','t','o','g','r',
3680         'a','p','h','y','\\','D','e','f','a','u','l','t','s','\\','P','r','o','v',
3681         'i','d','e','r','\\','M','i','c','r','o','s','o','f','t',' ','B','a','s',
3682         'e',' ','C','r','y','p','t','o','g','r','a','p','h','i','c',' ','P','r',
3683         'o','v','i','d','e','r',' ','v','1','.','0',0 },
3684     {   'S','o','f','t','w','a','r','e','\\',
3685         'M','i','c','r','o','s','o','f','t','\\','C','r','y','p','t','o','g','r',
3686         'a','p','h','y','\\','D','e','f','a','u','l','t','s','\\','P','r','o','v',
3687         'i','d','e','r','\\','M','i','c','r','o','s','o','f','t',' ',
3688         'E','n','h','a','n','c','e','d',
3689         ' ','C','r','y','p','t','o','g','r','a','p','h','i','c',' ','P','r',
3690         'o','v','i','d','e','r',' ','v','1','.','0',0 },
3691     {   'S','o','f','t','w','a','r','e','\\',
3692         'M','i','c','r','o','s','o','f','t','\\','C','r','y','p','t','o','g','r',
3693         'a','p','h','y','\\','D','e','f','a','u','l','t','s','\\','P','r','o','v',
3694         'i','d','e','r','\\','M','i','c','r','o','s','o','f','t',' ','S','t','r','o','n','g',
3695         ' ','C','r','y','p','t','o','g','r','a','p','h','i','c',' ','P','r',
3696         'o','v','i','d','e','r',0 },
3697     {   'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\',
3698         'C','r','y','p','t','o','g','r','a','p','h','y','\\','D','e','f','a','u','l','t','s','\\',
3699         'P','r','o','v','i','d','e','r','\\','M','i','c','r','o','s','o','f','t',' ',
3700         'R','S','A',' ','S','C','h','a','n','n','e','l',' ',
3701         'C','r','y','p','t','o','g','r','a','p','h','i','c',' ','P','r','o','v','i','d','e','r',0 }
3702 };
3703 static const WCHAR szDefaultKeys[2][65] = {
3704     {   'S','o','f','t','w','a','r','e','\\',
3705         'M','i','c','r','o','s','o','f','t','\\','C','r','y','p','t','o','g','r',
3706         'a','p','h','y','\\','D','e','f','a','u','l','t','s','\\','P','r','o','v',
3707         'i','d','e','r',' ','T','y','p','e','s','\\','T','y','p','e',' ','0','0','1',0 },
3708     {   'S','o','f','t','w','a','r','e','\\',
3709         'M','i','c','r','o','s','o','f','t','\\','C','r','y','p','t','o','g','r',
3710         'a','p','h','y','\\','D','e','f','a','u','l','t','s','\\','P','r','o','v',
3711         'i','d','e','r',' ','T','y','p','e','s','\\','T','y','p','e',' ','0','1','2',0 }
3712 };
3713
3714
3715 /******************************************************************************
3716  * DllRegisterServer (RSAENH.@)
3717  *
3718  * Dll self registration. 
3719  *
3720  * PARAMS
3721  *
3722  * RETURNS
3723  *  Success: S_OK.
3724  *    Failure: != S_OK
3725  * 
3726  * NOTES
3727  *  Registers the following keys:
3728  *   - HKLM\Software\Microsoft\Cryptography\Defaults\Provider\
3729  *       Microsoft Base Cryptographic Provider v1.0
3730  *   - HKLM\Software\Microsoft\Cryptography\Defaults\Provider\
3731  *       Microsoft Enhanced Cryptographic Provider
3732  *   - HKLM\Software\Microsoft\Cryptography\Defaults\Provider\
3733  *       Microsoft Strong Cryptographpic Provider
3734  *   - HKLM\Software\Microsoft\Cryptography\Defaults\Provider Types\Type 001
3735  */
3736 HRESULT WINAPI DllRegisterServer(void)
3737 {
3738     HKEY key;
3739     DWORD dp;
3740     long apiRet;
3741     int i;
3742
3743     for (i=0; i<4; i++) {
3744         apiRet = RegCreateKeyExW(HKEY_LOCAL_MACHINE, szProviderKeys[i], 0, NULL,
3745             REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &key, &dp);
3746
3747         if (apiRet == ERROR_SUCCESS)
3748         {
3749             if (dp == REG_CREATED_NEW_KEY)
3750             {
3751                 static const WCHAR szImagePath[] = { 'I','m','a','g','e',' ','P','a','t','h',0 };
3752                 static const WCHAR szRSABase[] = { 'r','s','a','e','n','h','.','d','l','l',0 };
3753                 static const WCHAR szType[] = { 'T','y','p','e',0 };
3754                 static const WCHAR szSignature[] = { 'S','i','g','n','a','t','u','r','e',0 };
3755                 DWORD type = (i == 3) ? PROV_RSA_SCHANNEL : PROV_RSA_FULL;
3756                 DWORD sign = 0xdeadbeef;
3757                 RegSetValueExW(key, szImagePath, 0, REG_SZ, (const BYTE *)szRSABase,
3758                                (lstrlenW(szRSABase) + 1) * sizeof(WCHAR));
3759                 RegSetValueExW(key, szType, 0, REG_DWORD, (LPBYTE)&type, sizeof(type));
3760                 RegSetValueExW(key, szSignature, 0, REG_BINARY, (LPBYTE)&sign, sizeof(sign));
3761             }
3762             RegCloseKey(key);
3763         }
3764     }
3765     
3766     for (i=0; i<2; i++) {
3767         apiRet = RegCreateKeyExW(HKEY_LOCAL_MACHINE, szDefaultKeys[i], 0, NULL, 
3768                                  REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &key, &dp);
3769         if (apiRet == ERROR_SUCCESS)
3770         {
3771             if (dp == REG_CREATED_NEW_KEY)
3772             {
3773                 static const WCHAR szName[] = { 'N','a','m','e',0 };
3774                 static const WCHAR szRSAName[2][46] = {
3775                   { 'M','i','c','r','o','s','o','f','t',' ', 'B','a','s','e',' ',
3776                     'C','r','y','p','t','o','g','r','a','p','h','i','c',' ', 
3777                     'P','r','o','v','i','d','e','r',' ','v','1','.','0',0 },
3778                   { 'M','i','c','r','o','s','o','f','t',' ','R','S','A',' ',
3779                     'S','C','h','a','n','n','e','l',' ',
3780                     'C','r','y','p','t','o','g','r','a','p','h','i','c',' ',
3781                     'P','r','o','v','i','d','e','r',0 } };
3782                 static const WCHAR szTypeName[] = { 'T','y','p','e','N','a','m','e',0 };
3783                 static const WCHAR szRSATypeName[2][38] = { 
3784                   { 'R','S','A',' ','F','u','l','l',' ',
3785                        '(','S','i','g','n','a','t','u','r','e',' ','a','n','d',' ',
3786                     'K','e','y',' ','E','x','c','h','a','n','g','e',')',0 },
3787                   { 'R','S','A',' ','S','C','h','a','n','n','e','l',0 } };
3788
3789                 RegSetValueExW(key, szName, 0, REG_SZ, 
3790                                 (const BYTE *)szRSAName[i], lstrlenW(szRSAName[i])*sizeof(WCHAR)+sizeof(WCHAR));
3791                 RegSetValueExW(key, szTypeName, 0, REG_SZ, 
3792                                 (const BYTE *)szRSATypeName[i], lstrlenW(szRSATypeName[i])*sizeof(WCHAR)+sizeof(WCHAR));
3793             }
3794         }
3795         RegCloseKey(key);
3796     }
3797     
3798     return HRESULT_FROM_WIN32(apiRet);
3799 }
3800
3801 /******************************************************************************
3802  * DllUnregisterServer (RSAENH.@)
3803  *
3804  * Dll self unregistration. 
3805  *
3806  * PARAMS
3807  *
3808  * RETURNS
3809  *  Success: S_OK
3810  *
3811  * NOTES
3812  *  For the relevant keys see DllRegisterServer.
3813  */
3814 HRESULT WINAPI DllUnregisterServer(void)
3815 {
3816     RegDeleteKeyW(HKEY_LOCAL_MACHINE, szProviderKeys[0]);
3817     RegDeleteKeyW(HKEY_LOCAL_MACHINE, szProviderKeys[1]);
3818     RegDeleteKeyW(HKEY_LOCAL_MACHINE, szProviderKeys[2]);
3819     RegDeleteKeyW(HKEY_LOCAL_MACHINE, szProviderKeys[3]);
3820     RegDeleteKeyW(HKEY_LOCAL_MACHINE, szDefaultKeys[0]);
3821     RegDeleteKeyW(HKEY_LOCAL_MACHINE, szDefaultKeys[1]);
3822     return S_OK;
3823 }