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