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