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