samlib: Add stubbed samlib.dll.
[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  * Copyright 2007 Vijay Kiran Kamuju
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24
25 #include "config.h"
26 #include "wine/port.h"
27 #include "wine/library.h"
28 #include "wine/debug.h"
29
30 #include <stdarg.h>
31 #include <stdio.h>
32
33 #include "windef.h"
34 #include "winbase.h"
35 #include "winreg.h"
36 #include "wincrypt.h"
37 #include "handle.h"
38 #include "implglue.h"
39 #include "objbase.h"
40
41 WINE_DEFAULT_DEBUG_CHANNEL(crypt);
42
43 /******************************************************************************
44  * CRYPTHASH - hash objects
45  */
46 #define RSAENH_MAGIC_HASH           0x85938417u
47 #define RSAENH_MAX_HASH_SIZE        104
48 #define RSAENH_HASHSTATE_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_MASTERKEY  2
79 typedef struct _RSAENH_SCHANNEL_INFO 
80 {
81     SCHANNEL_ALG saEncAlg;
82     SCHANNEL_ALG saMACAlg;
83     CRYPT_DATA_BLOB blobClientRandom;
84     CRYPT_DATA_BLOB blobServerRandom;
85 } RSAENH_SCHANNEL_INFO;
86
87 typedef struct tagCRYPTKEY
88 {
89     OBJECTHDR   header;
90     ALG_ID      aiAlgid;
91     HCRYPTPROV  hProv;
92     DWORD       dwMode;
93     DWORD       dwModeBits;
94     DWORD       dwPermissions;
95     DWORD       dwKeyLen;
96     DWORD       dwEffectiveKeyLen;
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 #define RSAENH_PERSONALITY_AES         4u
115
116 #define RSAENH_MAGIC_CONTAINER         0x26384993u
117 typedef struct tagKEYCONTAINER
118 {
119     OBJECTHDR    header;
120     DWORD        dwFlags;
121     DWORD        dwPersonality;
122     DWORD        dwEnumAlgsCtr;
123     DWORD        dwEnumContainersCtr;
124     CHAR         szName[MAX_PATH];
125     CHAR         szProvName[MAX_PATH];
126     HCRYPTKEY    hKeyExchangeKeyPair;
127     HCRYPTKEY    hSignatureKeyPair;
128 } KEYCONTAINER;
129
130 /******************************************************************************
131  * Some magic constants
132  */
133 #define RSAENH_ENCRYPT                    1
134 #define RSAENH_DECRYPT                    0    
135 #define RSAENH_HMAC_DEF_IPAD_CHAR      0x36
136 #define RSAENH_HMAC_DEF_OPAD_CHAR      0x5c
137 #define RSAENH_HMAC_DEF_PAD_LEN          64
138 #define RSAENH_DES_EFFECTIVE_KEYLEN      56
139 #define RSAENH_DES_STORAGE_KEYLEN        64
140 #define RSAENH_3DES112_EFFECTIVE_KEYLEN 112
141 #define RSAENH_3DES112_STORAGE_KEYLEN   128
142 #define RSAENH_3DES_EFFECTIVE_KEYLEN    168
143 #define RSAENH_3DES_STORAGE_KEYLEN      192
144 #define RSAENH_MAGIC_RSA2        0x32415352
145 #define RSAENH_MAGIC_RSA1        0x31415352
146 #define RSAENH_PKC_BLOCKTYPE           0x02
147 #define RSAENH_SSL3_VERSION_MAJOR         3
148 #define RSAENH_SSL3_VERSION_MINOR         0
149 #define RSAENH_TLS1_VERSION_MAJOR         3
150 #define RSAENH_TLS1_VERSION_MINOR         1
151 #define RSAENH_REGKEY "Software\\Wine\\Crypto\\RSA\\%s"
152
153 #define RSAENH_MIN(a,b) ((a)<(b)?(a):(b))
154 /******************************************************************************
155  * aProvEnumAlgsEx - Defines the capabilities of the CSP personalities.
156  */
157 #define RSAENH_MAX_ENUMALGS 24
158 #define RSAENH_PCT1_SSL2_SSL3_TLS1 (CRYPT_FLAG_PCT1|CRYPT_FLAG_SSL2|CRYPT_FLAG_SSL3|CRYPT_FLAG_TLS1)
159 static const PROV_ENUMALGS_EX aProvEnumAlgsEx[5][RSAENH_MAX_ENUMALGS+1] =
160 {
161  {
162   {CALG_RC2,       40, 40,   56,0,                    4,"RC2",     24,"RSA Data Security's RC2"},
163   {CALG_RC4,       40, 40,   56,0,                    4,"RC4",     24,"RSA Data Security's RC4"},
164   {CALG_DES,       56, 56,   56,0,                    4,"DES",     31,"Data Encryption Standard (DES)"},
165   {CALG_SHA,      160,160,  160,CRYPT_FLAG_SIGNING,   6,"SHA-1",   30,"Secure Hash Algorithm (SHA-1)"},
166   {CALG_MD2,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD2",     23,"Message Digest 2 (MD2)"},
167   {CALG_MD4,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD4",     23,"Message Digest 4 (MD4)"},
168   {CALG_MD5,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD5",     23,"Message Digest 5 (MD5)"},
169   {CALG_SSL3_SHAMD5,288,288,288,0,                   12,"SSL3 SHAMD5",12,"SSL3 SHAMD5"},
170   {CALG_MAC,        0,  0,    0,0,                    4,"MAC",     28,"Message Authentication Code"},
171   {CALG_RSA_SIGN, 512,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_SIGN",14,"RSA Signature"},
172   {CALG_RSA_KEYX, 512,384, 1024,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_KEYX",17,"RSA Key Exchange"},
173   {CALG_HMAC,       0,  0,    0,0,                    5,"HMAC",    18,"Hugo's MAC (HMAC)"},
174   {0,               0,  0,    0,0,                    1,"",         1,""}
175  },
176  {
177   {CALG_RC2,      128, 40,  128,0,                    4,"RC2",     24,"RSA Data Security's RC2"},
178   {CALG_RC4,      128, 40,  128,0,                    4,"RC4",     24,"RSA Data Security's RC4"},
179   {CALG_DES,       56, 56,   56,0,                    4,"DES",     31,"Data Encryption Standard (DES)"},
180   {CALG_3DES_112, 112,112,  112,0,                   13,"3DES TWO KEY",19,"Two Key Triple DES"},
181   {CALG_3DES,     168,168,  168,0,                    5,"3DES",    21,"Three Key Triple DES"},
182   {CALG_SHA,      160,160,  160,CRYPT_FLAG_SIGNING,   6,"SHA-1",   30,"Secure Hash Algorithm (SHA-1)"},
183   {CALG_MD2,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD2",     23,"Message Digest 2 (MD2)"},
184   {CALG_MD4,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD4",     23,"Message Digest 4 (MD4)"},
185   {CALG_MD5,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD5",     23,"Message Digest 5 (MD5)"},
186   {CALG_SSL3_SHAMD5,288,288,288,0,                   12,"SSL3 SHAMD5",12,"SSL3 SHAMD5"},
187   {CALG_MAC,        0,  0,    0,0,                    4,"MAC",     28,"Message Authentication Code"},
188   {CALG_RSA_SIGN,1024,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_SIGN",14,"RSA Signature"},
189   {CALG_RSA_KEYX,1024,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_KEYX",17,"RSA Key Exchange"},
190   {CALG_HMAC,       0,  0,    0,0,                    5,"HMAC",    18,"Hugo's MAC (HMAC)"},
191   {0,               0,  0,    0,0,                    1,"",         1,""}
192  },
193  {
194   {CALG_RC2,      128, 40,  128,0,                    4,"RC2",     24,"RSA Data Security's RC2"},
195   {CALG_RC4,      128, 40,  128,0,                    4,"RC4",     24,"RSA Data Security's RC4"},
196   {CALG_DES,       56, 56,   56,0,                    4,"DES",     31,"Data Encryption Standard (DES)"},
197   {CALG_3DES_112, 112,112,  112,0,                   13,"3DES TWO KEY",19,"Two Key Triple DES"},
198   {CALG_3DES,     168,168,  168,0,                    5,"3DES",    21,"Three Key Triple DES"},
199   {CALG_SHA,      160,160,  160,CRYPT_FLAG_SIGNING,   6,"SHA-1",   30,"Secure Hash Algorithm (SHA-1)"},
200   {CALG_MD2,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD2",     23,"Message Digest 2 (MD2)"},
201   {CALG_MD4,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD4",     23,"Message Digest 4 (MD4)"},
202   {CALG_MD5,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD5",     23,"Message Digest 5 (MD5)"},
203   {CALG_SSL3_SHAMD5,288,288,288,0,                   12,"SSL3 SHAMD5",12,"SSL3 SHAMD5"},
204   {CALG_MAC,        0,  0,    0,0,                    4,"MAC",     28,"Message Authentication Code"},
205   {CALG_RSA_SIGN,1024,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_SIGN",14,"RSA Signature"},
206   {CALG_RSA_KEYX,1024,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_KEYX",17,"RSA Key Exchange"},
207   {CALG_HMAC,       0,  0,    0,0,                    5,"HMAC",    18,"Hugo's MAC (HMAC)"},
208   {0,               0,  0,    0,0,                    1,"",         1,""}
209  },
210  {
211   {CALG_RC2,      128, 40,  128,RSAENH_PCT1_SSL2_SSL3_TLS1, 4,"RC2",        24,"RSA Data Security's RC2"},
212   {CALG_RC4,      128, 40,  128,RSAENH_PCT1_SSL2_SSL3_TLS1, 4,"RC4",        24,"RSA Data Security's RC4"},
213   {CALG_DES,       56, 56,   56,RSAENH_PCT1_SSL2_SSL3_TLS1, 4,"DES",        31,"Data Encryption Standard (DES)"},
214   {CALG_3DES_112, 112,112,  112,RSAENH_PCT1_SSL2_SSL3_TLS1,13,"3DES TWO KEY",19,"Two Key Triple DES"},
215   {CALG_3DES,     168,168,  168,RSAENH_PCT1_SSL2_SSL3_TLS1, 5,"3DES",       21,"Three Key Triple DES"},
216   {CALG_SHA,160,160,160,CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1,6,"SHA-1",30,"Secure Hash Algorithm (SHA-1)"},
217   {CALG_MD5,128,128,128,CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1,4,"MD5",23,"Message Digest 5 (MD5)"},
218   {CALG_SSL3_SHAMD5,288,288,288,0,                         12,"SSL3 SHAMD5",12,"SSL3 SHAMD5"},
219   {CALG_MAC,        0,  0,    0,0,                          4,"MAC",        28,"Message Authentication Code"},
220   {CALG_RSA_SIGN,1024,384,16384,CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1,9,"RSA_SIGN",14,"RSA Signature"},
221   {CALG_RSA_KEYX,1024,384,16384,CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1,9,"RSA_KEYX",17,"RSA Key Exchange"},
222   {CALG_HMAC,       0,  0,    0,0,                          5,"HMAC",       18,"Hugo's MAC (HMAC)"},
223   {CALG_PCT1_MASTER,128,128,128,CRYPT_FLAG_PCT1,           12,"PCT1 MASTER",12,"PCT1 Master"},
224   {CALG_SSL2_MASTER,40,40,  192,CRYPT_FLAG_SSL2,           12,"SSL2 MASTER",12,"SSL2 Master"},
225   {CALG_SSL3_MASTER,384,384,384,CRYPT_FLAG_SSL3,           12,"SSL3 MASTER",12,"SSL3 Master"},
226   {CALG_TLS1_MASTER,384,384,384,CRYPT_FLAG_TLS1,           12,"TLS1 MASTER",12,"TLS1 Master"},
227   {CALG_SCHANNEL_MASTER_HASH,0,0,-1,0,                     16,"SCH MASTER HASH",21,"SChannel Master Hash"},
228   {CALG_SCHANNEL_MAC_KEY,0,0,-1,0,                         12,"SCH MAC KEY",17,"SChannel MAC Key"},
229   {CALG_SCHANNEL_ENC_KEY,0,0,-1,0,                         12,"SCH ENC KEY",24,"SChannel Encryption Key"},
230   {CALG_TLS1PRF,    0,  0,   -1,0,                          9,"TLS1 PRF",   28,"TLS1 Pseudo Random Function"},
231   {0,               0,  0,    0,0,                          1,"",            1,""}
232  },
233  {
234   {CALG_RC2,      128, 40,  128,0,                    4,"RC2",     24,"RSA Data Security's RC2"},
235   {CALG_RC4,      128, 40,  128,0,                    4,"RC4",     24,"RSA Data Security's RC4"},
236   {CALG_DES,       56, 56,   56,0,                    4,"DES",     31,"Data Encryption Standard (DES)"},
237   {CALG_3DES_112, 112,112,  112,0,                   13,"3DES TWO KEY",19,"Two Key Triple DES"},
238   {CALG_3DES,     168,168,  168,0,                    5,"3DES",    21,"Three Key Triple DES"},
239   {CALG_AES,      128,128,  128,0,                    4,"AES",     35,"Advanced Encryption Standard (AES)"},
240   {CALG_AES_128,  128,128,  128,0,                    8,"AES-128", 39,"Advanced Encryption Standard (AES-128)"},
241   {CALG_AES_192,  192,192,  192,0,                    8,"AES-192", 39,"Advanced Encryption Standard (AES-192)"},
242   {CALG_AES_256,  256,256,  256,0,                    8,"AES-256", 39,"Advanced Encryption Standard (AES-256)"},
243   {CALG_SHA,      160,160,  160,CRYPT_FLAG_SIGNING,   6,"SHA-1",   30,"Secure Hash Algorithm (SHA-1)"},
244   {CALG_SHA_256,  256,256,  256,CRYPT_FLAG_SIGNING,   6,"SHA-256", 30,"Secure Hash Algorithm (SHA-256)"},
245   {CALG_SHA_384,  384,384,  384,CRYPT_FLAG_SIGNING,   6,"SHA-384", 30,"Secure Hash Algorithm (SHA-284)"},
246   {CALG_SHA_512,  512,512,  512,CRYPT_FLAG_SIGNING,   6,"SHA-512", 30,"Secure Hash Algorithm (SHA-512)"},
247   {CALG_MD2,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD2",     23,"Message Digest 2 (MD2)"},
248   {CALG_MD4,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD4",     23,"Message Digest 4 (MD4)"},
249   {CALG_MD5,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD5",     23,"Message Digest 5 (MD5)"},
250   {CALG_SSL3_SHAMD5,288,288,288,0,                   12,"SSL3 SHAMD5",12,"SSL3 SHAMD5"},
251   {CALG_MAC,        0,  0,    0,0,                    4,"MAC",     28,"Message Authentication Code"},
252   {CALG_RSA_SIGN,1024,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_SIGN",14,"RSA Signature"},
253   {CALG_RSA_KEYX,1024,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_KEYX",17,"RSA Key Exchange"},
254   {CALG_HMAC,       0,  0,    0,0,                    5,"HMAC",    18,"Hugo's MAC (HMAC)"},
255   {0,               0,  0,    0,0,                    1,"",         1,""}
256  }
257 };
258
259 /******************************************************************************
260  * API forward declarations
261  */
262 BOOL WINAPI 
263 RSAENH_CPGetKeyParam(
264     HCRYPTPROV hProv, 
265     HCRYPTKEY hKey, 
266     DWORD dwParam, 
267     BYTE *pbData, 
268     DWORD *pdwDataLen, 
269     DWORD dwFlags
270 );
271
272 BOOL WINAPI 
273 RSAENH_CPEncrypt(
274     HCRYPTPROV hProv, 
275     HCRYPTKEY hKey, 
276     HCRYPTHASH hHash, 
277     BOOL Final, 
278     DWORD dwFlags, 
279     BYTE *pbData,
280     DWORD *pdwDataLen, 
281     DWORD dwBufLen
282 );
283
284 BOOL WINAPI 
285 RSAENH_CPCreateHash(
286     HCRYPTPROV hProv, 
287     ALG_ID Algid, 
288     HCRYPTKEY hKey, 
289     DWORD dwFlags, 
290     HCRYPTHASH *phHash
291 );
292
293 BOOL WINAPI 
294 RSAENH_CPSetHashParam(
295     HCRYPTPROV hProv, 
296     HCRYPTHASH hHash, 
297     DWORD dwParam, 
298     BYTE *pbData, DWORD dwFlags
299 );
300
301 BOOL WINAPI 
302 RSAENH_CPGetHashParam(
303     HCRYPTPROV hProv, 
304     HCRYPTHASH hHash, 
305     DWORD dwParam, 
306     BYTE *pbData, 
307     DWORD *pdwDataLen, 
308     DWORD dwFlags
309 );
310
311 BOOL WINAPI 
312 RSAENH_CPDestroyHash(
313     HCRYPTPROV hProv, 
314     HCRYPTHASH hHash
315 );
316
317 static BOOL crypt_export_key(
318     CRYPTKEY *pCryptKey,
319     HCRYPTKEY hPubKey, 
320     DWORD dwBlobType, 
321     DWORD dwFlags, 
322     BOOL force,
323     BYTE *pbData, 
324     DWORD *pdwDataLen
325 );
326
327 static BOOL import_key(
328     HCRYPTPROV hProv, 
329     CONST BYTE *pbData, 
330     DWORD dwDataLen, 
331     HCRYPTKEY hPubKey, 
332     DWORD dwFlags, 
333     BOOL fStoreKey,
334     HCRYPTKEY *phKey
335 );
336
337 BOOL WINAPI 
338 RSAENH_CPHashData(
339     HCRYPTPROV hProv, 
340     HCRYPTHASH hHash, 
341     CONST BYTE *pbData, 
342     DWORD dwDataLen, 
343     DWORD dwFlags
344 );
345
346 /******************************************************************************
347  * CSP's handle table (used by all acquired key containers)
348  */
349 static struct handle_table handle_table;
350
351 /******************************************************************************
352  * DllMain (RSAENH.@)
353  *
354  * Initializes and destroys the handle table for the CSP's handles.
355  */
356 int WINAPI DllMain(HINSTANCE hInstance, DWORD fdwReason, PVOID pvReserved)
357 {
358     switch (fdwReason)
359     {
360         case DLL_PROCESS_ATTACH:
361             DisableThreadLibraryCalls(hInstance);
362             init_handle_table(&handle_table);
363             break;
364
365         case DLL_PROCESS_DETACH:
366             destroy_handle_table(&handle_table);
367             break;
368     }
369     return 1;
370 }
371
372 /******************************************************************************
373  * copy_param [Internal]
374  *
375  * Helper function that supports the standard WINAPI protocol for querying data
376  * of dynamic size.
377  *
378  * PARAMS
379  *  pbBuffer      [O]   Buffer where the queried parameter is copied to, if it is large enough.
380  *                      May be NUL if the required buffer size is to be queried only.
381  *  pdwBufferSize [I/O] In: Size of the buffer at pbBuffer
382  *                      Out: Size of parameter pbParam
383  *  pbParam       [I]   Parameter value.
384  *  dwParamSize   [I]   Size of pbParam
385  *
386  * RETURN
387  *  Success: TRUE (pbParam was copied into pbBuffer or pbBuffer is NULL)
388  *  Failure: FALSE (pbBuffer is not large enough to hold pbParam). Last error: ERROR_MORE_DATA
389  */
390 static inline BOOL copy_param(
391     BYTE *pbBuffer, DWORD *pdwBufferSize, CONST BYTE *pbParam, DWORD dwParamSize) 
392 {
393     if (pbBuffer) 
394     {
395         if (dwParamSize > *pdwBufferSize) 
396         {
397             SetLastError(ERROR_MORE_DATA);
398             *pdwBufferSize = dwParamSize;
399             return FALSE;
400         }
401         memcpy(pbBuffer, pbParam, dwParamSize);
402     }
403     *pdwBufferSize = dwParamSize;
404     return TRUE;
405 }
406
407 /******************************************************************************
408  * get_algid_info [Internal]
409  *
410  * Query CSP capabilities for a given crypto algorithm.
411  * 
412  * PARAMS
413  *  hProv [I] Handle to a key container of the CSP whose capabilities are to be queried.
414  *  algid [I] Identifier of the crypto algorithm about which information is requested.
415  *
416  * RETURNS
417  *  Success: Pointer to a PROV_ENUMALGS_EX struct containing information about the crypto algorithm.
418  *  Failure: NULL (algid not supported)
419  */
420 static inline const PROV_ENUMALGS_EX* get_algid_info(HCRYPTPROV hProv, ALG_ID algid) {
421     const PROV_ENUMALGS_EX *iterator;
422     KEYCONTAINER *pKeyContainer;
423
424     if (!lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER, (OBJECTHDR**)&pKeyContainer)) {
425         SetLastError(NTE_BAD_UID);
426         return NULL;
427     }
428
429     for (iterator = aProvEnumAlgsEx[pKeyContainer->dwPersonality]; iterator->aiAlgid; iterator++) {
430         if (iterator->aiAlgid == algid) return iterator;
431     }
432
433     SetLastError(NTE_BAD_ALGID);
434     return NULL;
435 }
436
437 /******************************************************************************
438  * copy_data_blob [Internal] 
439  *
440  * deeply copies a DATA_BLOB
441  *
442  * PARAMS
443  *  dst [O] That's where the blob will be copied to
444  *  src [I] Source blob
445  *
446  * RETURNS
447  *  Success: TRUE
448  *  Failure: FALSE (GetLastError() == NTE_NO_MEMORY
449  *
450  * NOTES
451  *  Use free_data_blob to release resources occupied by copy_data_blob.
452  */
453 static inline BOOL copy_data_blob(PCRYPT_DATA_BLOB dst, CONST PCRYPT_DATA_BLOB src) {
454     dst->pbData = HeapAlloc(GetProcessHeap(), 0, src->cbData);
455     if (!dst->pbData) {
456         SetLastError(NTE_NO_MEMORY);
457         return FALSE;
458     }    
459     dst->cbData = src->cbData;
460     memcpy(dst->pbData, src->pbData, src->cbData);
461     return TRUE;
462 }
463
464 /******************************************************************************
465  * concat_data_blobs [Internal]
466  *
467  * Concatenates two blobs
468  *
469  * PARAMS
470  *  dst  [O] The new blob will be copied here
471  *  src1 [I] Prefix blob
472  *  src2 [I] Appendix blob
473  *
474  * RETURNS
475  *  Success: TRUE
476  *  Failure: FALSE (GetLastError() == NTE_NO_MEMORY)
477  *
478  * NOTES
479  *  Release resources occupied by concat_data_blobs with free_data_blobs
480  */
481 static inline BOOL concat_data_blobs(PCRYPT_DATA_BLOB dst, CONST PCRYPT_DATA_BLOB src1, 
482                                      CONST PCRYPT_DATA_BLOB src2) 
483 {
484     dst->cbData = src1->cbData + src2->cbData;
485     dst->pbData = HeapAlloc(GetProcessHeap(), 0, dst->cbData);
486     if (!dst->pbData) {
487         SetLastError(NTE_NO_MEMORY);
488         return FALSE;
489     }
490     memcpy(dst->pbData, src1->pbData, src1->cbData);
491     memcpy(dst->pbData + src1->cbData, src2->pbData, src2->cbData);
492     return TRUE;
493 }
494
495 /******************************************************************************
496  * free_data_blob [Internal]
497  *
498  * releases resource occupied by a dynamically allocated CRYPT_DATA_BLOB
499  * 
500  * PARAMS
501  *  pBlob [I] Heap space occupied by pBlob->pbData is released
502  */
503 static inline void free_data_blob(PCRYPT_DATA_BLOB pBlob) {
504     HeapFree(GetProcessHeap(), 0, pBlob->pbData);
505 }
506
507 /******************************************************************************
508  * init_data_blob [Internal]
509  */
510 static inline void init_data_blob(PCRYPT_DATA_BLOB pBlob) {
511     pBlob->pbData = NULL;
512     pBlob->cbData = 0;
513 }
514
515 /******************************************************************************
516  * free_hmac_info [Internal]
517  *
518  * Deeply free an HMAC_INFO struct.
519  *
520  * PARAMS
521  *  hmac_info [I] Pointer to the HMAC_INFO struct to be freed.
522  *
523  * NOTES
524  *  See Internet RFC 2104 for details on the HMAC algorithm.
525  */
526 static inline void free_hmac_info(PHMAC_INFO hmac_info) {
527     if (!hmac_info) return;
528     HeapFree(GetProcessHeap(), 0, hmac_info->pbInnerString);
529     HeapFree(GetProcessHeap(), 0, hmac_info->pbOuterString);
530     HeapFree(GetProcessHeap(), 0, hmac_info);
531 }
532
533 /******************************************************************************
534  * copy_hmac_info [Internal]
535  *
536  * Deeply copy an HMAC_INFO struct
537  *
538  * PARAMS
539  *  dst [O] Pointer to a location where the pointer to the HMAC_INFO copy will be stored.
540  *  src [I] Pointer to the HMAC_INFO struct to be copied.
541  *
542  * RETURNS
543  *  Success: TRUE
544  *  Failure: FALSE
545  *
546  * NOTES
547  *  See Internet RFC 2104 for details on the HMAC algorithm.
548  */
549 static BOOL copy_hmac_info(PHMAC_INFO *dst, const HMAC_INFO *src) {
550     if (!src) return FALSE;
551     *dst = HeapAlloc(GetProcessHeap(), 0, sizeof(HMAC_INFO));
552     if (!*dst) return FALSE;
553     **dst = *src;
554     (*dst)->pbInnerString = NULL;
555     (*dst)->pbOuterString = NULL;
556     if ((*dst)->cbInnerString == 0) (*dst)->cbInnerString = RSAENH_HMAC_DEF_PAD_LEN;
557     (*dst)->pbInnerString = HeapAlloc(GetProcessHeap(), 0, (*dst)->cbInnerString);
558     if (!(*dst)->pbInnerString) {
559         free_hmac_info(*dst);
560         return FALSE;
561     }
562     if (src->cbInnerString) 
563         memcpy((*dst)->pbInnerString, src->pbInnerString, src->cbInnerString);
564     else 
565         memset((*dst)->pbInnerString, RSAENH_HMAC_DEF_IPAD_CHAR, RSAENH_HMAC_DEF_PAD_LEN);
566     if ((*dst)->cbOuterString == 0) (*dst)->cbOuterString = RSAENH_HMAC_DEF_PAD_LEN;
567     (*dst)->pbOuterString = HeapAlloc(GetProcessHeap(), 0, (*dst)->cbOuterString);
568     if (!(*dst)->pbOuterString) {
569         free_hmac_info(*dst);
570         return FALSE;
571     }
572     if (src->cbOuterString) 
573         memcpy((*dst)->pbOuterString, src->pbOuterString, src->cbOuterString);
574     else 
575         memset((*dst)->pbOuterString, RSAENH_HMAC_DEF_OPAD_CHAR, RSAENH_HMAC_DEF_PAD_LEN);
576     return TRUE;
577 }
578
579 /******************************************************************************
580  * destroy_hash [Internal]
581  *
582  * Destructor for hash objects
583  *
584  * PARAMS
585  *  pCryptHash [I] Pointer to the hash object to be destroyed. 
586  *                 Will be invalid after function returns!
587  */
588 static void destroy_hash(OBJECTHDR *pObject)
589 {
590     CRYPTHASH *pCryptHash = (CRYPTHASH*)pObject;
591         
592     free_hmac_info(pCryptHash->pHMACInfo);
593     free_data_blob(&pCryptHash->tpPRFParams.blobLabel);
594     free_data_blob(&pCryptHash->tpPRFParams.blobSeed);
595     HeapFree(GetProcessHeap(), 0, pCryptHash);
596 }
597
598 /******************************************************************************
599  * init_hash [Internal]
600  *
601  * Initialize (or reset) a hash object
602  *
603  * PARAMS
604  *  pCryptHash    [I] The hash object to be initialized.
605  */
606 static inline BOOL init_hash(CRYPTHASH *pCryptHash) {
607     DWORD dwLen;
608         
609     switch (pCryptHash->aiAlgid) 
610     {
611         case CALG_HMAC:
612             if (pCryptHash->pHMACInfo) { 
613                 const PROV_ENUMALGS_EX *pAlgInfo;
614                 
615                 pAlgInfo = get_algid_info(pCryptHash->hProv, pCryptHash->pHMACInfo->HashAlgid);
616                 if (!pAlgInfo) return FALSE;
617                 pCryptHash->dwHashSize = pAlgInfo->dwDefaultLen >> 3;
618                 init_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context);
619                 update_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
620                                  pCryptHash->pHMACInfo->pbInnerString, 
621                                  pCryptHash->pHMACInfo->cbInnerString);
622             }
623             return TRUE;
624             
625         case CALG_MAC:
626             dwLen = sizeof(DWORD);
627             RSAENH_CPGetKeyParam(pCryptHash->hProv, pCryptHash->hKey, KP_BLOCKLEN, 
628                                  (BYTE*)&pCryptHash->dwHashSize, &dwLen, 0);
629             pCryptHash->dwHashSize >>= 3;
630             return TRUE;
631
632         default:
633             return init_hash_impl(pCryptHash->aiAlgid, &pCryptHash->context);
634     }
635 }
636
637 /******************************************************************************
638  * update_hash [Internal]
639  *
640  * Hashes the given data and updates the hash object's state accordingly
641  *
642  * PARAMS
643  *  pCryptHash [I] Hash object to be updated.
644  *  pbData     [I] Pointer to data stream to be hashed.
645  *  dwDataLen  [I] Length of data stream.
646  */
647 static inline void update_hash(CRYPTHASH *pCryptHash, CONST BYTE *pbData, DWORD dwDataLen) {
648     BYTE *pbTemp;
649
650     switch (pCryptHash->aiAlgid)
651     {
652         case CALG_HMAC:
653             if (pCryptHash->pHMACInfo) 
654                 update_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context, 
655                                  pbData, dwDataLen);
656             break;
657
658         case CALG_MAC:
659             pbTemp = HeapAlloc(GetProcessHeap(), 0, dwDataLen);
660             if (!pbTemp) return;
661             memcpy(pbTemp, pbData, dwDataLen);
662             RSAENH_CPEncrypt(pCryptHash->hProv, pCryptHash->hKey, 0, FALSE, 0,
663                              pbTemp, &dwDataLen, dwDataLen);
664             HeapFree(GetProcessHeap(), 0, pbTemp);
665             break;
666
667         default:
668             update_hash_impl(pCryptHash->aiAlgid, &pCryptHash->context, pbData, dwDataLen);
669     }
670 }
671
672 /******************************************************************************
673  * finalize_hash [Internal]
674  *
675  * Finalizes the hash, after all data has been hashed with update_hash.
676  * No additional data can be hashed afterwards until the hash gets initialized again.
677  *
678  * PARAMS
679  *  pCryptHash [I] Hash object to be finalized.
680  */
681 static inline void finalize_hash(CRYPTHASH *pCryptHash) {
682     DWORD dwDataLen;
683         
684     switch (pCryptHash->aiAlgid)
685     {
686         case CALG_HMAC:
687             if (pCryptHash->pHMACInfo) {
688                 BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
689
690                 finalize_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context, 
691                                    pCryptHash->abHashValue);
692                 memcpy(abHashValue, pCryptHash->abHashValue, pCryptHash->dwHashSize);
693                 init_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context);
694                 update_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
695                                  pCryptHash->pHMACInfo->pbOuterString, 
696                                  pCryptHash->pHMACInfo->cbOuterString);
697                 update_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
698                                  abHashValue, pCryptHash->dwHashSize);
699                 finalize_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
700                                    pCryptHash->abHashValue);
701             } 
702             break;
703
704         case CALG_MAC:
705             dwDataLen = 0;
706             RSAENH_CPEncrypt(pCryptHash->hProv, pCryptHash->hKey, 0, TRUE, 0,
707                              pCryptHash->abHashValue, &dwDataLen, pCryptHash->dwHashSize);
708             break;
709
710         default:
711             finalize_hash_impl(pCryptHash->aiAlgid, &pCryptHash->context, pCryptHash->abHashValue);
712     }
713 }
714
715 /******************************************************************************
716  * destroy_key [Internal]
717  *
718  * Destructor for key objects
719  *
720  * PARAMS
721  *  pCryptKey [I] Pointer to the key object to be destroyed. 
722  *                Will be invalid after function returns!
723  */
724 static void destroy_key(OBJECTHDR *pObject)
725 {
726     CRYPTKEY *pCryptKey = (CRYPTKEY*)pObject;
727         
728     free_key_impl(pCryptKey->aiAlgid, &pCryptKey->context);
729     free_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom);
730     free_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom);
731     HeapFree(GetProcessHeap(), 0, pCryptKey);
732 }
733
734 /******************************************************************************
735  * setup_key [Internal]
736  *
737  * Initialize (or reset) a key object
738  *
739  * PARAMS
740  *  pCryptKey    [I] The key object to be initialized.
741  */
742 static inline void setup_key(CRYPTKEY *pCryptKey) {
743     pCryptKey->dwState = RSAENH_KEYSTATE_IDLE;
744     memcpy(pCryptKey->abChainVector, pCryptKey->abInitVector, sizeof(pCryptKey->abChainVector));
745     setup_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen, 
746                    pCryptKey->dwEffectiveKeyLen, pCryptKey->dwSaltLen,
747                    pCryptKey->abKeyValue);
748 }
749
750 /******************************************************************************
751  * new_key [Internal]
752  *
753  * Creates a new key object without assigning the actual binary key value. 
754  * This is done by CPDeriveKey, CPGenKey or CPImportKey, which call this function.
755  *
756  * PARAMS
757  *  hProv      [I] Handle to the provider to which the created key will belong.
758  *  aiAlgid    [I] The new key shall use the crypto algorithm idenfied by aiAlgid.
759  *  dwFlags    [I] Upper 16 bits give the key length.
760  *                 Lower 16 bits: CRYPT_EXPORTABLE, CRYPT_CREATE_SALT,
761  *                 CRYPT_NO_SALT
762  *  ppCryptKey [O] Pointer to the created key
763  *
764  * RETURNS
765  *  Success: Handle to the created key.
766  *  Failure: INVALID_HANDLE_VALUE
767  */
768 static HCRYPTKEY new_key(HCRYPTPROV hProv, ALG_ID aiAlgid, DWORD dwFlags, CRYPTKEY **ppCryptKey)
769 {
770     HCRYPTKEY hCryptKey;
771     CRYPTKEY *pCryptKey;
772     DWORD dwKeyLen = HIWORD(dwFlags);
773     const PROV_ENUMALGS_EX *peaAlgidInfo;
774
775     *ppCryptKey = NULL;
776     
777     /* 
778      * Retrieve the CSP's capabilities for the given ALG_ID value
779      */
780     peaAlgidInfo = get_algid_info(hProv, aiAlgid);
781     if (!peaAlgidInfo) return (HCRYPTKEY)INVALID_HANDLE_VALUE;
782
783     TRACE("alg = %s, dwKeyLen = %d\n", debugstr_a(peaAlgidInfo->szName),
784           dwKeyLen);
785     /*
786      * Assume the default key length, if none is specified explicitly
787      */
788     if (dwKeyLen == 0) dwKeyLen = peaAlgidInfo->dwDefaultLen;
789     
790     /*
791      * Check if the requested key length is supported by the current CSP.
792      * Adjust key length's for DES algorithms.
793      */
794     switch (aiAlgid) {
795         case CALG_DES:
796             if (dwKeyLen == RSAENH_DES_EFFECTIVE_KEYLEN) {
797                 dwKeyLen = RSAENH_DES_STORAGE_KEYLEN;
798             }
799             if (dwKeyLen != RSAENH_DES_STORAGE_KEYLEN) {
800                 SetLastError(NTE_BAD_FLAGS);
801                 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
802             }
803             break;
804
805         case CALG_3DES_112:
806             if (dwKeyLen == RSAENH_3DES112_EFFECTIVE_KEYLEN) {
807                 dwKeyLen = RSAENH_3DES112_STORAGE_KEYLEN;
808             }
809             if (dwKeyLen != RSAENH_3DES112_STORAGE_KEYLEN) {
810                 SetLastError(NTE_BAD_FLAGS);
811                 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
812             }
813             break;
814
815         case CALG_3DES:
816             if (dwKeyLen == RSAENH_3DES_EFFECTIVE_KEYLEN) {
817                 dwKeyLen = RSAENH_3DES_STORAGE_KEYLEN;
818             }
819             if (dwKeyLen != RSAENH_3DES_STORAGE_KEYLEN) {
820                 SetLastError(NTE_BAD_FLAGS);
821                 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
822             }
823             break;
824         
825         default:
826             if (dwKeyLen % 8 || 
827                 dwKeyLen > peaAlgidInfo->dwMaxLen || 
828                 dwKeyLen < peaAlgidInfo->dwMinLen) 
829             {
830                 TRACE("key len %d out of bounds (%d, %d)\n", dwKeyLen,
831                       peaAlgidInfo->dwMinLen, peaAlgidInfo->dwMaxLen);
832                 SetLastError(NTE_BAD_DATA);
833                 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
834             }
835     }
836
837     hCryptKey = new_object(&handle_table, sizeof(CRYPTKEY), RSAENH_MAGIC_KEY,
838                            destroy_key, (OBJECTHDR**)&pCryptKey);
839     if (hCryptKey != (HCRYPTKEY)INVALID_HANDLE_VALUE)
840     {
841         pCryptKey->aiAlgid = aiAlgid;
842         pCryptKey->hProv = hProv;
843         pCryptKey->dwModeBits = 0;
844         pCryptKey->dwPermissions = CRYPT_ENCRYPT | CRYPT_DECRYPT | CRYPT_READ | CRYPT_WRITE | 
845                                    CRYPT_MAC;
846         if (dwFlags & CRYPT_EXPORTABLE)
847             pCryptKey->dwPermissions |= CRYPT_EXPORT;
848         pCryptKey->dwKeyLen = dwKeyLen >> 3;
849         pCryptKey->dwEffectiveKeyLen = 0;
850         if ((dwFlags & CRYPT_CREATE_SALT) || (dwKeyLen == 40 && !(dwFlags & CRYPT_NO_SALT))) 
851             pCryptKey->dwSaltLen = 16 /*FIXME*/ - pCryptKey->dwKeyLen;
852         else
853             pCryptKey->dwSaltLen = 0;
854         memset(pCryptKey->abKeyValue, 0, sizeof(pCryptKey->abKeyValue));
855         memset(pCryptKey->abInitVector, 0, sizeof(pCryptKey->abInitVector));
856         init_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom);
857         init_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom);
858             
859         switch(aiAlgid)
860         {
861             case CALG_PCT1_MASTER:
862             case CALG_SSL2_MASTER:
863             case CALG_SSL3_MASTER:
864             case CALG_TLS1_MASTER:
865             case CALG_RC4:
866                 pCryptKey->dwBlockLen = 0;
867                 pCryptKey->dwMode = 0;
868                 break;
869
870             case CALG_RC2:
871             case CALG_DES:
872             case CALG_3DES_112:
873             case CALG_3DES:
874                 pCryptKey->dwBlockLen = 8;
875                 pCryptKey->dwMode = CRYPT_MODE_CBC;
876                 break;
877
878             case CALG_AES:
879             case CALG_AES_128:
880             case CALG_AES_192:
881             case CALG_AES_256:
882                 pCryptKey->dwBlockLen = 16;
883                 pCryptKey->dwMode = CRYPT_MODE_ECB;
884                 break;
885
886             case CALG_RSA_KEYX:
887             case CALG_RSA_SIGN:
888                 pCryptKey->dwBlockLen = dwKeyLen >> 3;
889                 pCryptKey->dwMode = 0;
890                 break;
891         }
892
893         *ppCryptKey = pCryptKey;
894     }
895
896     return hCryptKey;
897 }
898
899 /******************************************************************************
900  * map_key_spec_to_key_pair_name [Internal]
901  *
902  * Returns the name of the registry value associated with a key spec.
903  *
904  * PARAMS
905  *  dwKeySpec     [I] AT_KEYEXCHANGE or AT_SIGNATURE
906  *
907  * RETURNS
908  *  Success: Name of registry value.
909  *  Failure: NULL
910  */
911 static LPCSTR map_key_spec_to_key_pair_name(DWORD dwKeySpec)
912 {
913     LPCSTR szValueName;
914
915     switch (dwKeySpec)
916     {
917     case AT_KEYEXCHANGE:
918         szValueName = "KeyExchangeKeyPair";
919         break;
920     case AT_SIGNATURE:
921         szValueName = "SignatureKeyPair";
922         break;
923     default:
924         WARN("invalid key spec %d\n", dwKeySpec);
925         szValueName = NULL;
926     }
927     return szValueName;
928 }
929
930 /******************************************************************************
931  * store_key_pair [Internal]
932  *
933  * Stores a key pair to the registry
934  * 
935  * PARAMS
936  *  hCryptKey     [I] Handle to the key to be stored
937  *  hKey          [I] Registry key where the key pair is to be stored
938  *  dwKeySpec     [I] AT_KEYEXCHANGE or AT_SIGNATURE
939  *  dwFlags       [I] Flags for protecting the key
940  */
941 static void store_key_pair(HCRYPTKEY hCryptKey, HKEY hKey, DWORD dwKeySpec, DWORD dwFlags)
942 {
943     LPCSTR szValueName;
944     DATA_BLOB blobIn, blobOut;
945     CRYPTKEY *pKey;
946     DWORD dwLen;
947     BYTE *pbKey;
948
949     if (!(szValueName = map_key_spec_to_key_pair_name(dwKeySpec)))
950         return;
951     if (lookup_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY,
952                       (OBJECTHDR**)&pKey))
953     {
954         if (crypt_export_key(pKey, 0, PRIVATEKEYBLOB, 0, TRUE, 0, &dwLen))
955         {
956             pbKey = HeapAlloc(GetProcessHeap(), 0, dwLen);
957             if (pbKey)
958             {
959                 if (crypt_export_key(pKey, 0, PRIVATEKEYBLOB, 0, TRUE, pbKey,
960                     &dwLen))
961                 {
962                     blobIn.pbData = pbKey;
963                     blobIn.cbData = dwLen;
964
965                     if (CryptProtectData(&blobIn, NULL, NULL, NULL, NULL,
966                         dwFlags, &blobOut))
967                     {
968                         RegSetValueExA(hKey, szValueName, 0, REG_BINARY,
969                                        blobOut.pbData, blobOut.cbData);
970                         LocalFree(blobOut.pbData);
971                     }
972                 }
973                 HeapFree(GetProcessHeap(), 0, pbKey);
974             }
975         }
976     }
977 }
978
979 /******************************************************************************
980  * map_key_spec_to_permissions_name [Internal]
981  *
982  * Returns the name of the registry value associated with the permissions for
983  * a key spec.
984  *
985  * PARAMS
986  *  dwKeySpec     [I] AT_KEYEXCHANGE or AT_SIGNATURE
987  *
988  * RETURNS
989  *  Success: Name of registry value.
990  *  Failure: NULL
991  */
992 static LPCSTR map_key_spec_to_permissions_name(DWORD dwKeySpec)
993 {
994     LPCSTR szValueName;
995
996     switch (dwKeySpec)
997     {
998     case AT_KEYEXCHANGE:
999         szValueName = "KeyExchangePermissions";
1000         break;
1001     case AT_SIGNATURE:
1002         szValueName = "SignaturePermissions";
1003         break;
1004     default:
1005         WARN("invalid key spec %d\n", dwKeySpec);
1006         szValueName = NULL;
1007     }
1008     return szValueName;
1009 }
1010
1011 /******************************************************************************
1012  * store_key_permissions [Internal]
1013  *
1014  * Stores a key's permissions to the registry
1015  *
1016  * PARAMS
1017  *  hCryptKey     [I] Handle to the key whose permissions are to be stored
1018  *  hKey          [I] Registry key where the key permissions are to be stored
1019  *  dwKeySpec     [I] AT_KEYEXCHANGE or AT_SIGNATURE
1020  */
1021 static void store_key_permissions(HCRYPTKEY hCryptKey, HKEY hKey, DWORD dwKeySpec)
1022 {
1023     LPCSTR szValueName;
1024     CRYPTKEY *pKey;
1025
1026     if (!(szValueName = map_key_spec_to_permissions_name(dwKeySpec)))
1027         return;
1028     if (lookup_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY,
1029                       (OBJECTHDR**)&pKey))
1030         RegSetValueExA(hKey, szValueName, 0, REG_DWORD,
1031                        (BYTE *)&pKey->dwPermissions,
1032                        sizeof(pKey->dwPermissions));
1033 }
1034
1035 /******************************************************************************
1036  * create_container_key [Internal]
1037  *
1038  * Creates the registry key for a key container's persistent storage.
1039  * 
1040  * PARAMS
1041  *  pKeyContainer [I] Pointer to the key container
1042  *  sam           [I] Desired registry access
1043  *  phKey         [O] Returned key
1044  */
1045 static BOOL create_container_key(KEYCONTAINER *pKeyContainer, REGSAM sam, HKEY *phKey)
1046 {
1047     CHAR szRSABase[MAX_PATH];
1048     HKEY hRootKey;
1049
1050     sprintf(szRSABase, RSAENH_REGKEY, pKeyContainer->szName);
1051
1052     if (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET)
1053         hRootKey = HKEY_LOCAL_MACHINE;
1054     else
1055         hRootKey = HKEY_CURRENT_USER;
1056
1057     /* @@ Wine registry key: HKLM\Software\Wine\Crypto\RSA */
1058     /* @@ Wine registry key: HKCU\Software\Wine\Crypto\RSA */
1059     return RegCreateKeyExA(hRootKey, szRSABase, 0, NULL,
1060                            REG_OPTION_NON_VOLATILE, sam, NULL, phKey, NULL)
1061                            == ERROR_SUCCESS;
1062 }
1063
1064 /******************************************************************************
1065  * open_container_key [Internal]
1066  *
1067  * Opens a key container's persistent storage for reading.
1068  *
1069  * PARAMS
1070  *  pszContainerName [I] Name of the container to be opened.  May be the empty
1071  *                       string if the parent key of all containers is to be
1072  *                       opened.
1073  *  dwFlags          [I] Flags indicating which keyset to be opened.
1074  *  phKey            [O] Returned key
1075  */
1076 static BOOL open_container_key(LPCSTR pszContainerName, DWORD dwFlags, HKEY *phKey)
1077 {
1078     CHAR szRSABase[MAX_PATH];
1079     HKEY hRootKey;
1080
1081     sprintf(szRSABase, RSAENH_REGKEY, pszContainerName);
1082
1083     if (dwFlags & CRYPT_MACHINE_KEYSET)
1084         hRootKey = HKEY_LOCAL_MACHINE;
1085     else
1086         hRootKey = HKEY_CURRENT_USER;
1087
1088     /* @@ Wine registry key: HKLM\Software\Wine\Crypto\RSA */
1089     /* @@ Wine registry key: HKCU\Software\Wine\Crypto\RSA */
1090     return RegOpenKeyExA(hRootKey, szRSABase, 0, KEY_READ, phKey) ==
1091                          ERROR_SUCCESS;
1092 }
1093
1094 /******************************************************************************
1095  * delete_container_key [Internal]
1096  *
1097  * Deletes a key container's persistent storage.
1098  *
1099  * PARAMS
1100  *  pszContainerName [I] Name of the container to be opened.
1101  *  dwFlags          [I] Flags indicating which keyset to be opened.
1102  */
1103 static BOOL delete_container_key(LPCSTR pszContainerName, DWORD dwFlags)
1104 {
1105     CHAR szRegKey[MAX_PATH];
1106
1107     if (snprintf(szRegKey, MAX_PATH, RSAENH_REGKEY, pszContainerName) >= MAX_PATH) {
1108         SetLastError(NTE_BAD_KEYSET_PARAM);
1109         return FALSE;
1110     } else {
1111         HKEY hRootKey;
1112         if (dwFlags & CRYPT_MACHINE_KEYSET)
1113             hRootKey = HKEY_LOCAL_MACHINE;
1114         else
1115             hRootKey = HKEY_CURRENT_USER;
1116         if (!RegDeleteKeyA(hRootKey, szRegKey)) {
1117             SetLastError(ERROR_SUCCESS);
1118             return TRUE;
1119         } else {
1120             SetLastError(NTE_BAD_KEYSET);
1121             return FALSE;
1122         }
1123     }
1124 }
1125
1126 /******************************************************************************
1127  * store_key_container_keys [Internal]
1128  *
1129  * Stores key container's keys in a persistent location.
1130  *
1131  * PARAMS
1132  *  pKeyContainer [I] Pointer to the key container whose keys are to be saved
1133  */
1134 static void store_key_container_keys(KEYCONTAINER *pKeyContainer)
1135 {
1136     HKEY hKey;
1137     DWORD dwFlags;
1138
1139     /* On WinXP, persistent keys are stored in a file located at:
1140      * $AppData$\\Microsoft\\Crypto\\RSA\\$SID$\\some_hex_string
1141      */
1142
1143     if (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET)
1144         dwFlags = CRYPTPROTECT_LOCAL_MACHINE;
1145     else
1146         dwFlags = 0;
1147
1148     if (create_container_key(pKeyContainer, KEY_WRITE, &hKey))
1149     {
1150         store_key_pair(pKeyContainer->hKeyExchangeKeyPair, hKey,
1151                        AT_KEYEXCHANGE, dwFlags);
1152         store_key_pair(pKeyContainer->hSignatureKeyPair, hKey,
1153                        AT_SIGNATURE, dwFlags);
1154         RegCloseKey(hKey);
1155     }
1156 }
1157
1158 /******************************************************************************
1159  * store_key_container_permissions [Internal]
1160  *
1161  * Stores key container's key permissions in a persistent location.
1162  *
1163  * PARAMS
1164  *  pKeyContainer [I] Pointer to the key container whose key permissions are to
1165  *                    be saved
1166  */
1167 static void store_key_container_permissions(KEYCONTAINER *pKeyContainer)
1168 {
1169     HKEY hKey;
1170     DWORD dwFlags;
1171
1172     /* On WinXP, persistent keys are stored in a file located at:
1173      * $AppData$\\Microsoft\\Crypto\\RSA\\$SID$\\some_hex_string
1174      */
1175
1176     if (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET)
1177         dwFlags = CRYPTPROTECT_LOCAL_MACHINE;
1178     else
1179         dwFlags = 0;
1180
1181     if (create_container_key(pKeyContainer, KEY_WRITE, &hKey))
1182     {
1183         store_key_permissions(pKeyContainer->hKeyExchangeKeyPair, hKey,
1184                        AT_KEYEXCHANGE);
1185         store_key_permissions(pKeyContainer->hSignatureKeyPair, hKey,
1186                        AT_SIGNATURE);
1187         RegCloseKey(hKey);
1188     }
1189 }
1190
1191 /******************************************************************************
1192  * release_key_container_keys [Internal]
1193  *
1194  * Releases key container's keys.
1195  *
1196  * PARAMS
1197  *  pKeyContainer [I] Pointer to the key container whose keys are to be released.
1198  */
1199 static void release_key_container_keys(KEYCONTAINER *pKeyContainer)
1200 {
1201     release_handle(&handle_table, pKeyContainer->hKeyExchangeKeyPair,
1202                    RSAENH_MAGIC_KEY);
1203     release_handle(&handle_table, pKeyContainer->hSignatureKeyPair,
1204                    RSAENH_MAGIC_KEY);
1205 }
1206
1207 /******************************************************************************
1208  * destroy_key_container [Internal]
1209  *
1210  * Destructor for key containers.
1211  *
1212  * PARAMS
1213  *  pObjectHdr [I] Pointer to the key container to be destroyed.
1214  */
1215 static void destroy_key_container(OBJECTHDR *pObjectHdr)
1216 {
1217     KEYCONTAINER *pKeyContainer = (KEYCONTAINER*)pObjectHdr;
1218
1219     if (!(pKeyContainer->dwFlags & CRYPT_VERIFYCONTEXT))
1220     {
1221         store_key_container_keys(pKeyContainer);
1222         store_key_container_permissions(pKeyContainer);
1223         release_key_container_keys(pKeyContainer);
1224     }
1225     else
1226         release_key_container_keys(pKeyContainer);
1227     HeapFree( GetProcessHeap(), 0, pKeyContainer );
1228 }
1229
1230 /******************************************************************************
1231  * new_key_container [Internal]
1232  *
1233  * Create a new key container. The personality (RSA Base, Strong or Enhanced CP) 
1234  * of the CSP is determined via the pVTable->pszProvName string.
1235  *
1236  * PARAMS
1237  *  pszContainerName [I] Name of the key container.
1238  *  pVTable          [I] Callback functions and context info provided by the OS
1239  *
1240  * RETURNS
1241  *  Success: Handle to the new key container.
1242  *  Failure: INVALID_HANDLE_VALUE
1243  */
1244 static HCRYPTPROV new_key_container(PCCH pszContainerName, DWORD dwFlags, const VTableProvStruc *pVTable)
1245 {
1246     KEYCONTAINER *pKeyContainer;
1247     HCRYPTPROV hKeyContainer;
1248
1249     hKeyContainer = new_object(&handle_table, sizeof(KEYCONTAINER), RSAENH_MAGIC_CONTAINER,
1250                                destroy_key_container, (OBJECTHDR**)&pKeyContainer);
1251     if (hKeyContainer != (HCRYPTPROV)INVALID_HANDLE_VALUE)
1252     {
1253         lstrcpynA(pKeyContainer->szName, pszContainerName, MAX_PATH);
1254         pKeyContainer->dwFlags = dwFlags;
1255         pKeyContainer->dwEnumAlgsCtr = 0;
1256         pKeyContainer->hKeyExchangeKeyPair = (HCRYPTKEY)INVALID_HANDLE_VALUE;
1257         pKeyContainer->hSignatureKeyPair = (HCRYPTKEY)INVALID_HANDLE_VALUE;
1258         if (pVTable && pVTable->pszProvName) {
1259             lstrcpynA(pKeyContainer->szProvName, pVTable->pszProvName, MAX_PATH);
1260             if (!strcmp(pVTable->pszProvName, MS_DEF_PROV_A)) {
1261                 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_BASE;
1262             } else if (!strcmp(pVTable->pszProvName, MS_ENHANCED_PROV_A)) {
1263                 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_ENHANCED;
1264             } else if (!strcmp(pVTable->pszProvName, MS_DEF_RSA_SCHANNEL_PROV_A)) { 
1265                 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_SCHANNEL;
1266             } else if (!strcmp(pVTable->pszProvName, MS_ENH_RSA_AES_PROV_A)) {
1267                 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_AES;
1268             } else {
1269                 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_STRONG;
1270             }
1271         }
1272
1273         /* The new key container has to be inserted into the CSP immediately 
1274          * after creation to be available for CPGetProvParam's PP_ENUMCONTAINERS. */
1275         if (!(dwFlags & CRYPT_VERIFYCONTEXT)) {
1276             HKEY hKey;
1277
1278             if (create_container_key(pKeyContainer, KEY_WRITE, &hKey))
1279                 RegCloseKey(hKey);
1280         }
1281     }
1282
1283     return hKeyContainer;
1284 }
1285
1286 /******************************************************************************
1287  * read_key_value [Internal]
1288  *
1289  * Reads a key pair value from the registry
1290  *
1291  * PARAMS
1292  *  hKeyContainer [I] Crypt provider to use to import the key
1293  *  hKey          [I] Registry key from which to read the key pair
1294  *  dwKeySpec     [I] AT_KEYEXCHANGE or AT_SIGNATURE
1295  *  dwFlags       [I] Flags for unprotecting the key
1296  *  phCryptKey    [O] Returned key
1297  */
1298 static BOOL read_key_value(HCRYPTPROV hKeyContainer, HKEY hKey, DWORD dwKeySpec, DWORD dwFlags, HCRYPTKEY *phCryptKey)
1299 {
1300     LPCSTR szValueName;
1301     DWORD dwValueType, dwLen;
1302     BYTE *pbKey;
1303     DATA_BLOB blobIn, blobOut;
1304     BOOL ret = FALSE;
1305
1306     if (!(szValueName = map_key_spec_to_key_pair_name(dwKeySpec)))
1307         return FALSE;
1308     if (RegQueryValueExA(hKey, szValueName, 0, &dwValueType, NULL, &dwLen) ==
1309         ERROR_SUCCESS)
1310     {
1311         pbKey = HeapAlloc(GetProcessHeap(), 0, dwLen);
1312         if (pbKey)
1313         {
1314             if (RegQueryValueExA(hKey, szValueName, 0, &dwValueType, pbKey, &dwLen) ==
1315                 ERROR_SUCCESS)
1316             {
1317                 blobIn.pbData = pbKey;
1318                 blobIn.cbData = dwLen;
1319
1320                 if (CryptUnprotectData(&blobIn, NULL, NULL, NULL, NULL,
1321                     dwFlags, &blobOut))
1322                 {
1323                     ret = import_key(hKeyContainer, blobOut.pbData, blobOut.cbData, 0, 0,
1324                                      FALSE, phCryptKey);
1325                     LocalFree(blobOut.pbData);
1326                 }
1327             }
1328             HeapFree(GetProcessHeap(), 0, pbKey);
1329         }
1330     }
1331     if (ret)
1332     {
1333         CRYPTKEY *pKey;
1334
1335         if (lookup_handle(&handle_table, *phCryptKey, RSAENH_MAGIC_KEY,
1336                           (OBJECTHDR**)&pKey))
1337         {
1338             if ((szValueName = map_key_spec_to_permissions_name(dwKeySpec)))
1339             {
1340                 dwLen = sizeof(pKey->dwPermissions);
1341                 RegQueryValueExA(hKey, szValueName, 0, NULL,
1342                                  (BYTE *)&pKey->dwPermissions, &dwLen);
1343             }
1344         }
1345     }
1346     return ret;
1347 }
1348
1349 /******************************************************************************
1350  * read_key_container [Internal]
1351  *
1352  * Tries to read the persistent state of the key container (mainly the signature
1353  * and key exchange private keys) given by pszContainerName.
1354  *
1355  * PARAMS
1356  *  pszContainerName [I] Name of the key container to read from the registry
1357  *  pVTable          [I] Pointer to context data provided by the operating system
1358  *
1359  * RETURNS
1360  *  Success: Handle to the key container read from the registry
1361  *  Failure: INVALID_HANDLE_VALUE
1362  */
1363 static HCRYPTPROV read_key_container(PCHAR pszContainerName, DWORD dwFlags, const VTableProvStruc *pVTable)
1364 {
1365     HKEY hKey;
1366     KEYCONTAINER *pKeyContainer;
1367     HCRYPTPROV hKeyContainer;
1368     HCRYPTKEY hCryptKey;
1369
1370     if (!open_container_key(pszContainerName, dwFlags, &hKey))
1371     {
1372         SetLastError(NTE_BAD_KEYSET);
1373         return (HCRYPTPROV)INVALID_HANDLE_VALUE;
1374     }
1375
1376     hKeyContainer = new_key_container(pszContainerName, dwFlags, pVTable);
1377     if (hKeyContainer != (HCRYPTPROV)INVALID_HANDLE_VALUE)
1378     {
1379         DWORD dwProtectFlags = (dwFlags & CRYPT_MACHINE_KEYSET) ?
1380             CRYPTPROTECT_LOCAL_MACHINE : 0;
1381
1382         if (!lookup_handle(&handle_table, hKeyContainer, RSAENH_MAGIC_CONTAINER, 
1383                            (OBJECTHDR**)&pKeyContainer))
1384             return (HCRYPTPROV)INVALID_HANDLE_VALUE;
1385     
1386         /* read_key_value calls import_key, which calls import_private_key,
1387          * which implicitly installs the key value into the appropriate key
1388          * container key.  Thus the ref count is incremented twice, once for
1389          * the output key value, and once for the implicit install, and needs
1390          * to be decremented to balance the two.
1391          */
1392         if (read_key_value(hKeyContainer, hKey, AT_KEYEXCHANGE,
1393             dwProtectFlags, &hCryptKey))
1394             release_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY);
1395         if (read_key_value(hKeyContainer, hKey, AT_SIGNATURE,
1396             dwProtectFlags, &hCryptKey))
1397             release_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY);
1398     }
1399
1400     return hKeyContainer;
1401 }
1402
1403 /******************************************************************************
1404  * build_hash_signature [Internal]
1405  *
1406  * Builds a padded version of a hash to match the length of the RSA key modulus.
1407  *
1408  * PARAMS
1409  *  pbSignature [O] The padded hash object is stored here.
1410  *  dwLen       [I] Length of the pbSignature buffer.
1411  *  aiAlgid     [I] Algorithm identifier of the hash to be padded.
1412  *  abHashValue [I] The value of the hash object.
1413  *  dwHashLen   [I] Length of the hash value.
1414  *  dwFlags     [I] Selection of padding algorithm.
1415  *
1416  * RETURNS
1417  *  Success: TRUE
1418  *  Failure: FALSE (NTE_BAD_ALGID)
1419  */
1420 static BOOL build_hash_signature(BYTE *pbSignature, DWORD dwLen, ALG_ID aiAlgid, 
1421                                  CONST BYTE *abHashValue, DWORD dwHashLen, DWORD dwFlags) 
1422 {
1423     /* These prefixes are meant to be concatenated with hash values of the
1424      * respective kind to form a PKCS #7 DigestInfo. */
1425     static const struct tagOIDDescriptor {
1426         ALG_ID aiAlgid;
1427         DWORD dwLen;
1428         CONST BYTE abOID[19];
1429     } aOIDDescriptor[8] = {
1430         { CALG_MD2, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48,
1431                           0x86, 0xf7, 0x0d, 0x02, 0x02, 0x05, 0x00, 0x04, 0x10 } },
1432         { CALG_MD4, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 
1433                           0x86, 0xf7, 0x0d, 0x02, 0x04, 0x05, 0x00, 0x04, 0x10 } },
1434         { CALG_MD5, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48,
1435                           0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10 } },
1436         { CALG_SHA, 15, { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 
1437                           0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 } },
1438         { CALG_SHA_256, 19, { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
1439                               0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01,
1440                               0x05, 0x00, 0x04, 0x20 } },
1441         { CALG_SHA_384, 19, { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
1442                               0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01,
1443                               0x05, 0x00, 0x04, 0x30 } },
1444         { CALG_SHA_384, 19, { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
1445                               0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01,
1446                               0x05, 0x00, 0x04, 0x40 } },
1447         { 0,        0,  { 0 } }
1448     };
1449     DWORD dwIdxOID, i, j;
1450
1451     for (dwIdxOID = 0; aOIDDescriptor[dwIdxOID].aiAlgid; dwIdxOID++) {
1452         if (aOIDDescriptor[dwIdxOID].aiAlgid == aiAlgid) break;
1453     }
1454     
1455     if (!aOIDDescriptor[dwIdxOID].aiAlgid) {
1456         SetLastError(NTE_BAD_ALGID);
1457         return FALSE;
1458     }
1459
1460     /* Build the padded signature */
1461     if (dwFlags & CRYPT_X931_FORMAT) {
1462         pbSignature[0] = 0x6b;
1463         for (i=1; i < dwLen - dwHashLen - 3; i++) {
1464             pbSignature[i] = 0xbb;
1465         }
1466         pbSignature[i++] = 0xba;
1467         for (j=0; j < dwHashLen; j++, i++) {
1468             pbSignature[i] = abHashValue[j];
1469         }
1470         pbSignature[i++] = 0x33;
1471         pbSignature[i++] = 0xcc;
1472     } else {
1473         pbSignature[0] = 0x00;
1474         pbSignature[1] = 0x01;
1475         if (dwFlags & CRYPT_NOHASHOID) {
1476             for (i=2; i < dwLen - 1 - dwHashLen; i++) {
1477                 pbSignature[i] = 0xff;
1478             }
1479             pbSignature[i++] = 0x00;
1480         } else {
1481             for (i=2; i < dwLen - 1 - aOIDDescriptor[dwIdxOID].dwLen - dwHashLen; i++) {
1482                 pbSignature[i] = 0xff;
1483             }
1484             pbSignature[i++] = 0x00;
1485             for (j=0; j < aOIDDescriptor[dwIdxOID].dwLen; j++) {
1486                 pbSignature[i++] = aOIDDescriptor[dwIdxOID].abOID[j];
1487             }
1488         }
1489         for (j=0; j < dwHashLen; j++) {
1490             pbSignature[i++] = abHashValue[j];
1491         }
1492     }
1493     
1494     return TRUE;
1495 }
1496
1497 /******************************************************************************
1498  * tls1_p [Internal]
1499  *
1500  * This is an implementation of the 'P_hash' helper function for TLS1's PRF.
1501  * It is used exclusively by tls1_prf. For details see RFC 2246, chapter 5.
1502  * The pseudo random stream generated by this function is exclusive or'ed with
1503  * the data in pbBuffer.
1504  *
1505  * PARAMS
1506  *  hHMAC       [I]   HMAC object, which will be used in pseudo random generation
1507  *  pblobSeed   [I]   Seed value
1508  *  pbBuffer    [I/O] Pseudo random stream will be xor'ed to the provided data
1509  *  dwBufferLen [I]   Number of pseudo random bytes desired
1510  *
1511  * RETURNS
1512  *  Success: TRUE
1513  *  Failure: FALSE
1514  */
1515 static BOOL tls1_p(HCRYPTHASH hHMAC, CONST PCRYPT_DATA_BLOB pblobSeed, PBYTE pbBuffer, DWORD dwBufferLen)
1516 {
1517     CRYPTHASH *pHMAC;
1518     BYTE abAi[RSAENH_MAX_HASH_SIZE];
1519     DWORD i = 0;
1520
1521     if (!lookup_handle(&handle_table, hHMAC, RSAENH_MAGIC_HASH, (OBJECTHDR**)&pHMAC)) {
1522         SetLastError(NTE_BAD_HASH);
1523         return FALSE;
1524     }
1525     
1526     /* compute A_1 = HMAC(seed) */
1527     init_hash(pHMAC);
1528     update_hash(pHMAC, pblobSeed->pbData, pblobSeed->cbData);
1529     finalize_hash(pHMAC);
1530     memcpy(abAi, pHMAC->abHashValue, pHMAC->dwHashSize);
1531
1532     do {
1533         /* compute HMAC(A_i + seed) */
1534         init_hash(pHMAC);
1535         update_hash(pHMAC, abAi, pHMAC->dwHashSize);
1536         update_hash(pHMAC, pblobSeed->pbData, pblobSeed->cbData);
1537         finalize_hash(pHMAC);
1538
1539         /* pseudo random stream := CONCAT_{i=1..n} ( HMAC(A_i + seed) ) */
1540         do {
1541             if (i >= dwBufferLen) break;
1542             pbBuffer[i] ^= pHMAC->abHashValue[i % pHMAC->dwHashSize];
1543             i++;
1544         } while (i % pHMAC->dwHashSize);
1545
1546         /* compute A_{i+1} = HMAC(A_i) */
1547         init_hash(pHMAC);
1548         update_hash(pHMAC, abAi, pHMAC->dwHashSize);
1549         finalize_hash(pHMAC);
1550         memcpy(abAi, pHMAC->abHashValue, pHMAC->dwHashSize);
1551     } while (i < dwBufferLen);
1552
1553     return TRUE;
1554 }
1555
1556 /******************************************************************************
1557  * tls1_prf [Internal]
1558  *
1559  * TLS1 pseudo random function as specified in RFC 2246, chapter 5
1560  *
1561  * PARAMS
1562  *  hProv       [I] Key container used to compute the pseudo random stream
1563  *  hSecret     [I] Key that holds the (pre-)master secret
1564  *  pblobLabel  [I] Descriptive label
1565  *  pblobSeed   [I] Seed value
1566  *  pbBuffer    [O] Pseudo random numbers will be stored here
1567  *  dwBufferLen [I] Number of pseudo random bytes desired
1568  *
1569  * RETURNS
1570  *  Success: TRUE
1571  *  Failure: FALSE
1572  */ 
1573 static BOOL tls1_prf(HCRYPTPROV hProv, HCRYPTPROV hSecret, CONST PCRYPT_DATA_BLOB pblobLabel,
1574                      CONST PCRYPT_DATA_BLOB pblobSeed, PBYTE pbBuffer, DWORD dwBufferLen)
1575 {
1576     HMAC_INFO hmacInfo = { 0, NULL, 0, NULL, 0 };
1577     HCRYPTHASH hHMAC = (HCRYPTHASH)INVALID_HANDLE_VALUE;
1578     HCRYPTKEY hHalfSecret = (HCRYPTKEY)INVALID_HANDLE_VALUE;
1579     CRYPTKEY *pHalfSecret, *pSecret;
1580     DWORD dwHalfSecretLen;
1581     BOOL result = FALSE;
1582     CRYPT_DATA_BLOB blobLabelSeed;
1583
1584     TRACE("(hProv=%08lx, hSecret=%08lx, pblobLabel=%p, pblobSeed=%p, pbBuffer=%p, dwBufferLen=%d)\n",
1585           hProv, hSecret, pblobLabel, pblobSeed, pbBuffer, dwBufferLen);
1586
1587     if (!lookup_handle(&handle_table, hSecret, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pSecret)) {
1588         SetLastError(NTE_FAIL);
1589         return FALSE;
1590     }
1591
1592     dwHalfSecretLen = (pSecret->dwKeyLen+1)/2;
1593     
1594     /* concatenation of the label and the seed */
1595     if (!concat_data_blobs(&blobLabelSeed, pblobLabel, pblobSeed)) goto exit;
1596    
1597     /* zero out the buffer, since two random streams will be xor'ed into it. */
1598     memset(pbBuffer, 0, dwBufferLen);
1599    
1600     /* build a 'fake' key, to hold the secret. CALG_SSL2_MASTER is used since it provides
1601      * the biggest range of valid key lengths. */
1602     hHalfSecret = new_key(hProv, CALG_SSL2_MASTER, MAKELONG(0,dwHalfSecretLen*8), &pHalfSecret);
1603     if (hHalfSecret == (HCRYPTKEY)INVALID_HANDLE_VALUE) goto exit;
1604
1605     /* Derive an HMAC_MD5 hash and call the helper function. */
1606     memcpy(pHalfSecret->abKeyValue, pSecret->abKeyValue, dwHalfSecretLen);
1607     if (!RSAENH_CPCreateHash(hProv, CALG_HMAC, hHalfSecret, 0, &hHMAC)) goto exit;
1608     hmacInfo.HashAlgid = CALG_MD5;
1609     if (!RSAENH_CPSetHashParam(hProv, hHMAC, HP_HMAC_INFO, (BYTE*)&hmacInfo, 0)) goto exit;
1610     if (!tls1_p(hHMAC, &blobLabelSeed, pbBuffer, dwBufferLen)) goto exit;
1611
1612     /* Reconfigure to HMAC_SHA hash and call helper function again. */
1613     memcpy(pHalfSecret->abKeyValue, pSecret->abKeyValue + (pSecret->dwKeyLen/2), dwHalfSecretLen);
1614     hmacInfo.HashAlgid = CALG_SHA;
1615     if (!RSAENH_CPSetHashParam(hProv, hHMAC, HP_HMAC_INFO, (BYTE*)&hmacInfo, 0)) goto exit;
1616     if (!tls1_p(hHMAC, &blobLabelSeed, pbBuffer, dwBufferLen)) goto exit;
1617     
1618     result = TRUE;
1619 exit:
1620     release_handle(&handle_table, hHalfSecret, RSAENH_MAGIC_KEY);
1621     if (hHMAC != (HCRYPTHASH)INVALID_HANDLE_VALUE) RSAENH_CPDestroyHash(hProv, hHMAC);
1622     free_data_blob(&blobLabelSeed);
1623     return result;
1624 }
1625
1626 /******************************************************************************
1627  * pad_data [Internal]
1628  *
1629  * Helper function for data padding according to PKCS1 #2
1630  *
1631  * PARAMS
1632  *  abData      [I] The data to be padded
1633  *  dwDataLen   [I] Length of the data 
1634  *  abBuffer    [O] Padded data will be stored here
1635  *  dwBufferLen [I] Length of the buffer (also length of padded data)
1636  *  dwFlags     [I] Padding format (CRYPT_SSL2_FALLBACK)
1637  *
1638  * RETURN
1639  *  Success: TRUE
1640  *  Failure: FALSE (NTE_BAD_LEN, too much data to pad)
1641  */
1642 static BOOL pad_data(CONST BYTE *abData, DWORD dwDataLen, BYTE *abBuffer, DWORD dwBufferLen, 
1643                      DWORD dwFlags)
1644 {
1645     DWORD i;
1646     
1647     /* Ensure there is enough space for PKCS1 #2 padding */
1648     if (dwDataLen > dwBufferLen-11) {
1649         SetLastError(NTE_BAD_LEN);
1650         return FALSE;
1651     }
1652
1653     memmove(abBuffer + dwBufferLen - dwDataLen, abData, dwDataLen);            
1654     
1655     abBuffer[0] = 0x00;
1656     abBuffer[1] = RSAENH_PKC_BLOCKTYPE; 
1657     for (i=2; i < dwBufferLen - dwDataLen - 1; i++) 
1658         do gen_rand_impl(&abBuffer[i], 1); while (!abBuffer[i]);
1659     if (dwFlags & CRYPT_SSL2_FALLBACK) 
1660         for (i-=8; i < dwBufferLen - dwDataLen - 1; i++) 
1661             abBuffer[i] = 0x03;
1662     abBuffer[i] = 0x00;
1663     
1664     return TRUE; 
1665 }
1666
1667 /******************************************************************************
1668  * unpad_data [Internal]
1669  *
1670  * Remove the PKCS1 padding from RSA decrypted data
1671  *
1672  * PARAMS
1673  *  abData      [I]   The padded data
1674  *  dwDataLen   [I]   Length of the padded data
1675  *  abBuffer    [O]   Data without padding will be stored here
1676  *  dwBufferLen [I/O] I: Length of the buffer, O: Length of unpadded data
1677  *  dwFlags     [I]   Currently none defined
1678  *
1679  * RETURNS
1680  *  Success: TRUE
1681  *  Failure: FALSE, (NTE_BAD_DATA, no valid PKCS1 padding or buffer too small)
1682  */
1683 static BOOL unpad_data(CONST BYTE *abData, DWORD dwDataLen, BYTE *abBuffer, DWORD *dwBufferLen, 
1684                        DWORD dwFlags)
1685 {
1686     DWORD i;
1687     
1688     for (i=2; i<dwDataLen; i++)
1689         if (!abData[i])
1690             break;
1691
1692     if ((i == dwDataLen) || (*dwBufferLen < dwDataLen - i - 1) ||
1693         (abData[0] != 0x00) || (abData[1] != RSAENH_PKC_BLOCKTYPE))
1694     {
1695         SetLastError(NTE_BAD_DATA);
1696         return FALSE;
1697     }
1698
1699     *dwBufferLen = dwDataLen - i - 1;
1700     memmove(abBuffer, abData + i + 1, *dwBufferLen);
1701     return TRUE;
1702 }
1703
1704 /******************************************************************************
1705  * CPAcquireContext (RSAENH.@)
1706  *
1707  * Acquire a handle to the key container specified by pszContainer
1708  *
1709  * PARAMS
1710  *  phProv       [O] Pointer to the location the acquired handle will be written to.
1711  *  pszContainer [I] Name of the desired key container. See Notes
1712  *  dwFlags      [I] Flags. See Notes.
1713  *  pVTable      [I] Pointer to a PVTableProvStruct containing callbacks.
1714  * 
1715  * RETURNS
1716  *  Success: TRUE
1717  *  Failure: FALSE
1718  *
1719  * NOTES
1720  *  If pszContainer is NULL or points to a zero length string the user's login 
1721  *  name will be used as the key container name.
1722  *
1723  *  If the CRYPT_NEW_KEYSET flag is set in dwFlags a new keyset will be created.
1724  *  If a keyset with the given name already exists, the function fails and sets
1725  *  last error to NTE_EXISTS. If CRYPT_NEW_KEYSET is not set and the specified
1726  *  key container does not exist, function fails and sets last error to 
1727  *  NTE_BAD_KEYSET.
1728  */                         
1729 BOOL WINAPI RSAENH_CPAcquireContext(HCRYPTPROV *phProv, LPSTR pszContainer,
1730                    DWORD dwFlags, PVTableProvStruc pVTable)
1731 {
1732     CHAR szKeyContainerName[MAX_PATH];
1733
1734     TRACE("(phProv=%p, pszContainer=%s, dwFlags=%08x, pVTable=%p)\n", phProv,
1735           debugstr_a(pszContainer), dwFlags, pVTable);
1736
1737     if (pszContainer && *pszContainer)
1738     {
1739         lstrcpynA(szKeyContainerName, pszContainer, MAX_PATH);
1740     } 
1741     else
1742     {
1743         DWORD dwLen = sizeof(szKeyContainerName);
1744         if (!GetUserNameA(szKeyContainerName, &dwLen)) return FALSE;
1745     }
1746
1747     switch (dwFlags & (CRYPT_NEWKEYSET|CRYPT_VERIFYCONTEXT|CRYPT_DELETEKEYSET)) 
1748     {
1749         case 0:
1750             *phProv = read_key_container(szKeyContainerName, dwFlags, pVTable);
1751             break;
1752
1753         case CRYPT_DELETEKEYSET:
1754             return delete_container_key(szKeyContainerName, dwFlags);
1755
1756         case CRYPT_NEWKEYSET:
1757             *phProv = read_key_container(szKeyContainerName, dwFlags, pVTable);
1758             if (*phProv != (HCRYPTPROV)INVALID_HANDLE_VALUE) 
1759             {
1760                 release_handle(&handle_table, *phProv, RSAENH_MAGIC_CONTAINER);
1761                 TRACE("Can't create new keyset, already exists\n");
1762                 SetLastError(NTE_EXISTS);
1763                 return FALSE;
1764             }
1765             *phProv = new_key_container(szKeyContainerName, dwFlags, pVTable);
1766             break;
1767
1768         case CRYPT_VERIFYCONTEXT|CRYPT_NEWKEYSET:
1769         case CRYPT_VERIFYCONTEXT:
1770             if (pszContainer && *pszContainer) {
1771                 TRACE("pszContainer should be empty\n");
1772                 SetLastError(NTE_BAD_FLAGS);
1773                 return FALSE;
1774             }
1775             *phProv = new_key_container("", dwFlags, pVTable);
1776             break;
1777             
1778         default:
1779             *phProv = (HCRYPTPROV)INVALID_HANDLE_VALUE;
1780             SetLastError(NTE_BAD_FLAGS);
1781             return FALSE;
1782     }
1783                 
1784     if (*phProv != (HCRYPTPROV)INVALID_HANDLE_VALUE) {
1785         SetLastError(ERROR_SUCCESS);
1786         return TRUE;
1787     } else {
1788         return FALSE;
1789     }
1790 }
1791
1792 /******************************************************************************
1793  * CPCreateHash (RSAENH.@)
1794  *
1795  * CPCreateHash creates and initalizes a new hash object.
1796  *
1797  * PARAMS
1798  *  hProv   [I] Handle to the key container to which the new hash will belong.
1799  *  Algid   [I] Identifies the hash algorithm, which will be used for the hash.
1800  *  hKey    [I] Handle to a session key applied for keyed hashes.
1801  *  dwFlags [I] Currently no flags defined. Must be zero.
1802  *  phHash  [O] Points to the location where a handle to the new hash will be stored.
1803  *
1804  * RETURNS
1805  *  Success: TRUE
1806  *  Failure: FALSE
1807  *
1808  * NOTES
1809  *  hKey is a handle to a session key applied in keyed hashes like MAC and HMAC.
1810  *  If a normal hash object is to be created (like e.g. MD2 or SHA1) hKey must be zero.
1811  */
1812 BOOL WINAPI RSAENH_CPCreateHash(HCRYPTPROV hProv, ALG_ID Algid, HCRYPTKEY hKey, DWORD dwFlags, 
1813                                 HCRYPTHASH *phHash)
1814 {
1815     CRYPTKEY *pCryptKey;
1816     CRYPTHASH *pCryptHash;
1817     const PROV_ENUMALGS_EX *peaAlgidInfo;
1818         
1819     TRACE("(hProv=%08lx, Algid=%08x, hKey=%08lx, dwFlags=%08x, phHash=%p)\n", hProv, Algid, hKey,
1820           dwFlags, phHash);
1821
1822     peaAlgidInfo = get_algid_info(hProv, Algid);
1823     if (!peaAlgidInfo) return FALSE;
1824
1825     if (dwFlags)
1826     {
1827         SetLastError(NTE_BAD_FLAGS);
1828         return FALSE;
1829     }
1830
1831     if (Algid == CALG_MAC || Algid == CALG_HMAC || Algid == CALG_SCHANNEL_MASTER_HASH || 
1832         Algid == CALG_TLS1PRF) 
1833     {
1834         if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey)) {
1835             SetLastError(NTE_BAD_KEY);
1836             return FALSE;
1837         }
1838
1839         if ((Algid == CALG_MAC) && (GET_ALG_TYPE(pCryptKey->aiAlgid) != ALG_TYPE_BLOCK)) {
1840             SetLastError(NTE_BAD_KEY);
1841             return FALSE;
1842         }
1843
1844         if ((Algid == CALG_SCHANNEL_MASTER_HASH || Algid == CALG_TLS1PRF) && 
1845             (pCryptKey->aiAlgid != CALG_TLS1_MASTER)) 
1846         {
1847             SetLastError(NTE_BAD_KEY);
1848             return FALSE;
1849         }
1850
1851         if ((Algid == CALG_TLS1PRF) && (pCryptKey->dwState != RSAENH_KEYSTATE_MASTERKEY)) {
1852             SetLastError(NTE_BAD_KEY_STATE);
1853             return FALSE;
1854         }
1855     }
1856
1857     *phHash = new_object(&handle_table, sizeof(CRYPTHASH), RSAENH_MAGIC_HASH,
1858                          destroy_hash, (OBJECTHDR**)&pCryptHash);
1859     if (!pCryptHash) return FALSE;
1860
1861     pCryptHash->aiAlgid = Algid;
1862     pCryptHash->hKey = hKey;
1863     pCryptHash->hProv = hProv;
1864     pCryptHash->dwState = RSAENH_HASHSTATE_HASHING;
1865     pCryptHash->pHMACInfo = NULL;
1866     pCryptHash->dwHashSize = peaAlgidInfo->dwDefaultLen >> 3;
1867     init_data_blob(&pCryptHash->tpPRFParams.blobLabel);
1868     init_data_blob(&pCryptHash->tpPRFParams.blobSeed);
1869
1870     if (Algid == CALG_SCHANNEL_MASTER_HASH) {
1871         static const char keyex[] = "key expansion";
1872         BYTE key_expansion[sizeof keyex];
1873         CRYPT_DATA_BLOB blobRandom, blobKeyExpansion = { 13, key_expansion };
1874
1875         memcpy( key_expansion, keyex, sizeof keyex );
1876         
1877         if (pCryptKey->dwState != RSAENH_KEYSTATE_MASTERKEY) {
1878             static const char msec[] = "master secret";
1879             BYTE master_secret[sizeof msec];
1880             CRYPT_DATA_BLOB blobLabel = { 13, master_secret };
1881             BYTE abKeyValue[48];
1882
1883             memcpy( master_secret, msec, sizeof msec );
1884     
1885             /* See RFC 2246, chapter 8.1 */
1886             if (!concat_data_blobs(&blobRandom, 
1887                                    &pCryptKey->siSChannelInfo.blobClientRandom, 
1888                                    &pCryptKey->siSChannelInfo.blobServerRandom))
1889             {
1890                 return FALSE;
1891             }
1892             tls1_prf(hProv, hKey, &blobLabel, &blobRandom, abKeyValue, 48);
1893             pCryptKey->dwState = RSAENH_KEYSTATE_MASTERKEY; 
1894             memcpy(pCryptKey->abKeyValue, abKeyValue, 48);
1895             free_data_blob(&blobRandom);
1896         }
1897
1898         /* See RFC 2246, chapter 6.3 */
1899         if (!concat_data_blobs(&blobRandom, 
1900                                   &pCryptKey->siSChannelInfo.blobServerRandom, 
1901                                   &pCryptKey->siSChannelInfo.blobClientRandom))
1902         {
1903             return FALSE;
1904         }
1905         tls1_prf(hProv, hKey, &blobKeyExpansion, &blobRandom, pCryptHash->abHashValue, 
1906                  RSAENH_MAX_HASH_SIZE);
1907         free_data_blob(&blobRandom);
1908     }
1909
1910     return init_hash(pCryptHash);
1911 }
1912
1913 /******************************************************************************
1914  * CPDestroyHash (RSAENH.@)
1915  * 
1916  * Releases the handle to a hash object. The object is destroyed if it's reference
1917  * count reaches zero.
1918  *
1919  * PARAMS
1920  *  hProv [I] Handle to the key container to which the hash object belongs.
1921  *  hHash [I] Handle to the hash object to be released.
1922  *
1923  * RETURNS
1924  *  Success: TRUE
1925  *  Failure: FALSE 
1926  */
1927 BOOL WINAPI RSAENH_CPDestroyHash(HCRYPTPROV hProv, HCRYPTHASH hHash)
1928 {
1929     TRACE("(hProv=%08lx, hHash=%08lx)\n", hProv, hHash);
1930      
1931     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
1932     {
1933         SetLastError(NTE_BAD_UID);
1934         return FALSE;
1935     }
1936         
1937     if (!release_handle(&handle_table, hHash, RSAENH_MAGIC_HASH)) 
1938     {
1939         SetLastError(NTE_BAD_HASH);
1940         return FALSE;
1941     }
1942     
1943     return TRUE;
1944 }
1945
1946 /******************************************************************************
1947  * CPDestroyKey (RSAENH.@)
1948  *
1949  * Releases the handle to a key object. The object is destroyed if it's reference
1950  * count reaches zero.
1951  *
1952  * PARAMS
1953  *  hProv [I] Handle to the key container to which the key object belongs.
1954  *  hKey  [I] Handle to the key object to be released.
1955  *
1956  * RETURNS
1957  *  Success: TRUE
1958  *  Failure: FALSE
1959  */
1960 BOOL WINAPI RSAENH_CPDestroyKey(HCRYPTPROV hProv, HCRYPTKEY hKey)
1961 {
1962     TRACE("(hProv=%08lx, hKey=%08lx)\n", hProv, hKey);
1963         
1964     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
1965     {
1966         SetLastError(NTE_BAD_UID);
1967         return FALSE;
1968     }
1969         
1970     if (!release_handle(&handle_table, hKey, RSAENH_MAGIC_KEY)) 
1971     {
1972         SetLastError(NTE_BAD_KEY);
1973         return FALSE;
1974     }
1975     
1976     return TRUE;
1977 }
1978
1979 /******************************************************************************
1980  * CPDuplicateHash (RSAENH.@)
1981  *
1982  * Clones a hash object including it's current state.
1983  *
1984  * PARAMS
1985  *  hUID        [I] Handle to the key container the hash belongs to.
1986  *  hHash       [I] Handle to the hash object to be cloned.
1987  *  pdwReserved [I] Reserved. Must be NULL.
1988  *  dwFlags     [I] No flags are currently defined. Must be 0.
1989  *  phHash      [O] Handle to the cloned hash object.
1990  *
1991  * RETURNS
1992  *  Success: TRUE.
1993  *  Failure: FALSE.
1994  */
1995 BOOL WINAPI RSAENH_CPDuplicateHash(HCRYPTPROV hUID, HCRYPTHASH hHash, DWORD *pdwReserved, 
1996                                    DWORD dwFlags, HCRYPTHASH *phHash)
1997 {
1998     CRYPTHASH *pSrcHash, *pDestHash;
1999     
2000     TRACE("(hUID=%08lx, hHash=%08lx, pdwReserved=%p, dwFlags=%08x, phHash=%p)\n", hUID, hHash,
2001            pdwReserved, dwFlags, phHash);
2002
2003     if (!is_valid_handle(&handle_table, hUID, RSAENH_MAGIC_CONTAINER))
2004     {
2005         SetLastError(NTE_BAD_UID);
2006         return FALSE;
2007     }
2008
2009     if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH, (OBJECTHDR**)&pSrcHash))
2010     {
2011         SetLastError(NTE_BAD_HASH);
2012         return FALSE;
2013     }
2014
2015     if (!phHash || pdwReserved || dwFlags) 
2016     {
2017         SetLastError(ERROR_INVALID_PARAMETER);
2018         return FALSE;
2019     }
2020
2021     *phHash = new_object(&handle_table, sizeof(CRYPTHASH), RSAENH_MAGIC_HASH,
2022                          destroy_hash, (OBJECTHDR**)&pDestHash);
2023     if (*phHash != (HCRYPTHASH)INVALID_HANDLE_VALUE)
2024     {
2025         *pDestHash = *pSrcHash;
2026         duplicate_hash_impl(pSrcHash->aiAlgid, &pSrcHash->context, &pDestHash->context);
2027         copy_hmac_info(&pDestHash->pHMACInfo, pSrcHash->pHMACInfo);
2028         copy_data_blob(&pDestHash->tpPRFParams.blobLabel, &pSrcHash->tpPRFParams.blobLabel);
2029         copy_data_blob(&pDestHash->tpPRFParams.blobSeed, &pSrcHash->tpPRFParams.blobSeed);
2030     }
2031
2032     return *phHash != (HCRYPTHASH)INVALID_HANDLE_VALUE;
2033 }
2034
2035 /******************************************************************************
2036  * CPDuplicateKey (RSAENH.@)
2037  *
2038  * Clones a key object including it's current state.
2039  *
2040  * PARAMS
2041  *  hUID        [I] Handle to the key container the hash belongs to.
2042  *  hKey        [I] Handle to the key object to be cloned.
2043  *  pdwReserved [I] Reserved. Must be NULL.
2044  *  dwFlags     [I] No flags are currently defined. Must be 0.
2045  *  phHash      [O] Handle to the cloned key object.
2046  *
2047  * RETURNS
2048  *  Success: TRUE.
2049  *  Failure: FALSE.
2050  */
2051 BOOL WINAPI RSAENH_CPDuplicateKey(HCRYPTPROV hUID, HCRYPTKEY hKey, DWORD *pdwReserved, 
2052                                   DWORD dwFlags, HCRYPTKEY *phKey)
2053 {
2054     CRYPTKEY *pSrcKey, *pDestKey;
2055     
2056     TRACE("(hUID=%08lx, hKey=%08lx, pdwReserved=%p, dwFlags=%08x, phKey=%p)\n", hUID, hKey,
2057           pdwReserved, dwFlags, phKey);
2058
2059     if (!is_valid_handle(&handle_table, hUID, RSAENH_MAGIC_CONTAINER))
2060     {
2061         SetLastError(NTE_BAD_UID);
2062         return FALSE;
2063     }
2064
2065     if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pSrcKey))
2066     {
2067         SetLastError(NTE_BAD_KEY);
2068         return FALSE;
2069     }
2070
2071     if (!phKey || pdwReserved || dwFlags) 
2072     {
2073         SetLastError(ERROR_INVALID_PARAMETER);
2074         return FALSE;
2075     }
2076
2077     *phKey = new_object(&handle_table, sizeof(CRYPTKEY), RSAENH_MAGIC_KEY, destroy_key,
2078                         (OBJECTHDR**)&pDestKey);
2079     if (*phKey != (HCRYPTKEY)INVALID_HANDLE_VALUE)
2080     {
2081         *pDestKey = *pSrcKey;
2082         copy_data_blob(&pDestKey->siSChannelInfo.blobServerRandom,
2083                        &pSrcKey->siSChannelInfo.blobServerRandom);
2084         copy_data_blob(&pDestKey->siSChannelInfo.blobClientRandom, 
2085                        &pSrcKey->siSChannelInfo.blobClientRandom);
2086         duplicate_key_impl(pSrcKey->aiAlgid, &pSrcKey->context, &pDestKey->context);
2087         return TRUE;
2088     }
2089     else
2090     {
2091         return FALSE;
2092     }
2093 }
2094
2095 /******************************************************************************
2096  * CPEncrypt (RSAENH.@)
2097  *
2098  * Encrypt data.
2099  *
2100  * PARAMS
2101  *  hProv      [I]   The key container hKey and hHash belong to.
2102  *  hKey       [I]   The key used to encrypt the data.
2103  *  hHash      [I]   An optional hash object for parallel hashing. See notes.
2104  *  Final      [I]   Indicates if this is the last block of data to encrypt.
2105  *  dwFlags    [I]   Currently no flags defined. Must be zero.
2106  *  pbData     [I/O] Pointer to the data to encrypt. Encrypted data will also be stored there. 
2107  *  pdwDataLen [I/O] I: Length of data to encrypt, O: Length of encrypted data.
2108  *  dwBufLen   [I]   Size of the buffer at pbData.
2109  *
2110  * RETURNS
2111  *  Success: TRUE.
2112  *  Failure: FALSE.
2113  *
2114  * NOTES
2115  *  If a hash object handle is provided in hHash, it will be updated with the plaintext. 
2116  *  This is useful for message signatures.
2117  *
2118  *  This function uses the standard WINAPI protocol for querying data of dynamic length. 
2119  */
2120 BOOL WINAPI RSAENH_CPEncrypt(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final, 
2121                              DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen, DWORD dwBufLen)
2122 {
2123     CRYPTKEY *pCryptKey;
2124     BYTE *in, out[RSAENH_MAX_BLOCK_SIZE], o[RSAENH_MAX_BLOCK_SIZE];
2125     DWORD dwEncryptedLen, i, j, k;
2126         
2127     TRACE("(hProv=%08lx, hKey=%08lx, hHash=%08lx, Final=%d, dwFlags=%08x, pbData=%p, "
2128           "pdwDataLen=%p, dwBufLen=%d)\n", hProv, hKey, hHash, Final, dwFlags, pbData, pdwDataLen,
2129           dwBufLen);
2130     
2131     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2132     {
2133         SetLastError(NTE_BAD_UID);
2134         return FALSE;
2135     }
2136
2137     if (dwFlags)
2138     {
2139         SetLastError(NTE_BAD_FLAGS);
2140         return FALSE;
2141     }
2142
2143     if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2144     {
2145         SetLastError(NTE_BAD_KEY);
2146         return FALSE;
2147     }
2148
2149     if (pCryptKey->dwState == RSAENH_KEYSTATE_IDLE) 
2150         pCryptKey->dwState = RSAENH_KEYSTATE_ENCRYPTING;
2151
2152     if (pCryptKey->dwState != RSAENH_KEYSTATE_ENCRYPTING) 
2153     {
2154         SetLastError(NTE_BAD_DATA);
2155         return FALSE;
2156     }
2157
2158     if (is_valid_handle(&handle_table, hHash, RSAENH_MAGIC_HASH)) {
2159         if (!RSAENH_CPHashData(hProv, hHash, pbData, *pdwDataLen, 0)) return FALSE;
2160     }
2161     
2162     if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_BLOCK) {
2163         if (!Final && (*pdwDataLen % pCryptKey->dwBlockLen)) {
2164             SetLastError(NTE_BAD_DATA);
2165             return FALSE;
2166         }
2167
2168         dwEncryptedLen = (*pdwDataLen/pCryptKey->dwBlockLen+(Final?1:0))*pCryptKey->dwBlockLen;
2169
2170         if (pbData == NULL) {
2171             *pdwDataLen = dwEncryptedLen;
2172             return TRUE;
2173         }
2174         else if (dwEncryptedLen > dwBufLen) {
2175             *pdwDataLen = dwEncryptedLen;
2176             SetLastError(ERROR_MORE_DATA);
2177             return FALSE;
2178         }
2179
2180         /* Pad final block with length bytes */
2181         for (i=*pdwDataLen; i<dwEncryptedLen; i++) pbData[i] = dwEncryptedLen - *pdwDataLen;
2182         *pdwDataLen = dwEncryptedLen;
2183
2184         for (i=0, in=pbData; i<*pdwDataLen; i+=pCryptKey->dwBlockLen, in+=pCryptKey->dwBlockLen) {
2185             switch (pCryptKey->dwMode) {
2186                 case CRYPT_MODE_ECB:
2187                     encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out, 
2188                                        RSAENH_ENCRYPT);
2189                     break;
2190                 
2191                 case CRYPT_MODE_CBC:
2192                     for (j=0; j<pCryptKey->dwBlockLen; j++) in[j] ^= pCryptKey->abChainVector[j];
2193                     encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out, 
2194                                        RSAENH_ENCRYPT);
2195                     memcpy(pCryptKey->abChainVector, out, pCryptKey->dwBlockLen);
2196                     break;
2197
2198                 case CRYPT_MODE_CFB:
2199                     for (j=0; j<pCryptKey->dwBlockLen; j++) {
2200                         encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, 
2201                                            pCryptKey->abChainVector, o, RSAENH_ENCRYPT);
2202                         out[j] = in[j] ^ o[0];
2203                         for (k=0; k<pCryptKey->dwBlockLen-1; k++) 
2204                             pCryptKey->abChainVector[k] = pCryptKey->abChainVector[k+1];
2205                         pCryptKey->abChainVector[k] = out[j];
2206                     }
2207                     break;
2208                     
2209                 default:
2210                     SetLastError(NTE_BAD_ALGID);
2211                     return FALSE;
2212             }
2213             memcpy(in, out, pCryptKey->dwBlockLen); 
2214         }
2215     } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_STREAM) {
2216         if (pbData == NULL) {
2217             *pdwDataLen = dwBufLen;
2218             return TRUE;
2219         }
2220         encrypt_stream_impl(pCryptKey->aiAlgid, &pCryptKey->context, pbData, *pdwDataLen);
2221     } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_RSA) {
2222         if (pCryptKey->aiAlgid == CALG_RSA_SIGN) {
2223             SetLastError(NTE_BAD_KEY);
2224             return FALSE;
2225         }
2226         if (!pbData) {
2227             *pdwDataLen = pCryptKey->dwBlockLen;
2228             return TRUE;
2229         }
2230         if (dwBufLen < pCryptKey->dwBlockLen) {
2231             SetLastError(ERROR_MORE_DATA);
2232             return FALSE;
2233         }
2234         if (!pad_data(pbData, *pdwDataLen, pbData, pCryptKey->dwBlockLen, dwFlags)) return FALSE;
2235         encrypt_block_impl(pCryptKey->aiAlgid, PK_PUBLIC, &pCryptKey->context, pbData, pbData, RSAENH_ENCRYPT);
2236         *pdwDataLen = pCryptKey->dwBlockLen;
2237         Final = TRUE;
2238     } else {
2239         SetLastError(NTE_BAD_TYPE);
2240         return FALSE;
2241     }
2242
2243     if (Final) setup_key(pCryptKey);
2244
2245     return TRUE;
2246 }
2247
2248 /******************************************************************************
2249  * CPDecrypt (RSAENH.@)
2250  *
2251  * Decrypt data.
2252  *
2253  * PARAMS
2254  *  hProv      [I]   The key container hKey and hHash belong to.
2255  *  hKey       [I]   The key used to decrypt the data.
2256  *  hHash      [I]   An optional hash object for parallel hashing. See notes.
2257  *  Final      [I]   Indicates if this is the last block of data to decrypt.
2258  *  dwFlags    [I]   Currently no flags defined. Must be zero.
2259  *  pbData     [I/O] Pointer to the data to decrypt. Plaintext will also be stored there. 
2260  *  pdwDataLen [I/O] I: Length of ciphertext, O: Length of plaintext.
2261  *
2262  * RETURNS
2263  *  Success: TRUE.
2264  *  Failure: FALSE.
2265  *
2266  * NOTES
2267  *  If a hash object handle is provided in hHash, it will be updated with the plaintext. 
2268  *  This is useful for message signatures.
2269  *
2270  *  This function uses the standard WINAPI protocol for querying data of dynamic length. 
2271  */
2272 BOOL WINAPI RSAENH_CPDecrypt(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final, 
2273                              DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2274 {
2275     CRYPTKEY *pCryptKey;
2276     BYTE *in, out[RSAENH_MAX_BLOCK_SIZE], o[RSAENH_MAX_BLOCK_SIZE];
2277     DWORD i, j, k;
2278     DWORD dwMax;
2279
2280     TRACE("(hProv=%08lx, hKey=%08lx, hHash=%08lx, Final=%d, dwFlags=%08x, pbData=%p, "
2281           "pdwDataLen=%p)\n", hProv, hKey, hHash, Final, dwFlags, pbData, pdwDataLen);
2282     
2283     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2284     {
2285         SetLastError(NTE_BAD_UID);
2286         return FALSE;
2287     }
2288
2289     if (dwFlags)
2290     {
2291         SetLastError(NTE_BAD_FLAGS);
2292         return FALSE;
2293     }
2294
2295     if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2296     {
2297         SetLastError(NTE_BAD_KEY);
2298         return FALSE;
2299     }
2300
2301     if (pCryptKey->dwState == RSAENH_KEYSTATE_IDLE) 
2302         pCryptKey->dwState = RSAENH_KEYSTATE_ENCRYPTING;
2303
2304     if (pCryptKey->dwState != RSAENH_KEYSTATE_ENCRYPTING)
2305     {
2306         SetLastError(NTE_BAD_DATA);
2307         return FALSE;
2308     }
2309
2310     dwMax=*pdwDataLen;
2311
2312     if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_BLOCK) {
2313         for (i=0, in=pbData; i<*pdwDataLen; i+=pCryptKey->dwBlockLen, in+=pCryptKey->dwBlockLen) {
2314             switch (pCryptKey->dwMode) {
2315                 case CRYPT_MODE_ECB:
2316                     encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out, 
2317                                        RSAENH_DECRYPT);
2318                     break;
2319                 
2320                 case CRYPT_MODE_CBC:
2321                     encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out, 
2322                                        RSAENH_DECRYPT);
2323                     for (j=0; j<pCryptKey->dwBlockLen; j++) out[j] ^= pCryptKey->abChainVector[j];
2324                     memcpy(pCryptKey->abChainVector, in, pCryptKey->dwBlockLen);
2325                     break;
2326
2327                 case CRYPT_MODE_CFB:
2328                     for (j=0; j<pCryptKey->dwBlockLen; j++) {
2329                         encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, 
2330                                            pCryptKey->abChainVector, o, RSAENH_ENCRYPT);
2331                         out[j] = in[j] ^ o[0];
2332                         for (k=0; k<pCryptKey->dwBlockLen-1; k++) 
2333                             pCryptKey->abChainVector[k] = pCryptKey->abChainVector[k+1];
2334                         pCryptKey->abChainVector[k] = in[j];
2335                     }
2336                     break;
2337                     
2338                 default:
2339                     SetLastError(NTE_BAD_ALGID);
2340                     return FALSE;
2341             }
2342             memcpy(in, out, pCryptKey->dwBlockLen);
2343         }
2344         if (Final) {
2345             if (pbData[*pdwDataLen-1] &&
2346              pbData[*pdwDataLen-1] <= pCryptKey->dwBlockLen &&
2347              pbData[*pdwDataLen-1] <= *pdwDataLen) {
2348                 BOOL padOkay = TRUE;
2349
2350                 /* check that every bad byte has the same value */
2351                 for (i = 1; padOkay && i < pbData[*pdwDataLen-1]; i++)
2352                     if (pbData[*pdwDataLen - i - 1] != pbData[*pdwDataLen - 1])
2353                         padOkay = FALSE;
2354                 if (padOkay)
2355                     *pdwDataLen -= pbData[*pdwDataLen-1];
2356                 else {
2357                     SetLastError(NTE_BAD_DATA);
2358                     return FALSE;
2359                 }
2360             }
2361             else {
2362                 SetLastError(NTE_BAD_DATA);
2363                 return FALSE;
2364             }
2365         }
2366
2367     } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_STREAM) {
2368         encrypt_stream_impl(pCryptKey->aiAlgid, &pCryptKey->context, pbData, *pdwDataLen);
2369     } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_RSA) {
2370         if (pCryptKey->aiAlgid == CALG_RSA_SIGN) {
2371             SetLastError(NTE_BAD_KEY);
2372             return FALSE;
2373         }
2374         encrypt_block_impl(pCryptKey->aiAlgid, PK_PRIVATE, &pCryptKey->context, pbData, pbData, RSAENH_DECRYPT);
2375         if (!unpad_data(pbData, pCryptKey->dwBlockLen, pbData, pdwDataLen, dwFlags)) return FALSE;
2376         Final = TRUE;
2377     } else {
2378         SetLastError(NTE_BAD_TYPE);
2379         return FALSE;
2380     } 
2381     
2382     if (Final) setup_key(pCryptKey);
2383
2384     if (is_valid_handle(&handle_table, hHash, RSAENH_MAGIC_HASH)) {
2385         if (*pdwDataLen>dwMax ||
2386             !RSAENH_CPHashData(hProv, hHash, pbData, *pdwDataLen, 0)) return FALSE;
2387     }
2388     
2389     return TRUE;
2390 }
2391
2392 static BOOL crypt_export_simple(CRYPTKEY *pCryptKey, CRYPTKEY *pPubKey,
2393     DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2394 {
2395     BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2396     ALG_ID *pAlgid = (ALG_ID*)(pBlobHeader+1);
2397     DWORD dwDataLen;
2398
2399     if (!(GET_ALG_CLASS(pCryptKey->aiAlgid)&(ALG_CLASS_DATA_ENCRYPT|ALG_CLASS_MSG_ENCRYPT))) {
2400         SetLastError(NTE_BAD_KEY); /* FIXME: error code? */
2401         return FALSE;
2402     }
2403
2404     dwDataLen = sizeof(BLOBHEADER) + sizeof(ALG_ID) + pPubKey->dwBlockLen;
2405     if (pbData) {
2406         if (*pdwDataLen < dwDataLen) {
2407             SetLastError(ERROR_MORE_DATA);
2408             *pdwDataLen = dwDataLen;
2409             return FALSE;
2410         }
2411
2412         pBlobHeader->bType = SIMPLEBLOB;
2413         pBlobHeader->bVersion = CUR_BLOB_VERSION;
2414         pBlobHeader->reserved = 0;
2415         pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2416
2417         *pAlgid = pPubKey->aiAlgid;
2418
2419         if (!pad_data(pCryptKey->abKeyValue, pCryptKey->dwKeyLen, (BYTE*)(pAlgid+1),
2420                       pPubKey->dwBlockLen, dwFlags))
2421         {
2422             return FALSE;
2423         }
2424
2425         encrypt_block_impl(pPubKey->aiAlgid, PK_PUBLIC, &pPubKey->context, (BYTE*)(pAlgid+1),
2426                            (BYTE*)(pAlgid+1), RSAENH_ENCRYPT);
2427     }
2428     *pdwDataLen = dwDataLen;
2429     return TRUE;
2430 }
2431
2432 static BOOL crypt_export_public_key(CRYPTKEY *pCryptKey, BYTE *pbData,
2433     DWORD *pdwDataLen)
2434 {
2435     BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2436     RSAPUBKEY *pRSAPubKey = (RSAPUBKEY*)(pBlobHeader+1);
2437     DWORD dwDataLen;
2438
2439     if ((pCryptKey->aiAlgid != CALG_RSA_KEYX) && (pCryptKey->aiAlgid != CALG_RSA_SIGN)) {
2440         SetLastError(NTE_BAD_KEY);
2441         return FALSE;
2442     }
2443
2444     dwDataLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) + pCryptKey->dwKeyLen;
2445     if (pbData) {
2446         if (*pdwDataLen < dwDataLen) {
2447             SetLastError(ERROR_MORE_DATA);
2448             *pdwDataLen = dwDataLen;
2449             return FALSE;
2450         }
2451
2452         pBlobHeader->bType = PUBLICKEYBLOB;
2453         pBlobHeader->bVersion = CUR_BLOB_VERSION;
2454         pBlobHeader->reserved = 0;
2455         pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2456
2457         pRSAPubKey->magic = RSAENH_MAGIC_RSA1;
2458         pRSAPubKey->bitlen = pCryptKey->dwKeyLen << 3;
2459
2460         export_public_key_impl((BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2461                                pCryptKey->dwKeyLen, &pRSAPubKey->pubexp);
2462     }
2463     *pdwDataLen = dwDataLen;
2464     return TRUE;
2465 }
2466
2467 static BOOL crypt_export_private_key(CRYPTKEY *pCryptKey, BOOL force,
2468     BYTE *pbData, DWORD *pdwDataLen)
2469 {
2470     BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2471     RSAPUBKEY *pRSAPubKey = (RSAPUBKEY*)(pBlobHeader+1);
2472     DWORD dwDataLen;
2473
2474     if ((pCryptKey->aiAlgid != CALG_RSA_KEYX) && (pCryptKey->aiAlgid != CALG_RSA_SIGN)) {
2475         SetLastError(NTE_BAD_KEY);
2476         return FALSE;
2477     }
2478     if (!force && !(pCryptKey->dwPermissions & CRYPT_EXPORT))
2479     {
2480         SetLastError(NTE_BAD_KEY_STATE);
2481         return FALSE;
2482     }
2483
2484     dwDataLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) +
2485                 2 * pCryptKey->dwKeyLen + 5 * ((pCryptKey->dwKeyLen + 1) >> 1);
2486     if (pbData) {
2487         if (*pdwDataLen < dwDataLen) {
2488             SetLastError(ERROR_MORE_DATA);
2489             *pdwDataLen = dwDataLen;
2490             return FALSE;
2491         }
2492
2493         pBlobHeader->bType = PRIVATEKEYBLOB;
2494         pBlobHeader->bVersion = CUR_BLOB_VERSION;
2495         pBlobHeader->reserved = 0;
2496         pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2497
2498         pRSAPubKey->magic = RSAENH_MAGIC_RSA2;
2499         pRSAPubKey->bitlen = pCryptKey->dwKeyLen << 3;
2500
2501         export_private_key_impl((BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2502                                 pCryptKey->dwKeyLen, &pRSAPubKey->pubexp);
2503     }
2504     *pdwDataLen = dwDataLen;
2505     return TRUE;
2506 }
2507
2508 static BOOL crypt_export_plaintext_key(CRYPTKEY *pCryptKey, BYTE *pbData,
2509     DWORD *pdwDataLen)
2510 {
2511     BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2512     DWORD *pKeyLen = (DWORD*)(pBlobHeader+1);
2513     BYTE *pbKey = (BYTE*)(pKeyLen+1);
2514     DWORD dwDataLen;
2515
2516     dwDataLen = sizeof(BLOBHEADER) + sizeof(DWORD) + pCryptKey->dwKeyLen;
2517     if (pbData) {
2518         if (*pdwDataLen < dwDataLen) {
2519             SetLastError(ERROR_MORE_DATA);
2520             *pdwDataLen = dwDataLen;
2521             return FALSE;
2522         }
2523
2524         pBlobHeader->bType = PLAINTEXTKEYBLOB;
2525         pBlobHeader->bVersion = CUR_BLOB_VERSION;
2526         pBlobHeader->reserved = 0;
2527         pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2528
2529         *pKeyLen = pCryptKey->dwKeyLen;
2530         memcpy(pbKey, &pCryptKey->abKeyValue, pCryptKey->dwKeyLen);
2531     }
2532     *pdwDataLen = dwDataLen;
2533     return TRUE;
2534 }
2535 /******************************************************************************
2536  * crypt_export_key [Internal]
2537  *
2538  * Export a key into a binary large object (BLOB).  Called by CPExportKey and
2539  * by store_key_pair.
2540  *
2541  * PARAMS
2542  *  pCryptKey  [I]   Key to be exported.
2543  *  hPubKey    [I]   Key used to encrypt sensitive BLOB data.
2544  *  dwBlobType [I]   SIMPLEBLOB, PUBLICKEYBLOB or PRIVATEKEYBLOB.
2545  *  dwFlags    [I]   Currently none defined.
2546  *  force      [I]   If TRUE, the key is written no matter what the key's
2547  *                   permissions are.  Otherwise the key's permissions are
2548  *                   checked before exporting.
2549  *  pbData     [O]   Pointer to a buffer where the BLOB will be written to.
2550  *  pdwDataLen [I/O] I: Size of buffer at pbData, O: Size of BLOB
2551  *
2552  * RETURNS
2553  *  Success: TRUE.
2554  *  Failure: FALSE.
2555  */
2556 static BOOL crypt_export_key(CRYPTKEY *pCryptKey, HCRYPTKEY hPubKey,
2557                              DWORD dwBlobType, DWORD dwFlags, BOOL force,
2558                              BYTE *pbData, DWORD *pdwDataLen)
2559 {
2560     CRYPTKEY *pPubKey;
2561     
2562     if (dwFlags & CRYPT_SSL2_FALLBACK) {
2563         if (pCryptKey->aiAlgid != CALG_SSL2_MASTER) {
2564             SetLastError(NTE_BAD_KEY);
2565             return FALSE;
2566         }
2567     }
2568     
2569     switch ((BYTE)dwBlobType)
2570     {
2571         case SIMPLEBLOB:
2572             if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pPubKey)){
2573                 SetLastError(NTE_BAD_PUBLIC_KEY); /* FIXME: error_code? */
2574                 return FALSE;
2575             }
2576             return crypt_export_simple(pCryptKey, pPubKey, dwFlags, pbData,
2577                                        pdwDataLen);
2578             
2579         case PUBLICKEYBLOB:
2580             if (is_valid_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY)) {
2581                 SetLastError(NTE_BAD_KEY); /* FIXME: error code? */
2582                 return FALSE;
2583             }
2584
2585             return crypt_export_public_key(pCryptKey, pbData, pdwDataLen);
2586
2587         case PRIVATEKEYBLOB:
2588             return crypt_export_private_key(pCryptKey, force, pbData, pdwDataLen);
2589
2590         case PLAINTEXTKEYBLOB:
2591             return crypt_export_plaintext_key(pCryptKey, pbData, pdwDataLen);
2592             
2593         default:
2594             SetLastError(NTE_BAD_TYPE); /* FIXME: error code? */
2595             return FALSE;
2596     }
2597 }
2598
2599 /******************************************************************************
2600  * CPExportKey (RSAENH.@)
2601  *
2602  * Export a key into a binary large object (BLOB).
2603  *
2604  * PARAMS
2605  *  hProv      [I]   Key container from which a key is to be exported.
2606  *  hKey       [I]   Key to be exported.
2607  *  hPubKey    [I]   Key used to encrypt sensitive BLOB data.
2608  *  dwBlobType [I]   SIMPLEBLOB, PUBLICKEYBLOB or PRIVATEKEYBLOB.
2609  *  dwFlags    [I]   Currently none defined.
2610  *  pbData     [O]   Pointer to a buffer where the BLOB will be written to.
2611  *  pdwDataLen [I/O] I: Size of buffer at pbData, O: Size of BLOB
2612  *
2613  * RETURNS
2614  *  Success: TRUE.
2615  *  Failure: FALSE.
2616  */
2617 BOOL WINAPI RSAENH_CPExportKey(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTKEY hPubKey,
2618                                DWORD dwBlobType, DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2619 {
2620     CRYPTKEY *pCryptKey;
2621
2622     TRACE("(hProv=%08lx, hKey=%08lx, hPubKey=%08lx, dwBlobType=%08x, dwFlags=%08x, pbData=%p,"
2623           "pdwDataLen=%p)\n", hProv, hKey, hPubKey, dwBlobType, dwFlags, pbData, pdwDataLen);
2624
2625     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2626     {
2627         SetLastError(NTE_BAD_UID);
2628         return FALSE;
2629     }
2630
2631     if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2632     {
2633         SetLastError(NTE_BAD_KEY);
2634         return FALSE;
2635     }
2636
2637     return crypt_export_key(pCryptKey, hPubKey, dwBlobType, dwFlags, FALSE,
2638         pbData, pdwDataLen);
2639 }
2640
2641 /******************************************************************************
2642  * release_and_install_key [Internal]
2643  *
2644  * Release an existing key, if present, and replaces it with a new one.
2645  *
2646  * PARAMS
2647  *  hProv     [I] Key container into which the key is to be imported.
2648  *  src       [I] Key which will replace *dest
2649  *  dest      [I] Points to key to be released and replaced with src
2650  *  fStoreKey [I] If TRUE, the newly installed key is stored to the registry.
2651  */
2652 static void release_and_install_key(HCRYPTPROV hProv, HCRYPTKEY src,
2653                                     HCRYPTKEY *dest, DWORD fStoreKey)
2654 {
2655     RSAENH_CPDestroyKey(hProv, *dest);
2656     copy_handle(&handle_table, src, RSAENH_MAGIC_KEY, dest);
2657     if (fStoreKey)
2658     {
2659         KEYCONTAINER *pKeyContainer;
2660
2661         if (lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER,
2662                           (OBJECTHDR**)&pKeyContainer))
2663         {
2664             store_key_container_keys(pKeyContainer);
2665             store_key_container_permissions(pKeyContainer);
2666         }
2667     }
2668 }
2669
2670 /******************************************************************************
2671  * import_private_key [Internal]
2672  *
2673  * Import a BLOB'ed private key into a key container.
2674  *
2675  * PARAMS
2676  *  hProv     [I] Key container into which the private key is to be imported.
2677  *  pbData    [I] Pointer to a buffer which holds the private key BLOB.
2678  *  dwDataLen [I] Length of data in buffer at pbData.
2679  *  dwFlags   [I] One of:
2680  *                CRYPT_EXPORTABLE: the imported key is marked exportable
2681  *  fStoreKey [I] If TRUE, the imported key is stored to the registry.
2682  *  phKey     [O] Handle to the imported key.
2683  *
2684  *
2685  * NOTES
2686  *  Assumes the caller has already checked the BLOBHEADER at pbData to ensure
2687  *  it's a PRIVATEKEYBLOB.
2688  *
2689  * RETURNS
2690  *  Success: TRUE.
2691  *  Failure: FALSE.
2692  */
2693 static BOOL import_private_key(HCRYPTPROV hProv, CONST BYTE *pbData, DWORD dwDataLen,
2694                                DWORD dwFlags, BOOL fStoreKey, HCRYPTKEY *phKey)
2695 {
2696     KEYCONTAINER *pKeyContainer;
2697     CRYPTKEY *pCryptKey;
2698     CONST BLOBHEADER *pBlobHeader = (CONST BLOBHEADER*)pbData;
2699     CONST RSAPUBKEY *pRSAPubKey = (CONST RSAPUBKEY*)(pBlobHeader+1);
2700     BOOL ret;
2701
2702     if (!lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER,
2703                        (OBJECTHDR**)&pKeyContainer))
2704     {
2705         SetLastError(NTE_BAD_UID);
2706         return FALSE;
2707     }
2708
2709     if ((dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY)) ||
2710         (pRSAPubKey->magic != RSAENH_MAGIC_RSA2) ||
2711         (dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) +
2712             (2 * pRSAPubKey->bitlen >> 3) + (5 * ((pRSAPubKey->bitlen+8)>>4))))
2713     {
2714         SetLastError(NTE_BAD_DATA);
2715         return FALSE;
2716     }
2717
2718     *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, MAKELONG(0,pRSAPubKey->bitlen), &pCryptKey);
2719     if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
2720     setup_key(pCryptKey);
2721     ret = import_private_key_impl((CONST BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2722                                    pRSAPubKey->bitlen/8, pRSAPubKey->pubexp);
2723     if (ret) {
2724         if (dwFlags & CRYPT_EXPORTABLE)
2725             pCryptKey->dwPermissions |= CRYPT_EXPORT;
2726         switch (pBlobHeader->aiKeyAlg)
2727         {
2728         case AT_SIGNATURE:
2729         case CALG_RSA_SIGN:
2730             TRACE("installing signing key\n");
2731             release_and_install_key(hProv, *phKey, &pKeyContainer->hSignatureKeyPair,
2732                                     fStoreKey);
2733             break;
2734         case AT_KEYEXCHANGE:
2735         case CALG_RSA_KEYX:
2736             TRACE("installing key exchange key\n");
2737             release_and_install_key(hProv, *phKey, &pKeyContainer->hKeyExchangeKeyPair,
2738                                     fStoreKey);
2739             break;
2740         }
2741     }
2742     return ret;
2743 }
2744
2745 /******************************************************************************
2746  * import_public_key [Internal]
2747  *
2748  * Import a BLOB'ed public key into a key container.
2749  *
2750  * PARAMS
2751  *  hProv     [I] Key container into which the public key is to be imported.
2752  *  pbData    [I] Pointer to a buffer which holds the public key BLOB.
2753  *  dwDataLen [I] Length of data in buffer at pbData.
2754  *  dwFlags   [I] One of:
2755  *                CRYPT_EXPORTABLE: the imported key is marked exportable
2756  *  fStoreKey [I] If TRUE, the imported key is stored to the registry.
2757  *  phKey     [O] Handle to the imported key.
2758  *
2759  *
2760  * NOTES
2761  *  Assumes the caller has already checked the BLOBHEADER at pbData to ensure
2762  *  it's a PUBLICKEYBLOB.
2763  *
2764  * RETURNS
2765  *  Success: TRUE.
2766  *  Failure: FALSE.
2767  */
2768 static BOOL import_public_key(HCRYPTPROV hProv, CONST BYTE *pbData, DWORD dwDataLen,
2769                               DWORD dwFlags, BOOL fStoreKey, HCRYPTKEY *phKey)
2770 {
2771     KEYCONTAINER *pKeyContainer;
2772     CRYPTKEY *pCryptKey;
2773     CONST BLOBHEADER *pBlobHeader = (CONST BLOBHEADER*)pbData;
2774     CONST RSAPUBKEY *pRSAPubKey = (CONST RSAPUBKEY*)(pBlobHeader+1);
2775     ALG_ID algID;
2776     BOOL ret;
2777
2778     if (!lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER,
2779                        (OBJECTHDR**)&pKeyContainer))
2780     {
2781         SetLastError(NTE_BAD_UID);
2782         return FALSE;
2783     }
2784
2785     if ((dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY)) ||
2786         (pRSAPubKey->magic != RSAENH_MAGIC_RSA1) ||
2787         (dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) + (pRSAPubKey->bitlen >> 3)))
2788     {
2789         SetLastError(NTE_BAD_DATA);
2790         return FALSE;
2791     }
2792
2793     /* Since this is a public key blob, only the public key is
2794      * available, so only signature verification is possible.
2795      */
2796     algID = pBlobHeader->aiKeyAlg;
2797     *phKey = new_key(hProv, algID, MAKELONG(0,pRSAPubKey->bitlen), &pCryptKey);
2798     if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
2799     setup_key(pCryptKey);
2800     ret = import_public_key_impl((CONST BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2801                                   pRSAPubKey->bitlen >> 3, pRSAPubKey->pubexp);
2802     if (ret) {
2803         if (dwFlags & CRYPT_EXPORTABLE)
2804             pCryptKey->dwPermissions |= CRYPT_EXPORT;
2805         switch (pBlobHeader->aiKeyAlg)
2806         {
2807         case AT_KEYEXCHANGE:
2808         case CALG_RSA_KEYX:
2809             TRACE("installing public key\n");
2810             release_and_install_key(hProv, *phKey, &pKeyContainer->hKeyExchangeKeyPair,
2811                                     fStoreKey);
2812             break;
2813         }
2814     }
2815     return ret;
2816 }
2817
2818 /******************************************************************************
2819  * import_symmetric_key [Internal]
2820  *
2821  * Import a BLOB'ed symmetric key into a key container.
2822  *
2823  * PARAMS
2824  *  hProv     [I] Key container into which the symmetric key is to be imported.
2825  *  pbData    [I] Pointer to a buffer which holds the symmetric key BLOB.
2826  *  dwDataLen [I] Length of data in buffer at pbData.
2827  *  hPubKey   [I] Key used to decrypt sensitive BLOB data.
2828  *  dwFlags   [I] One of:
2829  *                CRYPT_EXPORTABLE: the imported key is marked exportable
2830  *  phKey     [O] Handle to the imported key.
2831  *
2832  *
2833  * NOTES
2834  *  Assumes the caller has already checked the BLOBHEADER at pbData to ensure
2835  *  it's a SIMPLEBLOB.
2836  *
2837  * RETURNS
2838  *  Success: TRUE.
2839  *  Failure: FALSE.
2840  */
2841 static BOOL import_symmetric_key(HCRYPTPROV hProv, CONST BYTE *pbData,
2842                                  DWORD dwDataLen, HCRYPTKEY hPubKey,
2843                                  DWORD dwFlags, HCRYPTKEY *phKey)
2844 {
2845     CRYPTKEY *pCryptKey, *pPubKey;
2846     CONST BLOBHEADER *pBlobHeader = (CONST BLOBHEADER*)pbData;
2847     CONST ALG_ID *pAlgid = (CONST ALG_ID*)(pBlobHeader+1);
2848     CONST BYTE *pbKeyStream = (CONST BYTE*)(pAlgid + 1);
2849     BYTE *pbDecrypted;
2850     DWORD dwKeyLen;
2851
2852     if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pPubKey) ||
2853         pPubKey->aiAlgid != CALG_RSA_KEYX)
2854     {
2855         SetLastError(NTE_BAD_PUBLIC_KEY); /* FIXME: error code? */
2856         return FALSE;
2857     }
2858
2859     if (dwDataLen < sizeof(BLOBHEADER)+sizeof(ALG_ID)+pPubKey->dwBlockLen)
2860     {
2861         SetLastError(NTE_BAD_DATA); /* FIXME: error code */
2862         return FALSE;
2863     }
2864
2865     pbDecrypted = HeapAlloc(GetProcessHeap(), 0, pPubKey->dwBlockLen);
2866     if (!pbDecrypted) return FALSE;
2867     encrypt_block_impl(pPubKey->aiAlgid, PK_PRIVATE, &pPubKey->context, pbKeyStream, pbDecrypted,
2868                        RSAENH_DECRYPT);
2869
2870     dwKeyLen = RSAENH_MAX_KEY_SIZE;
2871     if (!unpad_data(pbDecrypted, pPubKey->dwBlockLen, pbDecrypted, &dwKeyLen, dwFlags)) {
2872         HeapFree(GetProcessHeap(), 0, pbDecrypted);
2873         return FALSE;
2874     }
2875
2876     *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, dwKeyLen<<19, &pCryptKey);
2877     if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
2878     {
2879         HeapFree(GetProcessHeap(), 0, pbDecrypted);
2880         return FALSE;
2881     }
2882     memcpy(pCryptKey->abKeyValue, pbDecrypted, dwKeyLen);
2883     HeapFree(GetProcessHeap(), 0, pbDecrypted);
2884     setup_key(pCryptKey);
2885     if (dwFlags & CRYPT_EXPORTABLE)
2886         pCryptKey->dwPermissions |= CRYPT_EXPORT;
2887     return TRUE;
2888 }
2889
2890 /******************************************************************************
2891  * import_plaintext_key [Internal]
2892  *
2893  * Import a plaintext key into a key container.
2894  *
2895  * PARAMS
2896  *  hProv     [I] Key container into which the symmetric key is to be imported.
2897  *  pbData    [I] Pointer to a buffer which holds the plaintext key BLOB.
2898  *  dwDataLen [I] Length of data in buffer at pbData.
2899  *  dwFlags   [I] One of:
2900  *                CRYPT_EXPORTABLE: the imported key is marked exportable
2901  *  phKey     [O] Handle to the imported key.
2902  *
2903  *
2904  * NOTES
2905  *  Assumes the caller has already checked the BLOBHEADER at pbData to ensure
2906  *  it's a PLAINTEXTKEYBLOB.
2907  *
2908  * RETURNS
2909  *  Success: TRUE.
2910  *  Failure: FALSE.
2911  */
2912 static BOOL import_plaintext_key(HCRYPTPROV hProv, CONST BYTE *pbData,
2913                                  DWORD dwDataLen, DWORD dwFlags,
2914                                  HCRYPTKEY *phKey)
2915 {
2916     CRYPTKEY *pCryptKey;
2917     CONST BLOBHEADER *pBlobHeader = (CONST BLOBHEADER*)pbData;
2918     CONST DWORD *pKeyLen = (CONST DWORD *)(pBlobHeader + 1);
2919     CONST BYTE *pbKeyStream = (CONST BYTE*)(pKeyLen + 1);
2920
2921     if (dwDataLen < sizeof(BLOBHEADER)+sizeof(DWORD)+*pKeyLen)
2922     {
2923         SetLastError(NTE_BAD_DATA); /* FIXME: error code */
2924         return FALSE;
2925     }
2926
2927     *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, *pKeyLen<<19, &pCryptKey);
2928     if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
2929         return FALSE;
2930     memcpy(pCryptKey->abKeyValue, pbKeyStream, *pKeyLen);
2931     setup_key(pCryptKey);
2932     if (dwFlags & CRYPT_EXPORTABLE)
2933         pCryptKey->dwPermissions |= CRYPT_EXPORT;
2934     return TRUE;
2935 }
2936
2937 /******************************************************************************
2938  * import_key [Internal]
2939  *
2940  * Import a BLOB'ed key into a key container, optionally storing the key's
2941  * value to the registry.
2942  *
2943  * PARAMS
2944  *  hProv     [I] Key container into which the key is to be imported.
2945  *  pbData    [I] Pointer to a buffer which holds the BLOB.
2946  *  dwDataLen [I] Length of data in buffer at pbData.
2947  *  hPubKey   [I] Key used to decrypt sensitive BLOB data.
2948  *  dwFlags   [I] One of:
2949  *                CRYPT_EXPORTABLE: the imported key is marked exportable
2950  *  fStoreKey [I] If TRUE, the imported key is stored to the registry.
2951  *  phKey     [O] Handle to the imported key.
2952  *
2953  * RETURNS
2954  *  Success: TRUE.
2955  *  Failure: FALSE.
2956  */
2957 static BOOL import_key(HCRYPTPROV hProv, CONST BYTE *pbData, DWORD dwDataLen,
2958                        HCRYPTKEY hPubKey, DWORD dwFlags, BOOL fStoreKey,
2959                        HCRYPTKEY *phKey)
2960 {
2961     KEYCONTAINER *pKeyContainer;
2962     CONST BLOBHEADER *pBlobHeader = (CONST BLOBHEADER*)pbData;
2963
2964     if (!lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER,
2965                        (OBJECTHDR**)&pKeyContainer)) 
2966     {
2967         SetLastError(NTE_BAD_UID);
2968         return FALSE;
2969     }
2970
2971     if (dwDataLen < sizeof(BLOBHEADER) || 
2972         pBlobHeader->bVersion != CUR_BLOB_VERSION ||
2973         pBlobHeader->reserved != 0) 
2974     {
2975         TRACE("bVersion = %d, reserved = %d\n", pBlobHeader->bVersion,
2976               pBlobHeader->reserved);
2977         SetLastError(NTE_BAD_DATA);
2978         return FALSE;
2979     }
2980
2981     /* If this is a verify-only context, the key is not persisted regardless of
2982      * fStoreKey's original value.
2983      */
2984     fStoreKey = fStoreKey && !(dwFlags & CRYPT_VERIFYCONTEXT);
2985     TRACE("blob type: %x\n", pBlobHeader->bType);
2986     switch (pBlobHeader->bType)
2987     {
2988         case PRIVATEKEYBLOB:    
2989             return import_private_key(hProv, pbData, dwDataLen, dwFlags,
2990                                       fStoreKey, phKey);
2991                 
2992         case PUBLICKEYBLOB:
2993             return import_public_key(hProv, pbData, dwDataLen, dwFlags,
2994                                      fStoreKey, phKey);
2995                 
2996         case SIMPLEBLOB:
2997             return import_symmetric_key(hProv, pbData, dwDataLen, hPubKey,
2998                                         dwFlags, phKey);
2999
3000         case PLAINTEXTKEYBLOB:
3001             return import_plaintext_key(hProv, pbData, dwDataLen, dwFlags,
3002                                         phKey);
3003
3004         default:
3005             SetLastError(NTE_BAD_TYPE); /* FIXME: error code? */
3006             return FALSE;
3007     }
3008 }
3009
3010 /******************************************************************************
3011  * CPImportKey (RSAENH.@)
3012  *
3013  * Import a BLOB'ed key into a key container.
3014  *
3015  * PARAMS
3016  *  hProv     [I] Key container into which the key is to be imported.
3017  *  pbData    [I] Pointer to a buffer which holds the BLOB.
3018  *  dwDataLen [I] Length of data in buffer at pbData.
3019  *  hPubKey   [I] Key used to decrypt sensitive BLOB data.
3020  *  dwFlags   [I] One of:
3021  *                CRYPT_EXPORTABLE: the imported key is marked exportable
3022  *  phKey     [O] Handle to the imported key.
3023  *
3024  * RETURNS
3025  *  Success: TRUE.
3026  *  Failure: FALSE.
3027  */
3028 BOOL WINAPI RSAENH_CPImportKey(HCRYPTPROV hProv, CONST BYTE *pbData, DWORD dwDataLen,
3029                                HCRYPTKEY hPubKey, DWORD dwFlags, HCRYPTKEY *phKey)
3030 {
3031     TRACE("(hProv=%08lx, pbData=%p, dwDataLen=%d, hPubKey=%08lx, dwFlags=%08x, phKey=%p)\n",
3032         hProv, pbData, dwDataLen, hPubKey, dwFlags, phKey);
3033
3034     if (dwFlags & CRYPT_IPSEC_HMAC_KEY)
3035     {
3036         FIXME("unimplemented for CRYPT_IPSEC_HMAC_KEY\n");
3037         SetLastError(NTE_BAD_FLAGS);
3038         return FALSE;
3039     }
3040     return import_key(hProv, pbData, dwDataLen, hPubKey, dwFlags, TRUE, phKey);
3041 }
3042
3043 /******************************************************************************
3044  * CPGenKey (RSAENH.@)
3045  *
3046  * Generate a key in the key container
3047  *
3048  * PARAMS
3049  *  hProv   [I] Key container for which a key is to be generated.
3050  *  Algid   [I] Crypto algorithm identifier for the key to be generated.
3051  *  dwFlags [I] Upper 16 bits: Binary length of key. Lower 16 bits: Flags. See Notes
3052  *  phKey   [O] Handle to the generated key.
3053  *
3054  * RETURNS
3055  *  Success: TRUE.
3056  *  Failure: FALSE.
3057  *
3058  * FIXME
3059  *  Flags currently not considered.
3060  *
3061  * NOTES
3062  *  Private key-exchange- and signature-keys can be generated with Algid AT_KEYEXCHANGE
3063  *  and AT_SIGNATURE values.
3064  */
3065 BOOL WINAPI RSAENH_CPGenKey(HCRYPTPROV hProv, ALG_ID Algid, DWORD dwFlags, HCRYPTKEY *phKey)
3066 {
3067     KEYCONTAINER *pKeyContainer;
3068     CRYPTKEY *pCryptKey;
3069
3070     TRACE("(hProv=%08lx, aiAlgid=%d, dwFlags=%08x, phKey=%p)\n", hProv, Algid, dwFlags, phKey);
3071
3072     if (!lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER,
3073                        (OBJECTHDR**)&pKeyContainer)) 
3074     {
3075         /* MSDN: hProv not containing valid context handle */
3076         SetLastError(NTE_BAD_UID);
3077         return FALSE;
3078     }
3079     
3080     switch (Algid)
3081     {
3082         case AT_SIGNATURE:
3083         case CALG_RSA_SIGN:
3084             *phKey = new_key(hProv, CALG_RSA_SIGN, dwFlags, &pCryptKey);
3085             if (pCryptKey) { 
3086                 new_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen);
3087                 setup_key(pCryptKey);
3088                 release_and_install_key(hProv, *phKey,
3089                                         &pKeyContainer->hSignatureKeyPair,
3090                                         FALSE);
3091             }
3092             break;
3093
3094         case AT_KEYEXCHANGE:
3095         case CALG_RSA_KEYX:
3096             *phKey = new_key(hProv, CALG_RSA_KEYX, dwFlags, &pCryptKey);
3097             if (pCryptKey) { 
3098                 new_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen);
3099                 setup_key(pCryptKey);
3100                 release_and_install_key(hProv, *phKey,
3101                                         &pKeyContainer->hKeyExchangeKeyPair,
3102                                         FALSE);
3103             }
3104             break;
3105             
3106         case CALG_RC2:
3107         case CALG_RC4:
3108         case CALG_DES:
3109         case CALG_3DES_112:
3110         case CALG_3DES:
3111         case CALG_AES:
3112         case CALG_AES_128:
3113         case CALG_AES_192:
3114         case CALG_AES_256:
3115         case CALG_PCT1_MASTER:
3116         case CALG_SSL2_MASTER:
3117         case CALG_SSL3_MASTER:
3118         case CALG_TLS1_MASTER:
3119             *phKey = new_key(hProv, Algid, dwFlags, &pCryptKey);
3120             if (pCryptKey) {
3121                 gen_rand_impl(pCryptKey->abKeyValue, RSAENH_MAX_KEY_SIZE);
3122                 switch (Algid) {
3123                     case CALG_SSL3_MASTER:
3124                         pCryptKey->abKeyValue[0] = RSAENH_SSL3_VERSION_MAJOR;
3125                         pCryptKey->abKeyValue[1] = RSAENH_SSL3_VERSION_MINOR;
3126                         break;
3127
3128                     case CALG_TLS1_MASTER:
3129                         pCryptKey->abKeyValue[0] = RSAENH_TLS1_VERSION_MAJOR;
3130                         pCryptKey->abKeyValue[1] = RSAENH_TLS1_VERSION_MINOR;
3131                         break;
3132                 }
3133                 setup_key(pCryptKey);
3134             }
3135             break;
3136             
3137         default:
3138             /* MSDN: Algorithm not supported specified by Algid */
3139             SetLastError(NTE_BAD_ALGID);
3140             return FALSE;
3141     }
3142             
3143     return *phKey != (HCRYPTKEY)INVALID_HANDLE_VALUE;
3144 }
3145
3146 /******************************************************************************
3147  * CPGenRandom (RSAENH.@)
3148  *
3149  * Generate a random byte stream.
3150  *
3151  * PARAMS
3152  *  hProv    [I] Key container that is used to generate random bytes.
3153  *  dwLen    [I] Specifies the number of requested random data bytes.
3154  *  pbBuffer [O] Random bytes will be stored here.
3155  *
3156  * RETURNS
3157  *  Success: TRUE
3158  *  Failure: FALSE
3159  */
3160 BOOL WINAPI RSAENH_CPGenRandom(HCRYPTPROV hProv, DWORD dwLen, BYTE *pbBuffer)
3161 {
3162     TRACE("(hProv=%08lx, dwLen=%d, pbBuffer=%p)\n", hProv, dwLen, pbBuffer);
3163     
3164     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3165     {
3166         /* MSDN: hProv not containing valid context handle */
3167         SetLastError(NTE_BAD_UID);
3168         return FALSE;
3169     }
3170
3171     return gen_rand_impl(pbBuffer, dwLen);
3172 }
3173
3174 /******************************************************************************
3175  * CPGetHashParam (RSAENH.@)
3176  *
3177  * Query parameters of an hash object.
3178  *
3179  * PARAMS
3180  *  hProv      [I]   The kea container, which the hash belongs to.
3181  *  hHash      [I]   The hash object that is to be queried.
3182  *  dwParam    [I]   Specifies the parameter that is to be queried.
3183  *  pbData     [I]   Pointer to the buffer where the parameter value will be stored.
3184  *  pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
3185  *  dwFlags    [I]   None currently defined.
3186  *
3187  * RETURNS
3188  *  Success: TRUE
3189  *  Failure: FALSE
3190  *
3191  * NOTES
3192  *  Valid dwParams are: HP_ALGID, HP_HASHSIZE, HP_HASHVALUE. The hash will be 
3193  *  finalized if HP_HASHVALUE is queried.
3194  */
3195 BOOL WINAPI RSAENH_CPGetHashParam(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwParam, BYTE *pbData, 
3196                                   DWORD *pdwDataLen, DWORD dwFlags) 
3197 {
3198     CRYPTHASH *pCryptHash;
3199         
3200     TRACE("(hProv=%08lx, hHash=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p, dwFlags=%08x)\n",
3201         hProv, hHash, dwParam, pbData, pdwDataLen, dwFlags);
3202     
3203     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3204     {
3205         SetLastError(NTE_BAD_UID);
3206         return FALSE;
3207     }
3208
3209     if (dwFlags)
3210     {
3211         SetLastError(NTE_BAD_FLAGS);
3212         return FALSE;
3213     }
3214     
3215     if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH,
3216                        (OBJECTHDR**)&pCryptHash))
3217     {
3218         SetLastError(NTE_BAD_HASH);
3219         return FALSE;
3220     }
3221
3222     if (!pdwDataLen)
3223     {
3224         SetLastError(ERROR_INVALID_PARAMETER);
3225         return FALSE;
3226     }
3227     
3228     switch (dwParam)
3229     {
3230         case HP_ALGID:
3231             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptHash->aiAlgid, 
3232                               sizeof(ALG_ID));
3233
3234         case HP_HASHSIZE:
3235             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptHash->dwHashSize, 
3236                               sizeof(DWORD));
3237
3238         case HP_HASHVAL:
3239             if (pCryptHash->aiAlgid == CALG_TLS1PRF) {
3240                 return tls1_prf(hProv, pCryptHash->hKey, &pCryptHash->tpPRFParams.blobLabel,
3241                                 &pCryptHash->tpPRFParams.blobSeed, pbData, *pdwDataLen);
3242             }
3243
3244             if ( pbData == NULL ) {
3245                 *pdwDataLen = pCryptHash->dwHashSize;
3246                 return TRUE;
3247             }
3248
3249             if (pbData && (pCryptHash->dwState != RSAENH_HASHSTATE_FINISHED))
3250             {
3251                 finalize_hash(pCryptHash);
3252                 pCryptHash->dwState = RSAENH_HASHSTATE_FINISHED;
3253             }
3254
3255             return copy_param(pbData, pdwDataLen, pCryptHash->abHashValue,
3256                               pCryptHash->dwHashSize);
3257
3258         default:
3259             SetLastError(NTE_BAD_TYPE);
3260             return FALSE;
3261     }
3262 }
3263
3264 /******************************************************************************
3265  * CPSetKeyParam (RSAENH.@)
3266  *
3267  * Set a parameter of a key object
3268  *
3269  * PARAMS
3270  *  hProv   [I] The key container to which the key belongs.
3271  *  hKey    [I] The key for which a parameter is to be set.
3272  *  dwParam [I] Parameter type. See Notes.
3273  *  pbData  [I] Pointer to the parameter value.
3274  *  dwFlags [I] Currently none defined.
3275  *
3276  * RETURNS
3277  *  Success: TRUE.
3278  *  Failure: FALSE.
3279  *
3280  * NOTES:
3281  *  Defined dwParam types are:
3282  *   - KP_MODE: Values MODE_CBC, MODE_ECB, MODE_CFB.
3283  *   - KP_MODE_BITS: Shift width for cipher feedback mode. (Currently ignored by MS CSP's)
3284  *   - KP_PERMISSIONS: Or'ed combination of CRYPT_ENCRYPT, CRYPT_DECRYPT, 
3285  *                     CRYPT_EXPORT, CRYPT_READ, CRYPT_WRITE, CRYPT_MAC
3286  *   - KP_IV: Initialization vector
3287  */
3288 BOOL WINAPI RSAENH_CPSetKeyParam(HCRYPTPROV hProv, HCRYPTKEY hKey, DWORD dwParam, BYTE *pbData, 
3289                                  DWORD dwFlags)
3290 {
3291     CRYPTKEY *pCryptKey;
3292
3293     TRACE("(hProv=%08lx, hKey=%08lx, dwParam=%08x, pbData=%p, dwFlags=%08x)\n", hProv, hKey,
3294           dwParam, pbData, dwFlags);
3295
3296     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3297     {
3298         SetLastError(NTE_BAD_UID);
3299         return FALSE;
3300     }
3301
3302     if (dwFlags) {
3303         SetLastError(NTE_BAD_FLAGS);
3304         return FALSE;
3305     }
3306     
3307     if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
3308     {
3309         SetLastError(NTE_BAD_KEY);
3310         return FALSE;
3311     }
3312     
3313     switch (dwParam) {
3314         case KP_PADDING:
3315             /* The MS providers only support PKCS5_PADDING */
3316             if (*(DWORD *)pbData != PKCS5_PADDING) {
3317                 SetLastError(NTE_BAD_DATA);
3318                 return FALSE;
3319             }
3320             return TRUE;
3321
3322         case KP_MODE:
3323             pCryptKey->dwMode = *(DWORD*)pbData;
3324             return TRUE;
3325
3326         case KP_MODE_BITS:
3327             pCryptKey->dwModeBits = *(DWORD*)pbData;
3328             return TRUE;
3329
3330         case KP_PERMISSIONS:
3331         {
3332             DWORD perms = *(DWORD *)pbData;
3333
3334             if ((perms & CRYPT_EXPORT) &&
3335                 !(pCryptKey->dwPermissions & CRYPT_EXPORT))
3336             {
3337                 SetLastError(NTE_BAD_DATA);
3338                 return FALSE;
3339             }
3340             else if (!(perms & CRYPT_EXPORT) &&
3341                 (pCryptKey->dwPermissions & CRYPT_EXPORT))
3342             {
3343                 /* Clearing the export permission appears to be ignored,
3344                  * see tests.
3345                  */
3346                 perms |= CRYPT_EXPORT;
3347             }
3348             pCryptKey->dwPermissions = perms;
3349             return TRUE;
3350         }
3351
3352         case KP_IV:
3353             memcpy(pCryptKey->abInitVector, pbData, pCryptKey->dwBlockLen);
3354             setup_key(pCryptKey);
3355             return TRUE;
3356
3357         case KP_SALT:
3358             switch (pCryptKey->aiAlgid) {
3359                 case CALG_RC2:
3360                 case CALG_RC4:
3361                     if (!pbData)
3362                     {
3363                         SetLastError(ERROR_INVALID_PARAMETER);
3364                         return FALSE;
3365                     }
3366                     /* MSDN: the base provider always sets eleven bytes of
3367                      * salt value.
3368                      */
3369                     memcpy(pCryptKey->abKeyValue + pCryptKey->dwKeyLen,
3370                            pbData, 11);
3371                     pCryptKey->dwSaltLen = 11;
3372                     setup_key(pCryptKey);
3373                     /* Strange but true: salt length reset to 0 after setting
3374                      * it via KP_SALT.
3375                      */
3376                     pCryptKey->dwSaltLen = 0;
3377                     break;
3378                 default:
3379                     SetLastError(NTE_BAD_KEY);
3380                     return FALSE;
3381             }
3382             return TRUE;
3383
3384         case KP_SALT_EX:
3385         {
3386             CRYPT_INTEGER_BLOB *blob = (CRYPT_INTEGER_BLOB *)pbData;
3387
3388             /* salt length can't be greater than 184 bits = 24 bytes */
3389             if (blob->cbData > 24)
3390             {
3391                 SetLastError(NTE_BAD_DATA);
3392                 return FALSE;
3393             }
3394             memcpy(pCryptKey->abKeyValue + pCryptKey->dwKeyLen, blob->pbData,
3395                    blob->cbData);
3396             pCryptKey->dwSaltLen = blob->cbData;
3397             setup_key(pCryptKey);
3398             return TRUE;
3399         }
3400
3401         case KP_EFFECTIVE_KEYLEN:
3402             switch (pCryptKey->aiAlgid) {
3403                 case CALG_RC2:
3404                     if (!pbData)
3405                     {
3406                         SetLastError(ERROR_INVALID_PARAMETER);
3407                         return FALSE;
3408                     }
3409                     else if (!*(DWORD *)pbData || *(DWORD *)pbData > 1024)
3410                     {
3411                         SetLastError(NTE_BAD_DATA);
3412                         return FALSE;
3413                     }
3414                     else
3415                     {
3416                         pCryptKey->dwEffectiveKeyLen = *(DWORD *)pbData;
3417                         setup_key(pCryptKey);
3418                     }
3419                     break;
3420                 default:
3421                     SetLastError(NTE_BAD_TYPE);
3422                     return FALSE;
3423             }
3424             return TRUE;
3425
3426         case KP_SCHANNEL_ALG:
3427             switch (((PSCHANNEL_ALG)pbData)->dwUse) {
3428                 case SCHANNEL_ENC_KEY:
3429                     memcpy(&pCryptKey->siSChannelInfo.saEncAlg, pbData, sizeof(SCHANNEL_ALG));
3430                     break;
3431
3432                 case SCHANNEL_MAC_KEY:
3433                     memcpy(&pCryptKey->siSChannelInfo.saMACAlg, pbData, sizeof(SCHANNEL_ALG));
3434                     break;
3435
3436                 default:
3437                     SetLastError(NTE_FAIL); /* FIXME: error code */
3438                     return FALSE;
3439             }
3440             return TRUE;
3441
3442         case KP_CLIENT_RANDOM:
3443             return copy_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom, (PCRYPT_DATA_BLOB)pbData);
3444             
3445         case KP_SERVER_RANDOM:
3446             return copy_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom, (PCRYPT_DATA_BLOB)pbData);
3447
3448         default:
3449             SetLastError(NTE_BAD_TYPE);
3450             return FALSE;
3451     }
3452 }
3453
3454 /******************************************************************************
3455  * CPGetKeyParam (RSAENH.@)
3456  *
3457  * Query a key parameter.
3458  *
3459  * PARAMS
3460  *  hProv      [I]   The key container, which the key belongs to.
3461  *  hHash      [I]   The key object that is to be queried.
3462  *  dwParam    [I]   Specifies the parameter that is to be queried.
3463  *  pbData     [I]   Pointer to the buffer where the parameter value will be stored.
3464  *  pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
3465  *  dwFlags    [I]   None currently defined.
3466  *
3467  * RETURNS
3468  *  Success: TRUE
3469  *  Failure: FALSE
3470  *
3471  * NOTES
3472  *  Defined dwParam types are:
3473  *   - KP_MODE: Values MODE_CBC, MODE_ECB, MODE_CFB.
3474  *   - KP_MODE_BITS: Shift width for cipher feedback mode. 
3475  *                   (Currently ignored by MS CSP's - always eight)
3476  *   - KP_PERMISSIONS: Or'ed combination of CRYPT_ENCRYPT, CRYPT_DECRYPT, 
3477  *                     CRYPT_EXPORT, CRYPT_READ, CRYPT_WRITE, CRYPT_MAC
3478  *   - KP_IV: Initialization vector.
3479  *   - KP_KEYLEN: Bitwidth of the key.
3480  *   - KP_BLOCKLEN: Size of a block cipher block.
3481  *   - KP_SALT: Salt value.
3482  */
3483 BOOL WINAPI RSAENH_CPGetKeyParam(HCRYPTPROV hProv, HCRYPTKEY hKey, DWORD dwParam, BYTE *pbData, 
3484                                  DWORD *pdwDataLen, DWORD dwFlags)
3485 {
3486     CRYPTKEY *pCryptKey;
3487     DWORD dwValue;
3488         
3489     TRACE("(hProv=%08lx, hKey=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p dwFlags=%08x)\n",
3490           hProv, hKey, dwParam, pbData, pdwDataLen, dwFlags);
3491
3492     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3493     {
3494         SetLastError(NTE_BAD_UID);
3495         return FALSE;
3496     }
3497
3498     if (dwFlags) {
3499         SetLastError(NTE_BAD_FLAGS);
3500         return FALSE;
3501     }
3502
3503     if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
3504     {
3505         SetLastError(NTE_BAD_KEY);
3506         return FALSE;
3507     }
3508
3509     switch (dwParam) 
3510     {
3511         case KP_IV:
3512             return copy_param(pbData, pdwDataLen, pCryptKey->abInitVector,
3513                               pCryptKey->dwBlockLen);
3514         
3515         case KP_SALT:
3516             switch (pCryptKey->aiAlgid) {
3517                 case CALG_RC2:
3518                 case CALG_RC4:
3519                     return copy_param(pbData, pdwDataLen,
3520                             &pCryptKey->abKeyValue[pCryptKey->dwKeyLen],
3521                             pCryptKey->dwSaltLen);
3522                 default:
3523                     SetLastError(NTE_BAD_KEY);
3524                     return FALSE;
3525             }
3526
3527         case KP_PADDING:
3528             dwValue = PKCS5_PADDING;
3529             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwValue, sizeof(DWORD));
3530
3531         case KP_KEYLEN:
3532             dwValue = pCryptKey->dwKeyLen << 3;
3533             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwValue, sizeof(DWORD));
3534         
3535         case KP_EFFECTIVE_KEYLEN:
3536             if (pCryptKey->dwEffectiveKeyLen)
3537                 dwValue = pCryptKey->dwEffectiveKeyLen;
3538             else
3539                 dwValue = pCryptKey->dwKeyLen << 3;
3540             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwValue, sizeof(DWORD));
3541
3542         case KP_BLOCKLEN:
3543             dwValue = pCryptKey->dwBlockLen << 3;
3544             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwValue, sizeof(DWORD));
3545     
3546         case KP_MODE:
3547             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptKey->dwMode, sizeof(DWORD));
3548
3549         case KP_MODE_BITS:
3550             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptKey->dwModeBits, 
3551                               sizeof(DWORD));
3552     
3553         case KP_PERMISSIONS:
3554             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptKey->dwPermissions, 
3555                               sizeof(DWORD));
3556
3557         case KP_ALGID:
3558             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptKey->aiAlgid, sizeof(DWORD));
3559             
3560         default:
3561             SetLastError(NTE_BAD_TYPE);
3562             return FALSE;
3563     }
3564 }
3565                         
3566 /******************************************************************************
3567  * CPGetProvParam (RSAENH.@)
3568  *
3569  * Query a CSP parameter.
3570  *
3571  * PARAMS
3572  *  hProv      [I]   The key container that is to be queried.
3573  *  dwParam    [I]   Specifies the parameter that is to be queried.
3574  *  pbData     [I]   Pointer to the buffer where the parameter value will be stored.
3575  *  pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
3576  *  dwFlags    [I]   CRYPT_FIRST: Start enumeration (for PP_ENUMALGS{_EX}).
3577  *
3578  * RETURNS
3579  *  Success: TRUE
3580  *  Failure: FALSE
3581  * NOTES:
3582  *  Defined dwParam types:
3583  *   - PP_CONTAINER: Name of the key container.
3584  *   - PP_NAME: Name of the cryptographic service provider.
3585  *   - PP_SIG_KEYSIZE_INC: RSA signature keywidth granularity in bits.
3586  *   - PP_KEYX_KEYSIZE_INC: RSA key-exchange keywidth granularity in bits.
3587  *   - PP_ENUMALGS{_EX}: Query provider capabilities.
3588  */
3589 BOOL WINAPI RSAENH_CPGetProvParam(HCRYPTPROV hProv, DWORD dwParam, BYTE *pbData, 
3590                                   DWORD *pdwDataLen, DWORD dwFlags)
3591 {
3592     KEYCONTAINER *pKeyContainer;
3593     PROV_ENUMALGS provEnumalgs;
3594     DWORD dwTemp;
3595     HKEY hKey;
3596    
3597     /* This is for dwParam PP_CRYPT_COUNT_KEY_USE.
3598      * IE6 SP1 asks for it in the 'About' dialog.
3599      * Returning this BLOB seems to satisfy IE. The marked 0x00 seem 
3600      * to be 'don't care's. If you know anything more specific about
3601      * this provider parameter, please report to wine-devel@winehq.org */
3602     static CONST BYTE abWTF[96] = { 
3603         0xb0, 0x25,     0x63,     0x86, 0x9c, 0xab,     0xb6,     0x37, 
3604         0xe8, 0x82, /**/0x00,/**/ 0x72, 0x06, 0xb2, /**/0x00,/**/ 0x3b, 
3605         0x60, 0x35, /**/0x00,/**/ 0x3b, 0x88, 0xce, /**/0x00,/**/ 0x82, 
3606         0xbc, 0x7a, /**/0x00,/**/ 0xb7, 0x4f, 0x7e, /**/0x00,/**/ 0xde, 
3607         0x92, 0xf1, /**/0x00,/**/ 0x83, 0xea, 0x5e, /**/0x00,/**/ 0xc8, 
3608         0x12, 0x1e,     0xd4,     0x06, 0xf7, 0x66, /**/0x00,/**/ 0x01, 
3609         0x29, 0xa4, /**/0x00,/**/ 0xf8, 0x24, 0x0c, /**/0x00,/**/ 0x33, 
3610         0x06, 0x80, /**/0x00,/**/ 0x02, 0x46, 0x0b, /**/0x00,/**/ 0x6d, 
3611         0x5b, 0xca, /**/0x00,/**/ 0x9a, 0x10, 0xf0, /**/0x00,/**/ 0x05, 
3612         0x19, 0xd0, /**/0x00,/**/ 0x2c, 0xf6, 0x27, /**/0x00,/**/ 0xaa, 
3613         0x7c, 0x6f, /**/0x00,/**/ 0xb9, 0xd8, 0x72, /**/0x00,/**/ 0x03, 
3614         0xf3, 0x81, /**/0x00,/**/ 0xfa, 0xe8, 0x26, /**/0x00,/**/ 0xca 
3615     };
3616
3617     TRACE("(hProv=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p, dwFlags=%08x)\n",
3618            hProv, dwParam, pbData, pdwDataLen, dwFlags);
3619
3620     if (!pdwDataLen) {
3621         SetLastError(ERROR_INVALID_PARAMETER);
3622         return FALSE;
3623     }
3624     
3625     if (!lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER,
3626                        (OBJECTHDR**)&pKeyContainer)) 
3627     {
3628         /* MSDN: hProv not containing valid context handle */
3629         SetLastError(NTE_BAD_UID);
3630         return FALSE;
3631     }
3632
3633     switch (dwParam) 
3634     {
3635         case PP_CONTAINER:
3636         case PP_UNIQUE_CONTAINER:/* MSDN says we can return the same value as PP_CONTAINER */
3637             return copy_param(pbData, pdwDataLen, (CONST BYTE*)pKeyContainer->szName, 
3638                               strlen(pKeyContainer->szName)+1);
3639
3640         case PP_NAME:
3641             return copy_param(pbData, pdwDataLen, (CONST BYTE*)pKeyContainer->szProvName, 
3642                               strlen(pKeyContainer->szProvName)+1);
3643
3644         case PP_PROVTYPE:
3645             dwTemp = PROV_RSA_FULL;
3646             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwTemp, sizeof(dwTemp));
3647
3648         case PP_KEYSPEC:
3649             dwTemp = AT_SIGNATURE | AT_KEYEXCHANGE;
3650             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwTemp, sizeof(dwTemp));
3651
3652         case PP_KEYSET_TYPE:
3653             dwTemp = pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET;
3654             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwTemp, sizeof(dwTemp));
3655
3656         case PP_KEYSTORAGE:
3657             dwTemp = CRYPT_SEC_DESCR;
3658             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwTemp, sizeof(dwTemp));
3659
3660         case PP_SIG_KEYSIZE_INC:
3661         case PP_KEYX_KEYSIZE_INC:
3662             dwTemp = 8;
3663             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwTemp, sizeof(dwTemp));
3664
3665         case PP_IMPTYPE:
3666             dwTemp = CRYPT_IMPL_SOFTWARE;
3667             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwTemp, sizeof(dwTemp));
3668
3669         case PP_VERSION:
3670             dwTemp = 0x00000200;
3671             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwTemp, sizeof(dwTemp));
3672             
3673         case PP_ENUMCONTAINERS:
3674             if ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) pKeyContainer->dwEnumContainersCtr = 0;
3675
3676             if (!pbData) {
3677                 *pdwDataLen = (DWORD)MAX_PATH + 1;
3678                 return TRUE;
3679             }
3680  
3681             if (!open_container_key("", dwFlags, &hKey))
3682             {
3683                 SetLastError(ERROR_NO_MORE_ITEMS);
3684                 return FALSE;
3685             }
3686
3687             dwTemp = *pdwDataLen;
3688             switch (RegEnumKeyExA(hKey, pKeyContainer->dwEnumContainersCtr, (LPSTR)pbData, &dwTemp,
3689                     NULL, NULL, NULL, NULL))
3690             {
3691                 case ERROR_MORE_DATA:
3692                     *pdwDataLen = (DWORD)MAX_PATH + 1;
3693  
3694                 case ERROR_SUCCESS:
3695                     pKeyContainer->dwEnumContainersCtr++;
3696                     RegCloseKey(hKey);
3697                     return TRUE;
3698
3699                 case ERROR_NO_MORE_ITEMS:
3700                 default:
3701                     SetLastError(ERROR_NO_MORE_ITEMS);
3702                     RegCloseKey(hKey);
3703                     return FALSE;
3704             }
3705  
3706         case PP_ENUMALGS:
3707         case PP_ENUMALGS_EX:
3708             if (((pKeyContainer->dwEnumAlgsCtr >= RSAENH_MAX_ENUMALGS-1) ||
3709                  (!aProvEnumAlgsEx[pKeyContainer->dwPersonality]
3710                    [pKeyContainer->dwEnumAlgsCtr+1].aiAlgid)) && 
3711                 ((dwFlags & CRYPT_FIRST) != CRYPT_FIRST))
3712             {
3713                 SetLastError(ERROR_NO_MORE_ITEMS);
3714                 return FALSE;
3715             }
3716
3717             if (dwParam == PP_ENUMALGS) {    
3718                 if (pbData && (*pdwDataLen >= sizeof(PROV_ENUMALGS))) 
3719                     pKeyContainer->dwEnumAlgsCtr = ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) ? 
3720                         0 : pKeyContainer->dwEnumAlgsCtr+1;
3721             
3722                 provEnumalgs.aiAlgid = aProvEnumAlgsEx
3723                     [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].aiAlgid;
3724                 provEnumalgs.dwBitLen = aProvEnumAlgsEx
3725                     [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].dwDefaultLen;
3726                 provEnumalgs.dwNameLen = aProvEnumAlgsEx
3727                     [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].dwNameLen;
3728                 memcpy(provEnumalgs.szName, aProvEnumAlgsEx
3729                        [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].szName, 
3730                        20*sizeof(CHAR));
3731             
3732                 return copy_param(pbData, pdwDataLen, (CONST BYTE*)&provEnumalgs, 
3733                                   sizeof(PROV_ENUMALGS));
3734             } else {
3735                 if (pbData && (*pdwDataLen >= sizeof(PROV_ENUMALGS_EX))) 
3736                     pKeyContainer->dwEnumAlgsCtr = ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) ? 
3737                         0 : pKeyContainer->dwEnumAlgsCtr+1;
3738             
3739                 return copy_param(pbData, pdwDataLen, 
3740                                   (CONST BYTE*)&aProvEnumAlgsEx
3741                                       [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr], 
3742                                   sizeof(PROV_ENUMALGS_EX));
3743             }
3744
3745         case PP_CRYPT_COUNT_KEY_USE: /* Asked for by IE About dialog */
3746             return copy_param(pbData, pdwDataLen, abWTF, sizeof(abWTF));
3747
3748         default:
3749             /* MSDN: Unknown parameter number in dwParam */
3750             SetLastError(NTE_BAD_TYPE);
3751             return FALSE;
3752     }
3753 }
3754
3755 /******************************************************************************
3756  * CPDeriveKey (RSAENH.@)
3757  *
3758  * Derives a key from a hash value.
3759  *
3760  * PARAMS
3761  *  hProv     [I] Key container for which a key is to be generated.
3762  *  Algid     [I] Crypto algorithm identifier for the key to be generated.
3763  *  hBaseData [I] Hash from whose value the key will be derived.
3764  *  dwFlags   [I] See Notes.
3765  *  phKey     [O] The generated key.
3766  *
3767  * RETURNS
3768  *  Success: TRUE
3769  *  Failure: FALSE
3770  *
3771  * NOTES
3772  *  Defined flags:
3773  *   - CRYPT_EXPORTABLE: Key can be exported.
3774  *   - CRYPT_NO_SALT: No salt is used for 40 bit keys.
3775  *   - CRYPT_CREATE_SALT: Use remaining bits as salt value.
3776  */
3777 BOOL WINAPI RSAENH_CPDeriveKey(HCRYPTPROV hProv, ALG_ID Algid, HCRYPTHASH hBaseData, 
3778                                DWORD dwFlags, HCRYPTKEY *phKey)
3779 {
3780     CRYPTKEY *pCryptKey, *pMasterKey;
3781     CRYPTHASH *pCryptHash;
3782     BYTE abHashValue[RSAENH_MAX_HASH_SIZE*2];
3783     DWORD dwLen;
3784     
3785     TRACE("(hProv=%08lx, Algid=%d, hBaseData=%08lx, dwFlags=%08x phKey=%p)\n", hProv, Algid,
3786            hBaseData, dwFlags, phKey);
3787     
3788     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3789     {
3790         SetLastError(NTE_BAD_UID);
3791         return FALSE;
3792     }
3793
3794     if (!lookup_handle(&handle_table, hBaseData, RSAENH_MAGIC_HASH,
3795                        (OBJECTHDR**)&pCryptHash))
3796     {
3797         SetLastError(NTE_BAD_HASH);
3798         return FALSE;
3799     }
3800
3801     if (!phKey)
3802     {
3803         SetLastError(ERROR_INVALID_PARAMETER);
3804         return FALSE;
3805     }
3806
3807     switch (GET_ALG_CLASS(Algid))
3808     {
3809         case ALG_CLASS_DATA_ENCRYPT:
3810             *phKey = new_key(hProv, Algid, dwFlags, &pCryptKey);
3811             if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
3812
3813             /* 
3814              * We derive the key material from the hash.
3815              * If the hash value is not large enough for the claimed key, we have to construct
3816              * a larger binary value based on the hash. This is documented in MSDN: CryptDeriveKey.
3817              */
3818             dwLen = RSAENH_MAX_HASH_SIZE;
3819             RSAENH_CPGetHashParam(pCryptHash->hProv, hBaseData, HP_HASHVAL, abHashValue, &dwLen, 0);
3820     
3821             if (dwLen < pCryptKey->dwKeyLen) {
3822                 BYTE pad1[RSAENH_HMAC_DEF_PAD_LEN], pad2[RSAENH_HMAC_DEF_PAD_LEN];
3823                 BYTE old_hashval[RSAENH_MAX_HASH_SIZE];
3824                 DWORD i;
3825
3826                 memcpy(old_hashval, pCryptHash->abHashValue, RSAENH_MAX_HASH_SIZE);
3827             
3828                 for (i=0; i<RSAENH_HMAC_DEF_PAD_LEN; i++) {
3829                     pad1[i] = RSAENH_HMAC_DEF_IPAD_CHAR ^ (i<dwLen ? abHashValue[i] : 0);
3830                     pad2[i] = RSAENH_HMAC_DEF_OPAD_CHAR ^ (i<dwLen ? abHashValue[i] : 0);
3831                 }
3832                 
3833                 init_hash(pCryptHash);
3834                 update_hash(pCryptHash, pad1, RSAENH_HMAC_DEF_PAD_LEN);
3835                 finalize_hash(pCryptHash);
3836                 memcpy(abHashValue, pCryptHash->abHashValue, pCryptHash->dwHashSize);
3837
3838                 init_hash(pCryptHash);
3839                 update_hash(pCryptHash, pad2, RSAENH_HMAC_DEF_PAD_LEN);
3840                 finalize_hash(pCryptHash);
3841                 memcpy(abHashValue+pCryptHash->dwHashSize, pCryptHash->abHashValue, 
3842                        pCryptHash->dwHashSize);
3843
3844                 memcpy(pCryptHash->abHashValue, old_hashval, RSAENH_MAX_HASH_SIZE);
3845             }
3846     
3847             memcpy(pCryptKey->abKeyValue, abHashValue, 
3848                    RSAENH_MIN(pCryptKey->dwKeyLen, sizeof(pCryptKey->abKeyValue)));
3849             break;
3850
3851         case ALG_CLASS_MSG_ENCRYPT:
3852             if (!lookup_handle(&handle_table, pCryptHash->hKey, RSAENH_MAGIC_KEY,
3853                                (OBJECTHDR**)&pMasterKey)) 
3854             {
3855                 SetLastError(NTE_FAIL); /* FIXME error code */
3856                 return FALSE;
3857             }
3858                 
3859             switch (Algid) 
3860             {
3861                 /* See RFC 2246, chapter 6.3 Key calculation */
3862                 case CALG_SCHANNEL_ENC_KEY:
3863                     *phKey = new_key(hProv, pMasterKey->siSChannelInfo.saEncAlg.Algid, 
3864                                      MAKELONG(LOWORD(dwFlags),pMasterKey->siSChannelInfo.saEncAlg.cBits),
3865                                      &pCryptKey);
3866                     if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
3867                     memcpy(pCryptKey->abKeyValue, 
3868                            pCryptHash->abHashValue + (
3869                                2 * (pMasterKey->siSChannelInfo.saMACAlg.cBits / 8) +
3870                                ((dwFlags & CRYPT_SERVER) ? 
3871                                    (pMasterKey->siSChannelInfo.saEncAlg.cBits / 8) : 0)),
3872                            pMasterKey->siSChannelInfo.saEncAlg.cBits / 8);
3873                     memcpy(pCryptKey->abInitVector,
3874                            pCryptHash->abHashValue + (
3875                                2 * (pMasterKey->siSChannelInfo.saMACAlg.cBits / 8) +
3876                                2 * (pMasterKey->siSChannelInfo.saEncAlg.cBits / 8) +
3877                                ((dwFlags & CRYPT_SERVER) ? pCryptKey->dwBlockLen : 0)),
3878                            pCryptKey->dwBlockLen);
3879                     break;
3880                     
3881                 case CALG_SCHANNEL_MAC_KEY:
3882                     *phKey = new_key(hProv, Algid, 
3883                                      MAKELONG(LOWORD(dwFlags),pMasterKey->siSChannelInfo.saMACAlg.cBits),
3884                                      &pCryptKey);
3885                     if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
3886                     memcpy(pCryptKey->abKeyValue,
3887                            pCryptHash->abHashValue + ((dwFlags & CRYPT_SERVER) ? 
3888                                pMasterKey->siSChannelInfo.saMACAlg.cBits / 8 : 0),
3889                            pMasterKey->siSChannelInfo.saMACAlg.cBits / 8);
3890                     break;
3891                     
3892                 default:
3893                     SetLastError(NTE_BAD_ALGID);
3894                     return FALSE;
3895             }
3896             break;
3897
3898         default:
3899             SetLastError(NTE_BAD_ALGID);
3900             return FALSE;
3901     }
3902
3903     setup_key(pCryptKey);
3904     return TRUE;    
3905 }
3906
3907 /******************************************************************************
3908  * CPGetUserKey (RSAENH.@)
3909  *
3910  * Returns a handle to the user's private key-exchange- or signature-key.
3911  *
3912  * PARAMS
3913  *  hProv     [I] The key container from which a user key is requested.
3914  *  dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
3915  *  phUserKey [O] Handle to the requested key or INVALID_HANDLE_VALUE in case of failure.
3916  *
3917  * RETURNS
3918  *  Success: TRUE.
3919  *  Failure: FALSE.
3920  *
3921  * NOTE
3922  *  A newly created key container does not contain private user key. Create them with CPGenKey.
3923  */
3924 BOOL WINAPI RSAENH_CPGetUserKey(HCRYPTPROV hProv, DWORD dwKeySpec, HCRYPTKEY *phUserKey)
3925 {
3926     KEYCONTAINER *pKeyContainer;
3927
3928     TRACE("(hProv=%08lx, dwKeySpec=%08x, phUserKey=%p)\n", hProv, dwKeySpec, phUserKey);
3929     
3930     if (!lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER,
3931                        (OBJECTHDR**)&pKeyContainer)) 
3932     {
3933         /* MSDN: hProv not containing valid context handle */
3934         SetLastError(NTE_BAD_UID);
3935         return FALSE;
3936     }
3937
3938     switch (dwKeySpec)
3939     {
3940         case AT_KEYEXCHANGE:
3941             copy_handle(&handle_table, pKeyContainer->hKeyExchangeKeyPair, RSAENH_MAGIC_KEY, 
3942                         phUserKey);
3943             break;
3944
3945         case AT_SIGNATURE:
3946             copy_handle(&handle_table, pKeyContainer->hSignatureKeyPair, RSAENH_MAGIC_KEY, 
3947                         phUserKey);
3948             break;
3949
3950         default:
3951             *phUserKey = (HCRYPTKEY)INVALID_HANDLE_VALUE;
3952     }
3953
3954     if (*phUserKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
3955     {
3956         /* MSDN: dwKeySpec parameter specifies nonexistent key */
3957         SetLastError(NTE_NO_KEY);
3958         return FALSE;
3959     }
3960
3961     return TRUE;
3962 }
3963
3964 /******************************************************************************
3965  * CPHashData (RSAENH.@)
3966  *
3967  * Updates a hash object with the given data.
3968  *
3969  * PARAMS
3970  *  hProv     [I] Key container to which the hash object belongs.
3971  *  hHash     [I] Hash object which is to be updated.
3972  *  pbData    [I] Pointer to data with which the hash object is to be updated.
3973  *  dwDataLen [I] Length of the data.
3974  *  dwFlags   [I] Currently none defined.
3975  *
3976  * RETURNS
3977  *  Success: TRUE.
3978  *  Failure: FALSE.
3979  *
3980  * NOTES
3981  *  The actual hash value is queried with CPGetHashParam, which will finalize 
3982  *  the hash. Updating a finalized hash will fail with a last error NTE_BAD_HASH_STATE.
3983  */
3984 BOOL WINAPI RSAENH_CPHashData(HCRYPTPROV hProv, HCRYPTHASH hHash, CONST BYTE *pbData, 
3985                               DWORD dwDataLen, DWORD dwFlags)
3986 {
3987     CRYPTHASH *pCryptHash;
3988         
3989     TRACE("(hProv=%08lx, hHash=%08lx, pbData=%p, dwDataLen=%d, dwFlags=%08x)\n",
3990           hProv, hHash, pbData, dwDataLen, dwFlags);
3991
3992     if (dwFlags)
3993     {
3994         SetLastError(NTE_BAD_FLAGS);
3995         return FALSE;
3996     }
3997
3998     if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH,
3999                        (OBJECTHDR**)&pCryptHash))
4000     {
4001         SetLastError(NTE_BAD_HASH);
4002         return FALSE;
4003     }
4004
4005     if (!get_algid_info(hProv, pCryptHash->aiAlgid) || pCryptHash->aiAlgid == CALG_SSL3_SHAMD5)
4006     {
4007         SetLastError(NTE_BAD_ALGID);
4008         return FALSE;
4009     }
4010     
4011     if (pCryptHash->dwState != RSAENH_HASHSTATE_HASHING)
4012     {
4013         SetLastError(NTE_BAD_HASH_STATE);
4014         return FALSE;
4015     }
4016
4017     update_hash(pCryptHash, pbData, dwDataLen);
4018     return TRUE;
4019 }
4020
4021 /******************************************************************************
4022  * CPHashSessionKey (RSAENH.@)
4023  *
4024  * Updates a hash object with the binary representation of a symmetric key.
4025  *
4026  * PARAMS
4027  *  hProv     [I] Key container to which the hash object belongs.
4028  *  hHash     [I] Hash object which is to be updated.
4029  *  hKey      [I] The symmetric key, whose binary value will be added to the hash.
4030  *  dwFlags   [I] CRYPT_LITTLE_ENDIAN, if the binary key value shall be interpreted as little endian.
4031  *
4032  * RETURNS
4033  *  Success: TRUE.
4034  *  Failure: FALSE.
4035  */
4036 BOOL WINAPI RSAENH_CPHashSessionKey(HCRYPTPROV hProv, HCRYPTHASH hHash, HCRYPTKEY hKey, 
4037                                     DWORD dwFlags)
4038 {
4039     BYTE abKeyValue[RSAENH_MAX_KEY_SIZE], bTemp;
4040     CRYPTKEY *pKey;
4041     DWORD i;
4042
4043     TRACE("(hProv=%08lx, hHash=%08lx, hKey=%08lx, dwFlags=%08x)\n", hProv, hHash, hKey, dwFlags);
4044
4045     if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pKey) ||
4046         (GET_ALG_CLASS(pKey->aiAlgid) != ALG_CLASS_DATA_ENCRYPT)) 
4047     {
4048         SetLastError(NTE_BAD_KEY);
4049         return FALSE;
4050     }
4051
4052     if (dwFlags & ~CRYPT_LITTLE_ENDIAN) {
4053         SetLastError(NTE_BAD_FLAGS);
4054         return FALSE;
4055     }
4056
4057     memcpy(abKeyValue, pKey->abKeyValue, pKey->dwKeyLen);
4058     if (!(dwFlags & CRYPT_LITTLE_ENDIAN)) {
4059         for (i=0; i<pKey->dwKeyLen/2; i++) {
4060             bTemp = abKeyValue[i];
4061             abKeyValue[i] = abKeyValue[pKey->dwKeyLen-i-1];
4062             abKeyValue[pKey->dwKeyLen-i-1] = bTemp;
4063         }
4064     }
4065
4066     return RSAENH_CPHashData(hProv, hHash, abKeyValue, pKey->dwKeyLen, 0);
4067 }
4068
4069 /******************************************************************************
4070  * CPReleaseContext (RSAENH.@)
4071  *
4072  * Release a key container.
4073  *
4074  * PARAMS
4075  *  hProv   [I] Key container to be released.
4076  *  dwFlags [I] Currently none defined.
4077  *
4078  * RETURNS
4079  *  Success: TRUE
4080  *  Failure: FALSE
4081  */
4082 BOOL WINAPI RSAENH_CPReleaseContext(HCRYPTPROV hProv, DWORD dwFlags)
4083 {
4084     TRACE("(hProv=%08lx, dwFlags=%08x)\n", hProv, dwFlags);
4085
4086     if (!release_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
4087     {
4088         /* MSDN: hProv not containing valid context handle */
4089         SetLastError(NTE_BAD_UID);
4090         return FALSE;
4091     }
4092
4093     if (dwFlags) {
4094         SetLastError(NTE_BAD_FLAGS);
4095         return FALSE;
4096     }
4097     
4098     return TRUE;
4099 }
4100
4101 /******************************************************************************
4102  * CPSetHashParam (RSAENH.@)
4103  * 
4104  * Set a parameter of a hash object
4105  *
4106  * PARAMS
4107  *  hProv   [I] The key container to which the key belongs.
4108  *  hHash   [I] The hash object for which a parameter is to be set.
4109  *  dwParam [I] Parameter type. See Notes.
4110  *  pbData  [I] Pointer to the parameter value.
4111  *  dwFlags [I] Currently none defined.
4112  *
4113  * RETURNS
4114  *  Success: TRUE.
4115  *  Failure: FALSE.
4116  *
4117  * NOTES
4118  *  Currently only the HP_HMAC_INFO dwParam type is defined. 
4119  *  The HMAC_INFO struct will be deep copied into the hash object.
4120  *  See Internet RFC 2104 for details on the HMAC algorithm.
4121  */
4122 BOOL WINAPI RSAENH_CPSetHashParam(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwParam, 
4123                                   BYTE *pbData, DWORD dwFlags)
4124 {
4125     CRYPTHASH *pCryptHash;
4126     CRYPTKEY *pCryptKey;
4127     DWORD i;
4128
4129     TRACE("(hProv=%08lx, hHash=%08lx, dwParam=%08x, pbData=%p, dwFlags=%08x)\n",
4130            hProv, hHash, dwParam, pbData, dwFlags);
4131
4132     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
4133     {
4134         SetLastError(NTE_BAD_UID);
4135         return FALSE;
4136     }
4137
4138     if (dwFlags) {
4139         SetLastError(NTE_BAD_FLAGS);
4140         return FALSE;
4141     }
4142     
4143     if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH,
4144                        (OBJECTHDR**)&pCryptHash))
4145     {
4146         SetLastError(NTE_BAD_HASH);
4147         return FALSE;
4148     }
4149     
4150     switch (dwParam) {
4151         case HP_HMAC_INFO:
4152             free_hmac_info(pCryptHash->pHMACInfo);
4153             if (!copy_hmac_info(&pCryptHash->pHMACInfo, (PHMAC_INFO)pbData)) return FALSE;
4154
4155             if (!lookup_handle(&handle_table, pCryptHash->hKey, RSAENH_MAGIC_KEY, 
4156                                (OBJECTHDR**)&pCryptKey)) 
4157             {
4158                 SetLastError(NTE_FAIL); /* FIXME: correct error code? */
4159                 return FALSE;
4160             }
4161
4162             for (i=0; i<RSAENH_MIN(pCryptKey->dwKeyLen,pCryptHash->pHMACInfo->cbInnerString); i++) {
4163                 pCryptHash->pHMACInfo->pbInnerString[i] ^= pCryptKey->abKeyValue[i];
4164             }
4165             for (i=0; i<RSAENH_MIN(pCryptKey->dwKeyLen,pCryptHash->pHMACInfo->cbOuterString); i++) {
4166                 pCryptHash->pHMACInfo->pbOuterString[i] ^= pCryptKey->abKeyValue[i];
4167             }
4168             
4169             init_hash(pCryptHash);
4170             return TRUE;
4171
4172         case HP_HASHVAL:
4173             memcpy(pCryptHash->abHashValue, pbData, pCryptHash->dwHashSize);
4174             pCryptHash->dwState = RSAENH_HASHSTATE_FINISHED;
4175             return TRUE;
4176            
4177         case HP_TLS1PRF_SEED:
4178             return copy_data_blob(&pCryptHash->tpPRFParams.blobSeed, (PCRYPT_DATA_BLOB)pbData);
4179
4180         case HP_TLS1PRF_LABEL:
4181             return copy_data_blob(&pCryptHash->tpPRFParams.blobLabel, (PCRYPT_DATA_BLOB)pbData);
4182             
4183         default:
4184             SetLastError(NTE_BAD_TYPE);
4185             return FALSE;
4186     }
4187 }
4188
4189 /******************************************************************************
4190  * CPSetProvParam (RSAENH.@)
4191  */
4192 BOOL WINAPI RSAENH_CPSetProvParam(HCRYPTPROV hProv, DWORD dwParam, BYTE *pbData, DWORD dwFlags)
4193 {
4194     FIXME("(stub)\n");
4195     return FALSE;
4196 }
4197
4198 /******************************************************************************
4199  * CPSignHash (RSAENH.@)
4200  *
4201  * Sign a hash object
4202  *
4203  * PARAMS
4204  *  hProv        [I]   The key container, to which the hash object belongs.
4205  *  hHash        [I]   The hash object to be signed.
4206  *  dwKeySpec    [I]   AT_SIGNATURE or AT_KEYEXCHANGE: Key used to generate the signature.
4207  *  sDescription [I]   Should be NULL for security reasons. 
4208  *  dwFlags      [I]   0, CRYPT_NOHASHOID or CRYPT_X931_FORMAT: Format of the signature.
4209  *  pbSignature  [O]   Buffer, to which the signature will be stored. May be NULL to query SigLen.
4210  *  pdwSigLen    [I/O] Size of the buffer (in), Length of the signature (out)
4211  *
4212  * RETURNS
4213  *  Success: TRUE
4214  *  Failure: FALSE
4215  */
4216 BOOL WINAPI RSAENH_CPSignHash(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwKeySpec, 
4217                               LPCWSTR sDescription, DWORD dwFlags, BYTE *pbSignature, 
4218                               DWORD *pdwSigLen)
4219 {
4220     HCRYPTKEY hCryptKey = (HCRYPTKEY)INVALID_HANDLE_VALUE;
4221     CRYPTKEY *pCryptKey;
4222     DWORD dwHashLen;
4223     BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
4224     ALG_ID aiAlgid;
4225     BOOL ret = FALSE;
4226
4227     TRACE("(hProv=%08lx, hHash=%08lx, dwKeySpec=%08x, sDescription=%s, dwFlags=%08x, "
4228         "pbSignature=%p, pdwSigLen=%p)\n", hProv, hHash, dwKeySpec, debugstr_w(sDescription),
4229         dwFlags, pbSignature, pdwSigLen);
4230
4231     if (dwFlags & ~(CRYPT_NOHASHOID|CRYPT_X931_FORMAT)) {
4232         SetLastError(NTE_BAD_FLAGS);
4233         return FALSE;
4234     }
4235     
4236     if (!RSAENH_CPGetUserKey(hProv, dwKeySpec, &hCryptKey)) return FALSE;
4237             
4238     if (!lookup_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY,
4239                        (OBJECTHDR**)&pCryptKey))
4240     {
4241         SetLastError(NTE_NO_KEY);
4242         goto out;
4243     }
4244
4245     if (!pbSignature) {
4246         *pdwSigLen = pCryptKey->dwKeyLen;
4247         ret = TRUE;
4248         goto out;
4249     }
4250     if (pCryptKey->dwKeyLen > *pdwSigLen)
4251     {
4252         SetLastError(ERROR_MORE_DATA);
4253         *pdwSigLen = pCryptKey->dwKeyLen;
4254         goto out;
4255     }
4256     *pdwSigLen = pCryptKey->dwKeyLen;
4257
4258     if (sDescription) {
4259         if (!RSAENH_CPHashData(hProv, hHash, (CONST BYTE*)sDescription, 
4260                                 (DWORD)lstrlenW(sDescription)*sizeof(WCHAR), 0))
4261         {
4262             goto out;
4263         }
4264     }
4265     
4266     dwHashLen = sizeof(DWORD);
4267     if (!RSAENH_CPGetHashParam(hProv, hHash, HP_ALGID, (BYTE*)&aiAlgid, &dwHashLen, 0)) goto out;
4268     
4269     dwHashLen = RSAENH_MAX_HASH_SIZE;
4270     if (!RSAENH_CPGetHashParam(hProv, hHash, HP_HASHVAL, abHashValue, &dwHashLen, 0)) goto out;
4271  
4272
4273     if (!build_hash_signature(pbSignature, *pdwSigLen, aiAlgid, abHashValue, dwHashLen, dwFlags)) {
4274         goto out;
4275     }
4276
4277     ret = encrypt_block_impl(pCryptKey->aiAlgid, PK_PRIVATE, &pCryptKey->context, pbSignature, pbSignature, RSAENH_ENCRYPT);
4278 out:
4279     RSAENH_CPDestroyKey(hProv, hCryptKey);
4280     return ret;
4281 }
4282
4283 /******************************************************************************
4284  * CPVerifySignature (RSAENH.@)
4285  *
4286  * Verify the signature of a hash object.
4287  * 
4288  * PARAMS
4289  *  hProv        [I] The key container, to which the hash belongs.
4290  *  hHash        [I] The hash for which the signature is verified.
4291  *  pbSignature  [I] The binary signature.
4292  *  dwSigLen     [I] Length of the signature BLOB.
4293  *  hPubKey      [I] Public key used to verify the signature.
4294  *  sDescription [I] Should be NULL for security reasons.
4295  *  dwFlags      [I] 0, CRYPT_NOHASHOID or CRYPT_X931_FORMAT: Format of the signature.
4296  *
4297  * RETURNS
4298  *  Success: TRUE  (Signature is valid)
4299  *  Failure: FALSE (GetLastError() == NTE_BAD_SIGNATURE, if signature is invalid)
4300  */
4301 BOOL WINAPI RSAENH_CPVerifySignature(HCRYPTPROV hProv, HCRYPTHASH hHash, CONST BYTE *pbSignature, 
4302                                      DWORD dwSigLen, HCRYPTKEY hPubKey, LPCWSTR sDescription, 
4303                                      DWORD dwFlags)
4304 {
4305     BYTE *pbConstructed = NULL, *pbDecrypted = NULL;
4306     CRYPTKEY *pCryptKey;
4307     DWORD dwHashLen;
4308     ALG_ID aiAlgid;
4309     BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
4310     BOOL res = FALSE;
4311
4312     TRACE("(hProv=%08lx, hHash=%08lx, pbSignature=%p, dwSigLen=%d, hPubKey=%08lx, sDescription=%s, "
4313           "dwFlags=%08x)\n", hProv, hHash, pbSignature, dwSigLen, hPubKey, debugstr_w(sDescription),
4314           dwFlags);
4315         
4316     if (dwFlags & ~(CRYPT_NOHASHOID|CRYPT_X931_FORMAT)) {
4317         SetLastError(NTE_BAD_FLAGS);
4318         return FALSE;
4319     }
4320     
4321     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
4322     {
4323         SetLastError(NTE_BAD_UID);
4324         return FALSE;
4325     }
4326  
4327     if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY,
4328                        (OBJECTHDR**)&pCryptKey))
4329     {
4330         SetLastError(NTE_BAD_KEY);
4331         return FALSE;
4332     }
4333
4334     /* in Microsoft implementation, the signature length is checked before
4335      * the signature pointer.
4336      */
4337     if (dwSigLen != pCryptKey->dwKeyLen)
4338     {
4339         SetLastError(NTE_BAD_SIGNATURE);
4340         return FALSE;
4341     }
4342
4343     if (!hHash || !pbSignature)
4344     {
4345         SetLastError(ERROR_INVALID_PARAMETER);
4346         return FALSE;
4347     }
4348
4349     if (sDescription) {
4350         if (!RSAENH_CPHashData(hProv, hHash, (CONST BYTE*)sDescription, 
4351                                 (DWORD)lstrlenW(sDescription)*sizeof(WCHAR), 0))
4352         {
4353             return FALSE;
4354         }
4355     }
4356     
4357     dwHashLen = sizeof(DWORD);
4358     if (!RSAENH_CPGetHashParam(hProv, hHash, HP_ALGID, (BYTE*)&aiAlgid, &dwHashLen, 0)) return FALSE;
4359     
4360     dwHashLen = RSAENH_MAX_HASH_SIZE;
4361     if (!RSAENH_CPGetHashParam(hProv, hHash, HP_HASHVAL, abHashValue, &dwHashLen, 0)) return FALSE;
4362
4363     pbConstructed = HeapAlloc(GetProcessHeap(), 0, dwSigLen);
4364     if (!pbConstructed) {
4365         SetLastError(NTE_NO_MEMORY);
4366         goto cleanup;
4367     }
4368
4369     pbDecrypted = HeapAlloc(GetProcessHeap(), 0, dwSigLen);
4370     if (!pbDecrypted) {
4371         SetLastError(NTE_NO_MEMORY);
4372         goto cleanup;
4373     }
4374
4375     if (!encrypt_block_impl(pCryptKey->aiAlgid, PK_PUBLIC, &pCryptKey->context, pbSignature, pbDecrypted, 
4376                             RSAENH_DECRYPT)) 
4377     {
4378         goto cleanup;
4379     }
4380
4381     if (!build_hash_signature(pbConstructed, dwSigLen, aiAlgid, abHashValue, dwHashLen, dwFlags)) {
4382         goto cleanup;
4383     }
4384
4385     if (memcmp(pbDecrypted, pbConstructed, dwSigLen)) {
4386         SetLastError(NTE_BAD_SIGNATURE);
4387         goto cleanup;
4388     }
4389     
4390     res = TRUE;
4391 cleanup:
4392     HeapFree(GetProcessHeap(), 0, pbConstructed);
4393     HeapFree(GetProcessHeap(), 0, pbDecrypted);
4394     return res;
4395 }
4396
4397 static const WCHAR szProviderKeys[6][116] = {
4398     {   'S','o','f','t','w','a','r','e','\\',
4399         'M','i','c','r','o','s','o','f','t','\\','C','r','y','p','t','o','g','r',
4400         'a','p','h','y','\\','D','e','f','a','u','l','t','s','\\','P','r','o','v',
4401         'i','d','e','r','\\','M','i','c','r','o','s','o','f','t',' ','B','a','s',
4402         'e',' ','C','r','y','p','t','o','g','r','a','p','h','i','c',' ','P','r',
4403         'o','v','i','d','e','r',' ','v','1','.','0',0 },
4404     {   'S','o','f','t','w','a','r','e','\\',
4405         'M','i','c','r','o','s','o','f','t','\\','C','r','y','p','t','o','g','r',
4406         'a','p','h','y','\\','D','e','f','a','u','l','t','s','\\','P','r','o','v',
4407         'i','d','e','r','\\','M','i','c','r','o','s','o','f','t',' ',
4408         'E','n','h','a','n','c','e','d',
4409         ' ','C','r','y','p','t','o','g','r','a','p','h','i','c',' ','P','r',
4410         'o','v','i','d','e','r',' ','v','1','.','0',0 },
4411     {   'S','o','f','t','w','a','r','e','\\',
4412         'M','i','c','r','o','s','o','f','t','\\','C','r','y','p','t','o','g','r',
4413         'a','p','h','y','\\','D','e','f','a','u','l','t','s','\\','P','r','o','v',
4414         'i','d','e','r','\\','M','i','c','r','o','s','o','f','t',' ','S','t','r','o','n','g',
4415         ' ','C','r','y','p','t','o','g','r','a','p','h','i','c',' ','P','r',
4416         'o','v','i','d','e','r',0 },
4417     {   'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\',
4418         'C','r','y','p','t','o','g','r','a','p','h','y','\\','D','e','f','a','u','l','t','s','\\',
4419         'P','r','o','v','i','d','e','r','\\','M','i','c','r','o','s','o','f','t',' ',
4420         'R','S','A',' ','S','C','h','a','n','n','e','l',' ',
4421         'C','r','y','p','t','o','g','r','a','p','h','i','c',' ','P','r','o','v','i','d','e','r',0 },
4422     {   'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\',
4423         'C','r','y','p','t','o','g','r','a','p','h','y','\\','D','e','f','a','u','l','t','s','\\',
4424         'P','r','o','v','i','d','e','r','\\','M','i','c','r','o','s','o','f','t',' ',
4425         'E','n','h','a','n','c','e','d',' ','R','S','A',' ','a','n','d',' ','A','E','S',' ',
4426         'C','r','y','p','t','o','g','r','a','p','h','i','c',' ','P','r','o','v','i','d','e','r',0 },
4427     {   'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\',
4428         'C','r','y','p','t','o','g','r','a','p','h','y','\\','D','e','f','a','u','l','t','s','\\',
4429         'P','r','o','v','i','d','e','r','\\','M','i','c','r','o','s','o','f','t',' ',
4430         'E','n','h','a','n','c','e','d',' ','R','S','A',' ','a','n','d',' ','A','E','S',' ',
4431         'C','r','y','p','t','o','g','r','a','p','h','i','c',' ','P','r','o','v','i','d','e','r',
4432         ' ','(','P','r','o','t','o','t','y','p','e',')',0 }
4433 };
4434 static const WCHAR szDefaultKeys[3][65] = {
4435     {   'S','o','f','t','w','a','r','e','\\',
4436         'M','i','c','r','o','s','o','f','t','\\','C','r','y','p','t','o','g','r',
4437         'a','p','h','y','\\','D','e','f','a','u','l','t','s','\\','P','r','o','v',
4438         'i','d','e','r',' ','T','y','p','e','s','\\','T','y','p','e',' ','0','0','1',0 },
4439     {   'S','o','f','t','w','a','r','e','\\',
4440         'M','i','c','r','o','s','o','f','t','\\','C','r','y','p','t','o','g','r',
4441         'a','p','h','y','\\','D','e','f','a','u','l','t','s','\\','P','r','o','v',
4442         'i','d','e','r',' ','T','y','p','e','s','\\','T','y','p','e',' ','0','1','2',0 },
4443     {   'S','o','f','t','w','a','r','e','\\',
4444         'M','i','c','r','o','s','o','f','t','\\','C','r','y','p','t','o','g','r',
4445         'a','p','h','y','\\','D','e','f','a','u','l','t','s','\\','P','r','o','v',
4446         'i','d','e','r',' ','T','y','p','e','s','\\','T','y','p','e',' ','0','2','4',0 }
4447 };
4448
4449
4450 /******************************************************************************
4451  * DllRegisterServer (RSAENH.@)
4452  *
4453  * Dll self registration. 
4454  *
4455  * PARAMS
4456  *
4457  * RETURNS
4458  *  Success: S_OK.
4459  *    Failure: != S_OK
4460  * 
4461  * NOTES
4462  *  Registers the following keys:
4463  *   - HKLM\Software\Microsoft\Cryptography\Defaults\Provider\
4464  *       Microsoft Base Cryptographic Provider v1.0
4465  *   - HKLM\Software\Microsoft\Cryptography\Defaults\Provider\
4466  *       Microsoft Enhanced Cryptographic Provider
4467  *   - HKLM\Software\Microsoft\Cryptography\Defaults\Provider\
4468  *       Microsoft Strong Cryptographpic Provider
4469  *   - HKLM\Software\Microsoft\Cryptography\Defaults\Provider Types\Type 001
4470  */
4471 HRESULT WINAPI DllRegisterServer(void)
4472 {
4473     HKEY key;
4474     DWORD dp;
4475     long apiRet;
4476     int i;
4477
4478     for (i=0; i<6; i++) {
4479         apiRet = RegCreateKeyExW(HKEY_LOCAL_MACHINE, szProviderKeys[i], 0, NULL,
4480             REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &key, &dp);
4481
4482         if (apiRet == ERROR_SUCCESS)
4483         {
4484             if (dp == REG_CREATED_NEW_KEY)
4485             {
4486                 static const WCHAR szImagePath[] = { 'I','m','a','g','e',' ','P','a','t','h',0 };
4487                 static const WCHAR szRSABase[] = { 'r','s','a','e','n','h','.','d','l','l',0 };
4488                 static const WCHAR szType[] = { 'T','y','p','e',0 };
4489                 static const WCHAR szSignature[] = { 'S','i','g','n','a','t','u','r','e',0 };
4490                 DWORD type, sign;
4491
4492                 switch(i)
4493                 {
4494                     case 3:
4495                         type=PROV_RSA_SCHANNEL;
4496                         break;
4497                     case 4:
4498                     case 5:
4499                         type=PROV_RSA_AES;
4500                         break;
4501                     default:
4502                         type=PROV_RSA_FULL;
4503                         break;
4504                 }
4505                 sign = 0xdeadbeef;
4506                 RegSetValueExW(key, szImagePath, 0, REG_SZ, (const BYTE *)szRSABase,
4507                                (lstrlenW(szRSABase) + 1) * sizeof(WCHAR));
4508                 RegSetValueExW(key, szType, 0, REG_DWORD, (LPBYTE)&type, sizeof(type));
4509                 RegSetValueExW(key, szSignature, 0, REG_BINARY, (LPBYTE)&sign, sizeof(sign));
4510             }
4511             RegCloseKey(key);
4512         }
4513     }
4514     
4515     for (i=0; i<3; i++) {
4516         apiRet = RegCreateKeyExW(HKEY_LOCAL_MACHINE, szDefaultKeys[i], 0, NULL,
4517                                  REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &key, &dp);
4518         if (apiRet == ERROR_SUCCESS)
4519         {
4520             if (dp == REG_CREATED_NEW_KEY)
4521             {
4522                 static const WCHAR szName[] = { 'N','a','m','e',0 };
4523                 static const WCHAR szRSAName[3][54] = {
4524                   { 'M','i','c','r','o','s','o','f','t',' ',
4525                     'E','n','h','a','n','c','e','d',' ',
4526                     'C','r','y','p','t','o','g','r','a','p','h','i','c',' ', 
4527                     'P','r','o','v','i','d','e','r',' ','v','1','.','0',0 },
4528                   { 'M','i','c','r','o','s','o','f','t',' ','R','S','A',' ',
4529                     'S','C','h','a','n','n','e','l',' ',
4530                     'C','r','y','p','t','o','g','r','a','p','h','i','c',' ',
4531                     'P','r','o','v','i','d','e','r',0 },
4532                   { 'M','i','c','r','o','s','o','f','t',' ','E','n','h','a','n','c','e','d',' ',
4533                     'R','S','A',' ','a','n','d',' ','A','E','S',' ',
4534                     'C','r','y','p','t','o','g','r','a','p','h','i','c',' ',
4535                     'P','r','o','v','i','d','e','r',0 } };
4536                 static const WCHAR szTypeName[] = { 'T','y','p','e','N','a','m','e',0 };
4537                 static const WCHAR szRSATypeName[3][38] = {
4538                   { 'R','S','A',' ','F','u','l','l',' ',
4539                        '(','S','i','g','n','a','t','u','r','e',' ','a','n','d',' ',
4540                     'K','e','y',' ','E','x','c','h','a','n','g','e',')',0 },
4541                   { 'R','S','A',' ','S','C','h','a','n','n','e','l',0 },
4542                   { 'R','S','A',' ','F','u','l','l',' ','a','n','d',' ','A','E','S',0 } };
4543
4544                 RegSetValueExW(key, szName, 0, REG_SZ,
4545                                 (const BYTE *)szRSAName[i], lstrlenW(szRSAName[i])*sizeof(WCHAR)+sizeof(WCHAR));
4546                 RegSetValueExW(key, szTypeName, 0, REG_SZ, 
4547                                 (const BYTE *)szRSATypeName[i], lstrlenW(szRSATypeName[i])*sizeof(WCHAR)+sizeof(WCHAR));
4548             }
4549         }
4550         RegCloseKey(key);
4551     }
4552     
4553     return HRESULT_FROM_WIN32(apiRet);
4554 }
4555
4556 /******************************************************************************
4557  * DllUnregisterServer (RSAENH.@)
4558  *
4559  * Dll self unregistration. 
4560  *
4561  * PARAMS
4562  *
4563  * RETURNS
4564  *  Success: S_OK
4565  *
4566  * NOTES
4567  *  For the relevant keys see DllRegisterServer.
4568  */
4569 HRESULT WINAPI DllUnregisterServer(void)
4570 {
4571     RegDeleteKeyW(HKEY_LOCAL_MACHINE, szProviderKeys[0]);
4572     RegDeleteKeyW(HKEY_LOCAL_MACHINE, szProviderKeys[1]);
4573     RegDeleteKeyW(HKEY_LOCAL_MACHINE, szProviderKeys[2]);
4574     RegDeleteKeyW(HKEY_LOCAL_MACHINE, szProviderKeys[3]);
4575     RegDeleteKeyW(HKEY_LOCAL_MACHINE, szProviderKeys[4]);
4576     RegDeleteKeyW(HKEY_LOCAL_MACHINE, szProviderKeys[5]);
4577     RegDeleteKeyW(HKEY_LOCAL_MACHINE, szDefaultKeys[0]);
4578     RegDeleteKeyW(HKEY_LOCAL_MACHINE, szDefaultKeys[1]);
4579     RegDeleteKeyW(HKEY_LOCAL_MACHINE, szDefaultKeys[2]);
4580     return S_OK;
4581 }