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