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