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