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