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