~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~ [ freetext search ] ~ [ file search ] ~

Wine Cross Reference
wine/dlls/rsaenh/rsaenh.c

Version: ~ [ wine-1.1.33 ] ~ [ wine-1.1.32 ] ~ [ wine-1.1.31 ] ~ [ wine-1.1.30 ] ~ [ wine-1.1.29 ] ~ [ wine-1.1.28 ] ~ [ wine-1.1.27 ] ~ [ wine-1.1.26 ] ~ [ wine-1.1.25 ] ~ [ wine-1.1.24 ] ~ [ wine-1.1.23 ] ~ [ wine-1.1.22 ] ~ [ wine-1.1.21 ] ~ [ wine-1.1.20 ] ~ [ wine-1.1.19 ] ~ [ wine-1.1.18 ] ~ [ wine-1.1.17 ] ~ [ wine-1.1.16 ] ~ [ wine-1.1.15 ] ~ [ wine-1.1.14 ] ~ [ wine-1.1.13 ] ~ [ wine-1.1.12 ] ~ [ wine-1.1.11 ] ~ [ wine-1.1.10 ] ~ [ wine-1.1.9 ] ~ [ wine-1.1.8 ] ~ [ wine-1.1.7 ] ~ [ wine-1.0.1 ] ~ [ wine-1.1.6 ] ~ [ wine-1.1.5 ] ~ [ wine-1.1.4 ] ~ [ wine-1.1.3 ] ~ [ wine-1.1.2 ] ~ [ wine-1.1.1 ] ~ [ wine-1.1.0 ] ~ [ wine-1.0 ] ~

  1 /*
  2  * dlls/rsaenh/rsaenh.c
  3  * RSAENH - RSA encryption for Wine
  4  *
  5  * Copyright 2002 TransGaming Technologies (David Hammerton)
  6  * Copyright 2004 Mike McCormack for CodeWeavers
  7  * Copyright 2004, 2005 Michael Jung
  8  * Copyright 2007 Vijay Kiran Kamuju
  9  *
 10  * This library is free software; you can redistribute it and/or
 11  * modify it under the terms of the GNU Lesser General Public
 12  * License as published by the Free Software Foundation; either
 13  * version 2.1 of the License, or (at your option) any later version.
 14  *
 15  * This library is distributed in the hope that it will be useful,
 16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
 17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 18  * Lesser General Public License for more details.
 19  *
 20  * You should have received a copy of the GNU Lesser General Public
 21  * License along with this library; if not, write to the Free Software
 22  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 23  */
 24 
 25 #include "config.h"
 26 #include "wine/port.h"
 27 #include "wine/library.h"
 28 #include "wine/debug.h"
 29 
 30 #include <stdarg.h>
 31 #include <stdio.h>
 32 
 33 #include "windef.h"
 34 #include "winbase.h"
 35 #include "winreg.h"
 36 #include "wincrypt.h"
 37 #include "handle.h"
 38 #include "implglue.h"
 39 #include "objbase.h"
 40 
 41 WINE_DEFAULT_DEBUG_CHANNEL(crypt);
 42 
 43 /******************************************************************************
 44  * CRYPTHASH - hash objects
 45  */
 46 #define RSAENH_MAGIC_HASH           0x85938417u
 47 #define RSAENH_MAX_HASH_SIZE        104
 48 #define RSAENH_HASHSTATE_HASHING    1
 49 #define RSAENH_HASHSTATE_FINISHED   2
 50 typedef struct _RSAENH_TLS1PRF_PARAMS
 51 {
 52     CRYPT_DATA_BLOB blobLabel;
 53     CRYPT_DATA_BLOB blobSeed;
 54 } RSAENH_TLS1PRF_PARAMS;
 55 
 56 typedef struct tagCRYPTHASH
 57 {
 58     OBJECTHDR    header;
 59     ALG_ID       aiAlgid;
 60     HCRYPTKEY    hKey;
 61     HCRYPTPROV   hProv;
 62     DWORD        dwHashSize;
 63     DWORD        dwState;
 64     HASH_CONTEXT context;
 65     BYTE         abHashValue[RSAENH_MAX_HASH_SIZE];
 66     PHMAC_INFO   pHMACInfo;
 67     RSAENH_TLS1PRF_PARAMS tpPRFParams;
 68 } CRYPTHASH;
 69 
 70 /******************************************************************************
 71  * CRYPTKEY - key objects
 72  */
 73 #define RSAENH_MAGIC_KEY           0x73620457u
 74 #define RSAENH_MAX_KEY_SIZE        48
 75 #define RSAENH_MAX_BLOCK_SIZE      24
 76 #define RSAENH_KEYSTATE_IDLE       0
 77 #define RSAENH_KEYSTATE_ENCRYPTING 1
 78 #define RSAENH_KEYSTATE_MASTERKEY  2
 79 typedef struct _RSAENH_SCHANNEL_INFO 
 80 {
 81     SCHANNEL_ALG saEncAlg;
 82     SCHANNEL_ALG saMACAlg;
 83     CRYPT_DATA_BLOB blobClientRandom;
 84     CRYPT_DATA_BLOB blobServerRandom;
 85 } RSAENH_SCHANNEL_INFO;
 86 
 87 typedef struct tagCRYPTKEY
 88 {
 89     OBJECTHDR   header;
 90     ALG_ID      aiAlgid;
 91     HCRYPTPROV  hProv;
 92     DWORD       dwMode;
 93     DWORD       dwModeBits;
 94     DWORD       dwPermissions;
 95     DWORD       dwKeyLen;
 96     DWORD       dwEffectiveKeyLen;
 97     DWORD       dwSaltLen;
 98     DWORD       dwBlockLen;
 99     DWORD       dwState;
100     KEY_CONTEXT context;    
101     BYTE        abKeyValue[RSAENH_MAX_KEY_SIZE];
102     BYTE        abInitVector[RSAENH_MAX_BLOCK_SIZE];
103     BYTE        abChainVector[RSAENH_MAX_BLOCK_SIZE];
104     RSAENH_SCHANNEL_INFO siSChannelInfo;
105 } CRYPTKEY;
106 
107 /******************************************************************************
108  * KEYCONTAINER - key containers
109  */
110 #define RSAENH_PERSONALITY_BASE        0u
111 #define RSAENH_PERSONALITY_STRONG      1u
112 #define RSAENH_PERSONALITY_ENHANCED    2u
113 #define RSAENH_PERSONALITY_SCHANNEL    3u
114 #define RSAENH_PERSONALITY_AES         4u
115 
116 #define RSAENH_MAGIC_CONTAINER         0x26384993u
117 typedef struct tagKEYCONTAINER
118 {
119     OBJECTHDR    header;
120     DWORD        dwFlags;
121     DWORD        dwPersonality;
122     DWORD        dwEnumAlgsCtr;
123     DWORD        dwEnumContainersCtr;
124     CHAR         szName[MAX_PATH];
125     CHAR         szProvName[MAX_PATH];
126     HCRYPTKEY    hKeyExchangeKeyPair;
127     HCRYPTKEY    hSignatureKeyPair;
128 } KEYCONTAINER;
129 
130 /******************************************************************************
131  * Some magic constants
132  */
133 #define RSAENH_ENCRYPT                    1
134 #define RSAENH_DECRYPT                    0    
135 #define RSAENH_HMAC_DEF_IPAD_CHAR      0x36
136 #define RSAENH_HMAC_DEF_OPAD_CHAR      0x5c
137 #define RSAENH_HMAC_DEF_PAD_LEN          64
138 #define RSAENH_DES_EFFECTIVE_KEYLEN      56
139 #define RSAENH_DES_STORAGE_KEYLEN        64
140 #define RSAENH_3DES112_EFFECTIVE_KEYLEN 112
141 #define RSAENH_3DES112_STORAGE_KEYLEN   128
142 #define RSAENH_3DES_EFFECTIVE_KEYLEN    168
143 #define RSAENH_3DES_STORAGE_KEYLEN      192
144 #define RSAENH_MAGIC_RSA2        0x32415352
145 #define RSAENH_MAGIC_RSA1        0x31415352
146 #define RSAENH_PKC_BLOCKTYPE           0x02
147 #define RSAENH_SSL3_VERSION_MAJOR         3
148 #define RSAENH_SSL3_VERSION_MINOR         0
149 #define RSAENH_TLS1_VERSION_MAJOR         3
150 #define RSAENH_TLS1_VERSION_MINOR         1
151 #define RSAENH_REGKEY "Software\\Wine\\Crypto\\RSA\\%s"
152 
153 #define RSAENH_MIN(a,b) ((a)<(b)?(a):(b))
154 /******************************************************************************
155  * aProvEnumAlgsEx - Defines the capabilities of the CSP personalities.
156  */
157 #define RSAENH_MAX_ENUMALGS 24
158 #define RSAENH_PCT1_SSL2_SSL3_TLS1 (CRYPT_FLAG_PCT1|CRYPT_FLAG_SSL2|CRYPT_FLAG_SSL3|CRYPT_FLAG_TLS1)
159 static const PROV_ENUMALGS_EX aProvEnumAlgsEx[5][RSAENH_MAX_ENUMALGS+1] =
160 {
161  {
162   {CALG_RC2,       40, 40,   56,0,                    4,"RC2",     24,"RSA Data Security's RC2"},
163   {CALG_RC4,       40, 40,   56,0,                    4,"RC4",     24,"RSA Data Security's RC4"},
164   {CALG_DES,       56, 56,   56,0,                    4,"DES",     31,"Data Encryption Standard (DES)"},
165   {CALG_SHA,      160,160,  160,CRYPT_FLAG_SIGNING,   6,"SHA-1",   30,"Secure Hash Algorithm (SHA-1)"},
166   {CALG_MD2,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD2",     23,"Message Digest 2 (MD2)"},
167   {CALG_MD4,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD4",     23,"Message Digest 4 (MD4)"},
168   {CALG_MD5,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD5",     23,"Message Digest 5 (MD5)"},
169   {CALG_SSL3_SHAMD5,288,288,288,0,                   12,"SSL3 SHAMD5",12,"SSL3 SHAMD5"},
170   {CALG_MAC,        0,  0,    0,0,                    4,"MAC",     28,"Message Authentication Code"},
171   {CALG_RSA_SIGN, 512,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_SIGN",14,"RSA Signature"},
172   {CALG_RSA_KEYX, 512,384, 1024,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_KEYX",17,"RSA Key Exchange"},
173   {CALG_HMAC,       0,  0,    0,0,                    5,"HMAC",    18,"Hugo's MAC (HMAC)"},
174   {0,               0,  0,    0,0,                    1,"",         1,""}
175  },
176  {
177   {CALG_RC2,      128, 40,  128,0,                    4,"RC2",     24,"RSA Data Security's RC2"},
178   {CALG_RC4,      128, 40,  128,0,                    4,"RC4",     24,"RSA Data Security's RC4"},
179   {CALG_DES,       56, 56,   56,0,                    4,"DES",     31,"Data Encryption Standard (DES)"},
180   {CALG_3DES_112, 112,112,  112,0,                   13,"3DES TWO KEY",19,"Two Key Triple DES"},
181   {CALG_3DES,     168,168,  168,0,                    5,"3DES",    21,"Three Key Triple DES"},
182   {CALG_SHA,      160,160,  160,CRYPT_FLAG_SIGNING,   6,"SHA-1",   30,"Secure Hash Algorithm (SHA-1)"},
183   {CALG_MD2,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD2",     23,"Message Digest 2 (MD2)"},
184   {CALG_MD4,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD4",     23,"Message Digest 4 (MD4)"},
185   {CALG_MD5,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD5",     23,"Message Digest 5 (MD5)"},
186   {CALG_SSL3_SHAMD5,288,288,288,0,                   12,"SSL3 SHAMD5",12,"SSL3 SHAMD5"},
187   {CALG_MAC,        0,  0,    0,0,                    4,"MAC",     28,"Message Authentication Code"},
188   {CALG_RSA_SIGN,1024,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_SIGN",14,"RSA Signature"},
189   {CALG_RSA_KEYX,1024,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_KEYX",17,"RSA Key Exchange"},
190   {CALG_HMAC,       0,  0,    0,0,                    5,"HMAC",    18,"Hugo's MAC (HMAC)"},
191   {0,               0,  0,    0,0,                    1,"",         1,""}
192  },
193  {
194   {CALG_RC2,      128, 40,  128,0,                    4,"RC2",     24,"RSA Data Security's RC2"},
195   {CALG_RC4,      128, 40,  128,0,                    4,"RC4",     24,"RSA Data Security's RC4"},
196   {CALG_DES,       56, 56,   56,0,                    4,"DES",     31,"Data Encryption Standard (DES)"},
197   {CALG_3DES_112, 112,112,  112,0,                   13,"3DES TWO KEY",19,"Two Key Triple DES"},
198   {CALG_3DES,     168,168,  168,0,                    5,"3DES",    21,"Three Key Triple DES"},
199   {CALG_SHA,      160,160,  160,CRYPT_FLAG_SIGNING,   6,"SHA-1",   30,"Secure Hash Algorithm (SHA-1)"},
200   {CALG_MD2,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD2",     23,"Message Digest 2 (MD2)"},
201   {CALG_MD4,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD4",     23,"Message Digest 4 (MD4)"},
202   {CALG_MD5,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD5",     23,"Message Digest 5 (MD5)"},
203   {CALG_SSL3_SHAMD5,288,288,288,0,                   12,"SSL3 SHAMD5",12,"SSL3 SHAMD5"},
204   {CALG_MAC,        0,  0,    0,0,                    4,"MAC",     28,"Message Authentication Code"},
205   {CALG_RSA_SIGN,1024,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_SIGN",14,"RSA Signature"},
206   {CALG_RSA_KEYX,1024,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_KEYX",17,"RSA Key Exchange"},
207   {CALG_HMAC,       0,  0,    0,0,                    5,"HMAC",    18,"Hugo's MAC (HMAC)"},
208   {0,               0,  0,    0,0,                    1,"",         1,""}
209  },
210  {
211   {CALG_RC2,      128, 40,  128,RSAENH_PCT1_SSL2_SSL3_TLS1, 4,"RC2",        24,"RSA Data Security's RC2"},
212   {CALG_RC4,      128, 40,  128,RSAENH_PCT1_SSL2_SSL3_TLS1, 4,"RC4",        24,"RSA Data Security's RC4"},
213   {CALG_DES,       56, 56,   56,RSAENH_PCT1_SSL2_SSL3_TLS1, 4,"DES",        31,"Data Encryption Standard (DES)"},
214   {CALG_3DES_112, 112,112,  112,RSAENH_PCT1_SSL2_SSL3_TLS1,13,"3DES TWO KEY",19,"Two Key Triple DES"},
215   {CALG_3DES,     168,168,  168,RSAENH_PCT1_SSL2_SSL3_TLS1, 5,"3DES",       21,"Three Key Triple DES"},
216   {CALG_SHA,160,160,160,CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1,6,"SHA-1",30,"Secure Hash Algorithm (SHA-1)"},
217   {CALG_MD5,128,128,128,CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1,4,"MD5",23,"Message Digest 5 (MD5)"},
218   {CALG_SSL3_SHAMD5,288,288,288,0,                         12,"SSL3 SHAMD5",12,"SSL3 SHAMD5"},
219   {CALG_MAC,        0,  0,    0,0,                          4,"MAC",        28,"Message Authentication Code"},
220   {CALG_RSA_SIGN,1024,384,16384,CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1,9,"RSA_SIGN",14,"RSA Signature"},
221   {CALG_RSA_KEYX,1024,384,16384,CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1,9,"RSA_KEYX",17,"RSA Key Exchange"},
222   {CALG_HMAC,       0,  0,    0,0,                          5,"HMAC",       18,"Hugo's MAC (HMAC)"},
223   {CALG_PCT1_MASTER,128,128,128,CRYPT_FLAG_PCT1,           12,"PCT1 MASTER",12,"PCT1 Master"},
224   {CALG_SSL2_MASTER,40,40,  192,CRYPT_FLAG_SSL2,           12,"SSL2 MASTER",12,"SSL2 Master"},
225   {CALG_SSL3_MASTER,384,384,384,CRYPT_FLAG_SSL3,           12,"SSL3 MASTER",12,"SSL3 Master"},
226   {CALG_TLS1_MASTER,384,384,384,CRYPT_FLAG_TLS1,           12,"TLS1 MASTER",12,"TLS1 Master"},
227   {CALG_SCHANNEL_MASTER_HASH,0,0,-1,0,                     16,"SCH MASTER HASH",21,"SChannel Master Hash"},
228   {CALG_SCHANNEL_MAC_KEY,0,0,-1,0,                         12,"SCH MAC KEY",17,"SChannel MAC Key"},
229   {CALG_SCHANNEL_ENC_KEY,0,0,-1,0,                         12,"SCH ENC KEY",24,"SChannel Encryption Key"},
230   {CALG_TLS1PRF,    0,  0,   -1,0,                          9,"TLS1 PRF",   28,"TLS1 Pseudo Random Function"},
231   {0,               0,  0,    0,0,                          1,"",            1,""}
232  },
233  {
234   {CALG_RC2,      128, 40,  128,0,                    4,"RC2",     24,"RSA Data Security's RC2"},
235   {CALG_RC4,      128, 40,  128,0,                    4,"RC4",     24,"RSA Data Security's RC4"},
236   {CALG_DES,       56, 56,   56,0,                    4,"DES",     31,"Data Encryption Standard (DES)"},
237   {CALG_3DES_112, 112,112,  112,0,                   13,"3DES TWO KEY",19,"Two Key Triple DES"},
238   {CALG_3DES,     168,168,  168,0,                    5,"3DES",    21,"Three Key Triple DES"},
239   {CALG_AES,      128,128,  128,0,                    4,"AES",     35,"Advanced Encryption Standard (AES)"},
240   {CALG_AES_128,  128,128,  128,0,                    8,"AES-128", 39,"Advanced Encryption Standard (AES-128)"},
241   {CALG_AES_192,  192,192,  192,0,                    8,"AES-192", 39,"Advanced Encryption Standard (AES-192)"},
242   {CALG_AES_256,  256,256,  256,0,                    8,"AES-256", 39,"Advanced Encryption Standard (AES-256)"},
243   {CALG_SHA,      160,160,  160,CRYPT_FLAG_SIGNING,   6,"SHA-1",   30,"Secure Hash Algorithm (SHA-1)"},
244   {CALG_MD2,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD2",     23,"Message Digest 2 (MD2)"},
245   {CALG_MD4,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD4",     23,"Message Digest 4 (MD4)"},
246   {CALG_MD5,      128,128,  128,CRYPT_FLAG_SIGNING,   4,"MD5",     23,"Message Digest 5 (MD5)"},
247   {CALG_SSL3_SHAMD5,288,288,288,0,                   12,"SSL3 SHAMD5",12,"SSL3 SHAMD5"},
248   {CALG_MAC,        0,  0,    0,0,                    4,"MAC",     28,"Message Authentication Code"},
249   {CALG_RSA_SIGN,1024,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_SIGN",14,"RSA Signature"},
250   {CALG_RSA_KEYX,1024,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_KEYX",17,"RSA Key Exchange"},
251   {CALG_HMAC,       0,  0,    0,0,                    5,"HMAC",    18,"Hugo's MAC (HMAC)"},
252   {0,               0,  0,    0,0,                    1,"",         1,""}
253  }
254 };
255 
256 /******************************************************************************
257  * API forward declarations
258  */
259 BOOL WINAPI 
260 RSAENH_CPGetKeyParam(
261     HCRYPTPROV hProv, 
262     HCRYPTKEY hKey, 
263     DWORD dwParam, 
264     BYTE *pbData, 
265     DWORD *pdwDataLen, 
266     DWORD dwFlags
267 );
268 
269 BOOL WINAPI 
270 RSAENH_CPEncrypt(
271     HCRYPTPROV hProv, 
272     HCRYPTKEY hKey, 
273     HCRYPTHASH hHash, 
274     BOOL Final, 
275     DWORD dwFlags, 
276     BYTE *pbData,
277     DWORD *pdwDataLen, 
278     DWORD dwBufLen
279 );
280 
281 BOOL WINAPI 
282 RSAENH_CPCreateHash(
283     HCRYPTPROV hProv, 
284     ALG_ID Algid, 
285     HCRYPTKEY hKey, 
286     DWORD dwFlags, 
287     HCRYPTHASH *phHash
288 );
289 
290 BOOL WINAPI 
291 RSAENH_CPSetHashParam(
292     HCRYPTPROV hProv, 
293     HCRYPTHASH hHash, 
294     DWORD dwParam, 
295     BYTE *pbData, DWORD dwFlags
296 );
297 
298 BOOL WINAPI 
299 RSAENH_CPGetHashParam(
300     HCRYPTPROV hProv, 
301     HCRYPTHASH hHash, 
302     DWORD dwParam, 
303     BYTE *pbData, 
304     DWORD *pdwDataLen, 
305     DWORD dwFlags
306 );
307 
308 BOOL WINAPI 
309 RSAENH_CPDestroyHash(
310     HCRYPTPROV hProv, 
311     HCRYPTHASH hHash
312 );
313 
314 static BOOL crypt_export_key(
315     CRYPTKEY *pCryptKey,
316     HCRYPTKEY hPubKey, 
317     DWORD dwBlobType, 
318     DWORD dwFlags, 
319     BOOL force,
320     BYTE *pbData, 
321     DWORD *pdwDataLen
322 );
323 
324 static BOOL import_key(
325     HCRYPTPROV hProv, 
326     CONST BYTE *pbData, 
327     DWORD dwDataLen, 
328     HCRYPTKEY hPubKey, 
329     DWORD dwFlags, 
330     BOOL fStoreKey,
331     HCRYPTKEY *phKey
332 );
333 
334 BOOL WINAPI 
335 RSAENH_CPHashData(
336     HCRYPTPROV hProv, 
337     HCRYPTHASH hHash, 
338     CONST BYTE *pbData, 
339     DWORD dwDataLen, 
340     DWORD dwFlags
341 );
342 
343 /******************************************************************************
344  * CSP's handle table (used by all acquired key containers)
345  */
346 static struct handle_table handle_table;
347 
348 /******************************************************************************
349  * DllMain (RSAENH.@)
350  *
351  * Initializes and destroys the handle table for the CSP's handles.
352  */
353 int WINAPI DllMain(HINSTANCE hInstance, DWORD fdwReason, PVOID pvReserved)
354 {
355     switch (fdwReason)
356     {
357         case DLL_PROCESS_ATTACH:
358             DisableThreadLibraryCalls(hInstance);
359             init_handle_table(&handle_table);
360             break;
361 
362         case DLL_PROCESS_DETACH:
363             destroy_handle_table(&handle_table);
364             break;
365     }
366     return 1;
367 }
368 
369 /******************************************************************************
370  * copy_param [Internal]
371  *
372  * Helper function that supports the standard WINAPI protocol for querying data
373  * of dynamic size.
374  *
375  * PARAMS
376  *  pbBuffer      [O]   Buffer where the queried parameter is copied to, if it is large enough.
377  *                      May be NUL if the required buffer size is to be queried only.
378  *  pdwBufferSize [I/O] In: Size of the buffer at pbBuffer
379  *                      Out: Size of parameter pbParam
380  *  pbParam       [I]   Parameter value.
381  *  dwParamSize   [I]   Size of pbParam
382  *
383  * RETURN
384  *  Success: TRUE (pbParam was copied into pbBuffer or pbBuffer is NULL)
385  *  Failure: FALSE (pbBuffer is not large enough to hold pbParam). Last error: ERROR_MORE_DATA
386  */
387 static inline BOOL copy_param(
388     BYTE *pbBuffer, DWORD *pdwBufferSize, CONST BYTE *pbParam, DWORD dwParamSize) 
389 {
390     if (pbBuffer) 
391     {
392         if (dwParamSize > *pdwBufferSize) 
393         {
394             SetLastError(ERROR_MORE_DATA);
395             *pdwBufferSize = dwParamSize;
396             return FALSE;
397         }
398         memcpy(pbBuffer, pbParam, dwParamSize);
399     }
400     *pdwBufferSize = dwParamSize;
401     return TRUE;
402 }
403 
404 /******************************************************************************
405  * get_algid_info [Internal]
406  *
407  * Query CSP capabilities for a given crypto algorithm.
408  * 
409  * PARAMS
410  *  hProv [I] Handle to a key container of the CSP whose capabilities are to be queried.
411  *  algid [I] Identifier of the crypto algorithm about which information is requested.
412  *
413  * RETURNS
414  *  Success: Pointer to a PROV_ENUMALGS_EX struct containing information about the crypto algorithm.
415  *  Failure: NULL (algid not supported)
416  */
417 static inline const PROV_ENUMALGS_EX* get_algid_info(HCRYPTPROV hProv, ALG_ID algid) {
418     const PROV_ENUMALGS_EX *iterator;
419     KEYCONTAINER *pKeyContainer;
420 
421     if (!lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER, (OBJECTHDR**)&pKeyContainer)) {
422         SetLastError(NTE_BAD_UID);
423         return NULL;
424     }
425 
426     for (iterator = aProvEnumAlgsEx[pKeyContainer->dwPersonality]; iterator->aiAlgid; iterator++) {
427         if (iterator->aiAlgid == algid) return iterator;
428     }
429 
430     SetLastError(NTE_BAD_ALGID);
431     return NULL;
432 }
433 
434 /******************************************************************************
435  * copy_data_blob [Internal] 
436  *
437  * deeply copies a DATA_BLOB
438  *
439  * PARAMS
440  *  dst [O] That's where the blob will be copied to
441  *  src [I] Source blob
442  *
443  * RETURNS
444  *  Success: TRUE
445  *  Failure: FALSE (GetLastError() == NTE_NO_MEMORY
446  *
447  * NOTES
448  *  Use free_data_blob to release resources occupied by copy_data_blob.
449  */
450 static inline BOOL copy_data_blob(PCRYPT_DATA_BLOB dst, CONST PCRYPT_DATA_BLOB src) {
451     dst->pbData = HeapAlloc(GetProcessHeap(), 0, src->cbData);
452     if (!dst->pbData) {
453         SetLastError(NTE_NO_MEMORY);
454         return FALSE;
455     }    
456     dst->cbData = src->cbData;
457     memcpy(dst->pbData, src->pbData, src->cbData);
458     return TRUE;
459 }
460 
461 /******************************************************************************
462  * concat_data_blobs [Internal]
463  *
464  * Concatenates two blobs
465  *
466  * PARAMS
467  *  dst  [O] The new blob will be copied here
468  *  src1 [I] Prefix blob
469  *  src2 [I] Appendix blob
470  *
471  * RETURNS
472  *  Success: TRUE
473  *  Failure: FALSE (GetLastError() == NTE_NO_MEMORY)
474  *
475  * NOTES
476  *  Release resources occupied by concat_data_blobs with free_data_blobs
477  */
478 static inline BOOL concat_data_blobs(PCRYPT_DATA_BLOB dst, CONST PCRYPT_DATA_BLOB src1, 
479                                      CONST PCRYPT_DATA_BLOB src2) 
480 {
481     dst->cbData = src1->cbData + src2->cbData;
482     dst->pbData = HeapAlloc(GetProcessHeap(), 0, dst->cbData);
483     if (!dst->pbData) {
484         SetLastError(NTE_NO_MEMORY);
485         return FALSE;
486     }
487     memcpy(dst->pbData, src1->pbData, src1->cbData);
488     memcpy(dst->pbData + src1->cbData, src2->pbData, src2->cbData);
489     return TRUE;
490 }
491 
492 /******************************************************************************
493  * free_data_blob [Internal]
494  *
495  * releases resource occupied by a dynamically allocated CRYPT_DATA_BLOB
496  * 
497  * PARAMS
498  *  pBlob [I] Heap space occupied by pBlob->pbData is released
499  */
500 static inline void free_data_blob(PCRYPT_DATA_BLOB pBlob) {
501     HeapFree(GetProcessHeap(), 0, pBlob->pbData);
502 }
503 
504 /******************************************************************************
505  * init_data_blob [Internal]
506  */
507 static inline void init_data_blob(PCRYPT_DATA_BLOB pBlob) {
508     pBlob->pbData = NULL;
509     pBlob->cbData = 0;
510 }
511 
512 /******************************************************************************
513  * free_hmac_info [Internal]
514  *
515  * Deeply free an HMAC_INFO struct.
516  *
517  * PARAMS
518  *  hmac_info [I] Pointer to the HMAC_INFO struct to be freed.
519  *
520  * NOTES
521  *  See Internet RFC 2104 for details on the HMAC algorithm.
522  */
523 static inline void free_hmac_info(PHMAC_INFO hmac_info) {
524     if (!hmac_info) return;
525     HeapFree(GetProcessHeap(), 0, hmac_info->pbInnerString);
526     HeapFree(GetProcessHeap(), 0, hmac_info->pbOuterString);
527     HeapFree(GetProcessHeap(), 0, hmac_info);
528 }
529 
530 /******************************************************************************
531  * copy_hmac_info [Internal]
532  *
533  * Deeply copy an HMAC_INFO struct
534  *
535  * PARAMS
536  *  dst [O] Pointer to a location where the pointer to the HMAC_INFO copy will be stored.
537  *  src [I] Pointer to the HMAC_INFO struct to be copied.
538  *
539  * RETURNS
540  *  Success: TRUE
541  *  Failure: FALSE
542  *
543  * NOTES
544  *  See Internet RFC 2104 for details on the HMAC algorithm.
545  */
546 static BOOL copy_hmac_info(PHMAC_INFO *dst, const HMAC_INFO *src) {
547     if (!src) return FALSE;
548     *dst = HeapAlloc(GetProcessHeap(), 0, sizeof(HMAC_INFO));
549     if (!*dst) return FALSE;
550     **dst = *src;
551     (*dst)->pbInnerString = NULL;
552     (*dst)->pbOuterString = NULL;
553     if ((*dst)->cbInnerString == 0) (*dst)->cbInnerString = RSAENH_HMAC_DEF_PAD_LEN;
554     (*dst)->pbInnerString = HeapAlloc(GetProcessHeap(), 0, (*dst)->cbInnerString);
555     if (!(*dst)->pbInnerString) {
556         free_hmac_info(*dst);
557         return FALSE;
558     }
559     if (src->cbInnerString) 
560         memcpy((*dst)->pbInnerString, src->pbInnerString, src->cbInnerString);
561     else 
562         memset((*dst)->pbInnerString, RSAENH_HMAC_DEF_IPAD_CHAR, RSAENH_HMAC_DEF_PAD_LEN);
563     if ((*dst)->cbOuterString == 0) (*dst)->cbOuterString = RSAENH_HMAC_DEF_PAD_LEN;
564     (*dst)->pbOuterString = HeapAlloc(GetProcessHeap(), 0, (*dst)->cbOuterString);
565     if (!(*dst)->pbOuterString) {
566         free_hmac_info(*dst);
567         return FALSE;
568     }
569     if (src->cbOuterString) 
570         memcpy((*dst)->pbOuterString, src->pbOuterString, src->cbOuterString);
571     else 
572         memset((*dst)->pbOuterString, RSAENH_HMAC_DEF_OPAD_CHAR, RSAENH_HMAC_DEF_PAD_LEN);
573     return TRUE;
574 }
575 
576 /******************************************************************************
577  * destroy_hash [Internal]
578  *
579  * Destructor for hash objects
580  *
581  * PARAMS
582  *  pCryptHash [I] Pointer to the hash object to be destroyed. 
583  *                 Will be invalid after function returns!
584  */
585 static void destroy_hash(OBJECTHDR *pObject)
586 {
587     CRYPTHASH *pCryptHash = (CRYPTHASH*)pObject;
588         
589     free_hmac_info(pCryptHash->pHMACInfo);
590     free_data_blob(&pCryptHash->tpPRFParams.blobLabel);
591     free_data_blob(&pCryptHash->tpPRFParams.blobSeed);
592     HeapFree(GetProcessHeap(), 0, pCryptHash);
593 }
594 
595 /******************************************************************************
596  * init_hash [Internal]
597  *
598  * Initialize (or reset) a hash object
599  *
600  * PARAMS
601  *  pCryptHash    [I] The hash object to be initialized.
602  */
603 static inline BOOL init_hash(CRYPTHASH *pCryptHash) {
604     DWORD dwLen;
605         
606     switch (pCryptHash->aiAlgid) 
607     {
608         case CALG_HMAC:
609             if (pCryptHash->pHMACInfo) { 
610                 const PROV_ENUMALGS_EX *pAlgInfo;
611                 
612                 pAlgInfo = get_algid_info(pCryptHash->hProv, pCryptHash->pHMACInfo->HashAlgid);
613                 if (!pAlgInfo) return FALSE;
614                 pCryptHash->dwHashSize = pAlgInfo->dwDefaultLen >> 3;
615                 init_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context);
616                 update_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
617                                  pCryptHash->pHMACInfo->pbInnerString, 
618                                  pCryptHash->pHMACInfo->cbInnerString);
619             }
620             return TRUE;
621             
622         case CALG_MAC:
623             dwLen = sizeof(DWORD);
624             RSAENH_CPGetKeyParam(pCryptHash->hProv, pCryptHash->hKey, KP_BLOCKLEN, 
625                                  (BYTE*)&pCryptHash->dwHashSize, &dwLen, 0);
626             pCryptHash->dwHashSize >>= 3;
627             return TRUE;
628 
629         default:
630             return init_hash_impl(pCryptHash->aiAlgid, &pCryptHash->context);
631     }
632 }
633 
634 /******************************************************************************
635  * update_hash [Internal]
636  *
637  * Hashes the given data and updates the hash object's state accordingly
638  *
639  * PARAMS
640  *  pCryptHash [I] Hash object to be updated.
641  *  pbData     [I] Pointer to data stream to be hashed.
642  *  dwDataLen  [I] Length of data stream.
643  */
644 static inline void update_hash(CRYPTHASH *pCryptHash, CONST BYTE *pbData, DWORD dwDataLen) {
645     BYTE *pbTemp;
646 
647     switch (pCryptHash->aiAlgid)
648     {
649         case CALG_HMAC:
650             if (pCryptHash->pHMACInfo) 
651                 update_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context, 
652                                  pbData, dwDataLen);
653             break;
654 
655         case CALG_MAC:
656             pbTemp = HeapAlloc(GetProcessHeap(), 0, dwDataLen);
657             if (!pbTemp) return;
658             memcpy(pbTemp, pbData, dwDataLen);
659             RSAENH_CPEncrypt(pCryptHash->hProv, pCryptHash->hKey, 0, FALSE, 0,
660                              pbTemp, &dwDataLen, dwDataLen);
661             HeapFree(GetProcessHeap(), 0, pbTemp);
662             break;
663 
664         default:
665             update_hash_impl(pCryptHash->aiAlgid, &pCryptHash->context, pbData, dwDataLen);
666     }
667 }
668 
669 /******************************************************************************
670  * finalize_hash [Internal]
671  *
672  * Finalizes the hash, after all data has been hashed with update_hash.
673  * No additional data can be hashed afterwards until the hash gets initialized again.
674  *
675  * PARAMS
676  *  pCryptHash [I] Hash object to be finalized.
677  */
678 static inline void finalize_hash(CRYPTHASH *pCryptHash) {
679     DWORD dwDataLen;
680         
681     switch (pCryptHash->aiAlgid)
682     {
683         case CALG_HMAC:
684             if (pCryptHash->pHMACInfo) {
685                 BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
686 
687                 finalize_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context, 
688                                    pCryptHash->abHashValue);
689                 memcpy(abHashValue, pCryptHash->abHashValue, pCryptHash->dwHashSize);
690                 init_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context);
691                 update_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
692                                  pCryptHash->pHMACInfo->pbOuterString, 
693                                  pCryptHash->pHMACInfo->cbOuterString);
694                 update_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
695                                  abHashValue, pCryptHash->dwHashSize);
696                 finalize_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
697                                    pCryptHash->abHashValue);
698             } 
699             break;
700 
701         case CALG_MAC:
702             dwDataLen = 0;
703             RSAENH_CPEncrypt(pCryptHash->hProv, pCryptHash->hKey, 0, TRUE, 0,
704                              pCryptHash->abHashValue, &dwDataLen, pCryptHash->dwHashSize);
705             break;
706 
707         default:
708             finalize_hash_impl(pCryptHash->aiAlgid, &pCryptHash->context, pCryptHash->abHashValue);
709     }
710 }
711 
712 /******************************************************************************
713  * destroy_key [Internal]
714  *
715  * Destructor for key objects
716  *
717  * PARAMS
718  *  pCryptKey [I] Pointer to the key object to be destroyed. 
719  *                Will be invalid after function returns!
720  */
721 static void destroy_key(OBJECTHDR *pObject)
722 {
723     CRYPTKEY *pCryptKey = (CRYPTKEY*)pObject;
724         
725     free_key_impl(pCryptKey->aiAlgid, &pCryptKey->context);
726     free_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom);
727     free_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom);
728     HeapFree(GetProcessHeap(), 0, pCryptKey);
729 }
730 
731 /******************************************************************************
732  * setup_key [Internal]
733  *
734  * Initialize (or reset) a key object
735  *
736  * PARAMS
737  *  pCryptKey    [I] The key object to be initialized.
738  */
739 static inline void setup_key(CRYPTKEY *pCryptKey) {
740     pCryptKey->dwState = RSAENH_KEYSTATE_IDLE;
741     memcpy(pCryptKey->abChainVector, pCryptKey->abInitVector, sizeof(pCryptKey->abChainVector));
742     setup_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen, 
743                    pCryptKey->dwEffectiveKeyLen, pCryptKey->dwSaltLen,
744                    pCryptKey->abKeyValue);
745 }
746 
747 /******************************************************************************
748  * new_key [Internal]
749  *
750  * Creates a new key object without assigning the actual binary key value. 
751  * This is done by CPDeriveKey, CPGenKey or CPImportKey, which call this function.
752  *
753  * PARAMS
754  *  hProv      [I] Handle to the provider to which the created key will belong.
755  *  aiAlgid    [I] The new key shall use the crypto algorithm idenfied by aiAlgid.
756  *  dwFlags    [I] Upper 16 bits give the key length.
757  *                 Lower 16 bits: CRYPT_EXPORTABLE, CRYPT_CREATE_SALT,
758  *                 CRYPT_NO_SALT
759  *  ppCryptKey [O] Pointer to the created key
760  *
761  * RETURNS
762  *  Success: Handle to the created key.
763  *  Failure: INVALID_HANDLE_VALUE
764  */
765 static HCRYPTKEY new_key(HCRYPTPROV hProv, ALG_ID aiAlgid, DWORD dwFlags, CRYPTKEY **ppCryptKey)
766 {
767     HCRYPTKEY hCryptKey;
768     CRYPTKEY *pCryptKey;
769     DWORD dwKeyLen = HIWORD(dwFlags);
770     const PROV_ENUMALGS_EX *peaAlgidInfo;
771 
772     *ppCryptKey = NULL;
773     
774     /* 
775      * Retrieve the CSP's capabilities for the given ALG_ID value
776      */
777     peaAlgidInfo = get_algid_info(hProv, aiAlgid);
778     if (!peaAlgidInfo) return (HCRYPTKEY)INVALID_HANDLE_VALUE;
779 
780     /*
781      * Assume the default key length, if none is specified explicitly
782      */
783     if (dwKeyLen == 0) dwKeyLen = peaAlgidInfo->dwDefaultLen;
784     
785     /*
786      * Check if the requested key length is supported by the current CSP.
787      * Adjust key length's for DES algorithms.
788      */
789     switch (aiAlgid) {
790         case CALG_DES:
791             if (dwKeyLen == RSAENH_DES_EFFECTIVE_KEYLEN) {
792                 dwKeyLen = RSAENH_DES_STORAGE_KEYLEN;
793             }
794             if (dwKeyLen != RSAENH_DES_STORAGE_KEYLEN) {
795                 SetLastError(NTE_BAD_FLAGS);
796                 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
797             }
798             break;
799 
800         case CALG_3DES_112:
801             if (dwKeyLen == RSAENH_3DES112_EFFECTIVE_KEYLEN) {
802                 dwKeyLen = RSAENH_3DES112_STORAGE_KEYLEN;
803             }
804             if (dwKeyLen != RSAENH_3DES112_STORAGE_KEYLEN) {
805                 SetLastError(NTE_BAD_FLAGS);
806                 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
807             }
808             break;
809 
810         case CALG_3DES:
811             if (dwKeyLen == RSAENH_3DES_EFFECTIVE_KEYLEN) {
812                 dwKeyLen = RSAENH_3DES_STORAGE_KEYLEN;
813             }
814             if (dwKeyLen != RSAENH_3DES_STORAGE_KEYLEN) {
815                 SetLastError(NTE_BAD_FLAGS);
816                 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
817             }
818             break;
819         
820         default:
821             if (dwKeyLen % 8 || 
822                 dwKeyLen > peaAlgidInfo->dwMaxLen || 
823                 dwKeyLen < peaAlgidInfo->dwMinLen) 
824             {
825                 SetLastError(NTE_BAD_FLAGS);
826                 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
827             }
828     }
829 
830     hCryptKey = new_object(&handle_table, sizeof(CRYPTKEY), RSAENH_MAGIC_KEY,
831                            destroy_key, (OBJECTHDR**)&pCryptKey);
832     if (hCryptKey != (HCRYPTKEY)INVALID_HANDLE_VALUE)
833     {
834         pCryptKey->aiAlgid = aiAlgid;
835         pCryptKey->hProv = hProv;
836         pCryptKey->dwModeBits = 0;
837         pCryptKey->dwPermissions = CRYPT_ENCRYPT | CRYPT_DECRYPT | CRYPT_READ | CRYPT_WRITE | 
838                                    CRYPT_MAC;
839         if (dwFlags & CRYPT_EXPORTABLE)
840             pCryptKey->dwPermissions |= CRYPT_EXPORT;
841         pCryptKey->dwKeyLen = dwKeyLen >> 3;
842         pCryptKey->dwEffectiveKeyLen = 0;
843         if ((dwFlags & CRYPT_CREATE_SALT) || (dwKeyLen == 40 && !(dwFlags & CRYPT_NO_SALT))) 
844             pCryptKey->dwSaltLen = 16 /*FIXME*/ - pCryptKey->dwKeyLen;
845         else
846             pCryptKey->dwSaltLen = 0;
847         memset(pCryptKey->abKeyValue, 0, sizeof(pCryptKey->abKeyValue));
848         memset(pCryptKey->abInitVector, 0, sizeof(pCryptKey->abInitVector));
849         init_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom);
850         init_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom);
851             
852         switch(aiAlgid)
853         {
854             case CALG_PCT1_MASTER:
855             case CALG_SSL2_MASTER:
856             case CALG_SSL3_MASTER:
857             case CALG_TLS1_MASTER:
858             case CALG_RC4:
859                 pCryptKey->dwBlockLen = 0;
860                 pCryptKey->dwMode = 0;
861                 break;
862 
863             case CALG_RC2:
864             case CALG_DES:
865             case CALG_3DES_112:
866             case CALG_3DES:
867                 pCryptKey->dwBlockLen = 8;
868                 pCryptKey->dwMode = CRYPT_MODE_CBC;
869                 break;
870 
871             case CALG_AES:
872             case CALG_AES_128:
873             case CALG_AES_192:
874             case CALG_AES_256:
875                 pCryptKey->dwBlockLen = 16;
876                 pCryptKey->dwMode = CRYPT_MODE_ECB;
877                 break;
878 
879             case CALG_RSA_KEYX:
880             case CALG_RSA_SIGN:
881                 pCryptKey->dwBlockLen = dwKeyLen >> 3;
882                 pCryptKey->dwMode = 0;
883                 break;
884         }
885 
886         *ppCryptKey = pCryptKey;
887     }
888 
889     return hCryptKey;
890 }
891 
892 /******************************************************************************
893  * map_key_spec_to_key_pair_name [Internal]
894  *
895  * Returns the name of the registry value associated with a key spec.
896  *
897  * PARAMS
898  *  dwKeySpec     [I] AT_KEYEXCHANGE or AT_SIGNATURE
899  *
900  * RETURNS
901  *  Success: Name of registry value.
902  *  Failure: NULL
903  */
904 static LPCSTR map_key_spec_to_key_pair_name(DWORD dwKeySpec)
905 {
906     LPCSTR szValueName;
907 
908     switch (dwKeySpec)
909     {
910     case AT_KEYEXCHANGE:
911         szValueName = "KeyExchangeKeyPair";
912         break;
913     case AT_SIGNATURE:
914         szValueName = "SignatureKeyPair";
915         break;
916     default:
917         WARN("invalid key spec %d\n", dwKeySpec);
918         szValueName = NULL;
919     }
920     return szValueName;
921 }
922 
923 /******************************************************************************
924  * store_key_pair [Internal]
925  *
926  * Stores a key pair to the registry
927  * 
928  * PARAMS
929  *  hCryptKey     [I] Handle to the key to be stored
930  *  hKey          [I] Registry key where the key pair is to be stored
931  *  dwKeySpec     [I] AT_KEYEXCHANGE or AT_SIGNATURE
932  *  dwFlags       [I] Flags for protecting the key
933  */
934 static void store_key_pair(HCRYPTKEY hCryptKey, HKEY hKey, DWORD dwKeySpec, DWORD dwFlags)
935 {
936     LPCSTR szValueName;
937     DATA_BLOB blobIn, blobOut;
938     CRYPTKEY *pKey;
939     DWORD dwLen;
940     BYTE *pbKey;
941 
942     if (!(szValueName = map_key_spec_to_key_pair_name(dwKeySpec)))
943         return;
944     if (lookup_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY,
945                       (OBJECTHDR**)&pKey))
946     {
947         if (crypt_export_key(pKey, 0, PRIVATEKEYBLOB, 0, TRUE, 0, &dwLen))
948         {
949             pbKey = HeapAlloc(GetProcessHeap(), 0, dwLen);
950             if (pbKey)
951             {
952                 if (crypt_export_key(pKey, 0, PRIVATEKEYBLOB, 0, TRUE, pbKey,
953                     &dwLen))
954                 {
955                     blobIn.pbData = pbKey;
956                     blobIn.cbData = dwLen;
957 
958                     if (CryptProtectData(&blobIn, NULL, NULL, NULL, NULL,
959                         dwFlags, &blobOut))
960                     {
961                         RegSetValueExA(hKey, szValueName, 0, REG_BINARY,
962                                        blobOut.pbData, blobOut.cbData);
963                         LocalFree(blobOut.pbData);
964                     }
965                 }
966                 HeapFree(GetProcessHeap(), 0, pbKey);
967             }
968         }
969     }
970 }
971 
972 /******************************************************************************
973  * map_key_spec_to_permissions_name [Internal]
974  *
975  * Returns the name of the registry value associated with the permissions for
976  * a key spec.
977  *
978  * PARAMS
979  *  dwKeySpec     [I] AT_KEYEXCHANGE or AT_SIGNATURE
980  *
981  * RETURNS
982  *  Success: Name of registry value.
983  *  Failure: NULL
984  */
985 static LPCSTR map_key_spec_to_permissions_name(DWORD dwKeySpec)
986 {
987     LPCSTR szValueName;
988 
989     switch (dwKeySpec)
990     {
991     case AT_KEYEXCHANGE:
992         szValueName = "KeyExchangePermissions";
993         break;
994     case AT_SIGNATURE:
995         szValueName = "SignaturePermissions";
996         break;
997     default:
998         WARN("invalid key spec %d\n", dwKeySpec);
999         szValueName = NULL;
1000     }
1001     return szValueName;
1002 }
1003 
1004 /******************************************************************************
1005  * store_key_permissions [Internal]
1006  *
1007  * Stores a key's permissions to the registry
1008  *
1009  * PARAMS
1010  *  hCryptKey     [I] Handle to the key whose permissions are to be stored
1011  *  hKey          [I] Registry key where the key permissions are to be stored
1012  *  dwKeySpec     [I] AT_KEYEXCHANGE or AT_SIGNATURE
1013  */
1014 static void store_key_permissions(HCRYPTKEY hCryptKey, HKEY hKey, DWORD dwKeySpec)
1015 {
1016     LPCSTR szValueName;
1017     CRYPTKEY *pKey;
1018 
1019     if (!(szValueName = map_key_spec_to_permissions_name(dwKeySpec)))
1020         return;
1021     if (lookup_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY,
1022                       (OBJECTHDR**)&pKey))
1023         RegSetValueExA(hKey, szValueName, 0, REG_DWORD,
1024                        (BYTE *)&pKey->dwPermissions,
1025                        sizeof(pKey->dwPermissions));
1026 }
1027 
1028 /******************************************************************************
1029  * create_container_key [Internal]
1030  *
1031  * Creates the registry key for a key container's persistent storage.
1032  * 
1033  * PARAMS
1034  *  pKeyContainer [I] Pointer to the key container
1035  *  sam           [I] Desired registry access
1036  *  phKey         [O] Returned key
1037  */
1038 static BOOL create_container_key(KEYCONTAINER *pKeyContainer, REGSAM sam, HKEY *phKey)
1039 {
1040     CHAR szRSABase[MAX_PATH];
1041     HKEY hRootKey;
1042 
1043     sprintf(szRSABase, RSAENH_REGKEY, pKeyContainer->szName);
1044 
1045     if (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET)
1046         hRootKey = HKEY_LOCAL_MACHINE;
1047     else
1048         hRootKey = HKEY_CURRENT_USER;
1049 
1050     /* @@ Wine registry key: HKLM\Software\Wine\Crypto\RSA */
1051     /* @@ Wine registry key: HKCU\Software\Wine\Crypto\RSA */
1052     return RegCreateKeyExA(hRootKey, szRSABase, 0, NULL,
1053                            REG_OPTION_NON_VOLATILE, sam, NULL, phKey, NULL)
1054                            == ERROR_SUCCESS;
1055 }
1056 
1057 /******************************************************************************
1058  * open_container_key [Internal]
1059  *
1060  * Opens a key container's persistent storage for reading.
1061  *
1062  * PARAMS
1063  *  pszContainerName [I] Name of the container to be opened.  May be the empty
1064  *                       string if the parent key of all containers is to be
1065  *                       opened.
1066  *  dwFlags          [I] Flags indicating which keyset to be opened.
1067  *  phKey            [O] Returned key
1068  */
1069 static BOOL open_container_key(LPCSTR pszContainerName, DWORD dwFlags, HKEY *phKey)
1070 {
1071     CHAR szRSABase[MAX_PATH];
1072     HKEY hRootKey;
1073 
1074     sprintf(szRSABase, RSAENH_REGKEY, pszContainerName);
1075 
1076     if (dwFlags & CRYPT_MACHINE_KEYSET)
1077         hRootKey = HKEY_LOCAL_MACHINE;
1078     else
1079         hRootKey = HKEY_CURRENT_USER;
1080 
1081     /* @@ Wine registry key: HKLM\Software\Wine\Crypto\RSA */
1082     /* @@ Wine registry key: HKCU\Software\Wine\Crypto\RSA */
1083     return RegOpenKeyExA(hRootKey, szRSABase, 0, KEY_READ, phKey) ==
1084                          ERROR_SUCCESS;
1085 }
1086 
1087 /******************************************************************************
1088  * delete_container_key [Internal]
1089  *
1090  * Deletes a key container's persistent storage.
1091  *
1092  * PARAMS
1093  *  pszContainerName [I] Name of the container to be opened.
1094  *  dwFlags          [I] Flags indicating which keyset to be opened.
1095  */
1096 static BOOL delete_container_key(LPCSTR pszContainerName, DWORD dwFlags)
1097 {
1098     CHAR szRegKey[MAX_PATH];
1099 
1100     if (snprintf(szRegKey, MAX_PATH, RSAENH_REGKEY, pszContainerName) >= MAX_PATH) {
1101         SetLastError(NTE_BAD_KEYSET_PARAM);
1102         return FALSE;
1103     } else {
1104         HKEY hRootKey;
1105         if (dwFlags & CRYPT_MACHINE_KEYSET)
1106             hRootKey = HKEY_LOCAL_MACHINE;
1107         else
1108             hRootKey = HKEY_CURRENT_USER;
1109         if (!RegDeleteKeyA(hRootKey, szRegKey)) {
1110             SetLastError(ERROR_SUCCESS);
1111             return TRUE;
1112         } else {
1113             SetLastError(NTE_BAD_KEYSET);
1114             return FALSE;
1115         }
1116     }
1117 }
1118 
1119 /******************************************************************************
1120  * store_key_container_keys [Internal]
1121  *
1122  * Stores key container's keys in a persistent location.
1123  *
1124  * PARAMS
1125  *  pKeyContainer [I] Pointer to the key container whose keys are to be saved
1126  */
1127 static void store_key_container_keys(KEYCONTAINER *pKeyContainer)
1128 {
1129     HKEY hKey;
1130     DWORD dwFlags;
1131 
1132     /* On WinXP, persistent keys are stored in a file located at:
1133      * $AppData$\\Microsoft\\Crypto\\RSA\\$SID$\\some_hex_string
1134      */
1135 
1136     if (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET)
1137         dwFlags = CRYPTPROTECT_LOCAL_MACHINE;
1138     else
1139         dwFlags = 0;
1140 
1141     if (create_container_key(pKeyContainer, KEY_WRITE, &hKey))
1142     {
1143         store_key_pair(pKeyContainer->hKeyExchangeKeyPair, hKey,
1144                        AT_KEYEXCHANGE, dwFlags);
1145         store_key_pair(pKeyContainer->hSignatureKeyPair, hKey,
1146                        AT_SIGNATURE, dwFlags);
1147         RegCloseKey(hKey);
1148     }
1149 }
1150 
1151 /******************************************************************************
1152  * store_key_container_permissions [Internal]
1153  *
1154  * Stores key container's key permissions in a persistent location.
1155  *
1156  * PARAMS
1157  *  pKeyContainer [I] Pointer to the key container whose key permissions are to
1158  *                    be saved
1159  */
1160 static void store_key_container_permissions(KEYCONTAINER *pKeyContainer)
1161 {
1162     HKEY hKey;
1163     DWORD dwFlags;
1164 
1165     /* On WinXP, persistent keys are stored in a file located at:
1166      * $AppData$\\Microsoft\\Crypto\\RSA\\$SID$\\some_hex_string
1167      */
1168 
1169     if (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET)
1170         dwFlags = CRYPTPROTECT_LOCAL_MACHINE;
1171     else
1172         dwFlags = 0;
1173 
1174     if (create_container_key(pKeyContainer, KEY_WRITE, &hKey))
1175     {
1176         store_key_permissions(pKeyContainer->hKeyExchangeKeyPair, hKey,
1177                        AT_KEYEXCHANGE);
1178         store_key_permissions(pKeyContainer->hSignatureKeyPair, hKey,
1179                        AT_SIGNATURE);
1180         RegCloseKey(hKey);
1181     }
1182 }
1183 
1184 /******************************************************************************
1185  * release_key_container_keys [Internal]
1186  *
1187  * Releases key container's keys.
1188  *
1189  * PARAMS
1190  *  pKeyContainer [I] Pointer to the key container whose keys are to be released.
1191  */
1192 static void release_key_container_keys(KEYCONTAINER *pKeyContainer)
1193 {
1194     release_handle(&handle_table, pKeyContainer->hKeyExchangeKeyPair,
1195                    RSAENH_MAGIC_KEY);
1196     release_handle(&handle_table, pKeyContainer->hSignatureKeyPair,
1197                    RSAENH_MAGIC_KEY);
1198 }
1199 
1200 /******************************************************************************
1201  * destroy_key_container [Internal]
1202  *
1203  * Destructor for key containers.
1204  *
1205  * PARAMS
1206  *  pObjectHdr [I] Pointer to the key container to be destroyed.
1207  */
1208 static void destroy_key_container(OBJECTHDR *pObjectHdr)
1209 {
1210     KEYCONTAINER *pKeyContainer = (KEYCONTAINER*)pObjectHdr;
1211 
1212     if (!(pKeyContainer->dwFlags & CRYPT_VERIFYCONTEXT))
1213     {
1214         store_key_container_keys(pKeyContainer);
1215         store_key_container_permissions(pKeyContainer);
1216         release_key_container_keys(pKeyContainer);
1217     }
1218     HeapFree( GetProcessHeap(), 0, pKeyContainer );
1219 }
1220 
1221 /******************************************************************************
1222  * new_key_container [Internal]
1223  *
1224  * Create a new key container. The personality (RSA Base, Strong or Enhanced CP) 
1225  * of the CSP is determined via the pVTable->pszProvName string.
1226  *
1227  * PARAMS
1228  *  pszContainerName [I] Name of the key container.
1229  *  pVTable          [I] Callback functions and context info provided by the OS
1230  *
1231  * RETURNS
1232  *  Success: Handle to the new key container.
1233  *  Failure: INVALID_HANDLE_VALUE
1234  */
1235 static HCRYPTPROV new_key_container(PCCH pszContainerName, DWORD dwFlags, const VTableProvStruc *pVTable)
1236 {
1237     KEYCONTAINER *pKeyContainer;
1238     HCRYPTPROV hKeyContainer;
1239 
1240     hKeyContainer = new_object(&handle_table, sizeof(KEYCONTAINER), RSAENH_MAGIC_CONTAINER,
1241                                destroy_key_container, (OBJECTHDR**)&pKeyContainer);
1242     if (hKeyContainer != (HCRYPTPROV)INVALID_HANDLE_VALUE)
1243     {
1244         lstrcpynA(pKeyContainer->szName, pszContainerName, MAX_PATH);
1245         pKeyContainer->dwFlags = dwFlags;
1246         pKeyContainer->dwEnumAlgsCtr = 0;
1247         pKeyContainer->hKeyExchangeKeyPair = (HCRYPTKEY)INVALID_HANDLE_VALUE;
1248         pKeyContainer->hSignatureKeyPair = (HCRYPTKEY)INVALID_HANDLE_VALUE;
1249         if (pVTable && pVTable->pszProvName) {
1250             lstrcpynA(pKeyContainer->szProvName, pVTable->pszProvName, MAX_PATH);
1251             if (!strcmp(pVTable->pszProvName, MS_DEF_PROV_A)) {
1252                 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_BASE;
1253             } else if (!strcmp(pVTable->pszProvName, MS_ENHANCED_PROV_A)) {
1254                 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_ENHANCED;
1255             } else if (!strcmp(pVTable->pszProvName, MS_DEF_RSA_SCHANNEL_PROV_A)) { 
1256                 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_SCHANNEL;
1257             } else if (!strcmp(pVTable->pszProvName, MS_ENH_RSA_AES_PROV_A)) {
1258                 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_AES;
1259             } else {
1260                 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_STRONG;
1261             }
1262         }
1263 
1264         /* The new key container has to be inserted into the CSP immediately 
1265          * after creation to be available for CPGetProvParam's PP_ENUMCONTAINERS. */
1266         if (!(dwFlags & CRYPT_VERIFYCONTEXT)) {
1267             HKEY hKey;
1268 
1269             if (create_container_key(pKeyContainer, KEY_WRITE, &hKey))
1270                 RegCloseKey(hKey);
1271         }
1272     }
1273 
1274     return hKeyContainer;
1275 }
1276 
1277 /******************************************************************************
1278  * read_key_value [Internal]
1279  *
1280  * Reads a key pair value from the registry
1281  *
1282  * PARAMS
1283  *  hKeyContainer [I] Crypt provider to use to import the key
1284  *  hKey          [I] Registry key from which to read the key pair
1285  *  dwKeySpec     [I] AT_KEYEXCHANGE or AT_SIGNATURE
1286  *  dwFlags       [I] Flags for unprotecting the key
1287  *  phCryptKey    [O] Returned key
1288  */
1289 static BOOL read_key_value(HCRYPTPROV hKeyContainer, HKEY hKey, DWORD dwKeySpec, DWORD dwFlags, HCRYPTKEY *phCryptKey)
1290 {
1291     LPCSTR szValueName;
1292     DWORD dwValueType, dwLen;
1293     BYTE *pbKey;
1294     DATA_BLOB blobIn, blobOut;
1295     BOOL ret = FALSE;
1296 
1297     if (!(szValueName = map_key_spec_to_key_pair_name(dwKeySpec)))
1298         return FALSE;
1299     if (RegQueryValueExA(hKey, szValueName, 0, &dwValueType, NULL, &dwLen) ==
1300         ERROR_SUCCESS)
1301     {
1302         pbKey = HeapAlloc(GetProcessHeap(), 0, dwLen);
1303         if (pbKey)
1304         {
1305             if (RegQueryValueExA(hKey, szValueName, 0, &dwValueType, pbKey, &dwLen) ==
1306                 ERROR_SUCCESS)
1307             {
1308                 blobIn.pbData = pbKey;
1309                 blobIn.cbData = dwLen;
1310 
1311                 if (CryptUnprotectData(&blobIn, NULL, NULL, NULL, NULL,
1312                     dwFlags, &blobOut))
1313                 {
1314                     ret = import_key(hKeyContainer, blobOut.pbData, blobOut.cbData, 0, 0,
1315                                      FALSE, phCryptKey);
1316                     LocalFree(blobOut.pbData);
1317                 }
1318             }
1319             HeapFree(GetProcessHeap(), 0, pbKey);
1320         }
1321     }
1322     if (ret)
1323     {
1324         CRYPTKEY *pKey;
1325 
1326         if (lookup_handle(&handle_table, *phCryptKey, RSAENH_MAGIC_KEY,
1327                           (OBJECTHDR**)&pKey))
1328         {
1329             if ((szValueName = map_key_spec_to_permissions_name(dwKeySpec)))
1330             {
1331                 dwLen = sizeof(pKey->dwPermissions);
1332                 RegQueryValueExA(hKey, szValueName, 0, NULL,
1333                                  (BYTE *)&pKey->dwPermissions, &dwLen);
1334             }
1335         }
1336     }
1337     return ret;
1338 }
1339 
1340 /******************************************************************************
1341  * read_key_container [Internal]
1342  *
1343  * Tries to read the persistent state of the key container (mainly the signature
1344  * and key exchange private keys) given by pszContainerName.
1345  *
1346  * PARAMS
1347  *  pszContainerName [I] Name of the key container to read from the registry
1348  *  pVTable          [I] Pointer to context data provided by the operating system
1349  *
1350  * RETURNS
1351  *  Success: Handle to the key container read from the registry
1352  *  Failure: INVALID_HANDLE_VALUE
1353  */
1354 static HCRYPTPROV read_key_container(PCHAR pszContainerName, DWORD dwFlags, const VTableProvStruc *pVTable)
1355 {
1356     HKEY hKey;
1357     KEYCONTAINER *pKeyContainer;
1358     HCRYPTPROV hKeyContainer;
1359     HCRYPTKEY hCryptKey;
1360 
1361     if (!open_container_key(pszContainerName, dwFlags, &hKey))
1362     {
1363         SetLastError(NTE_BAD_KEYSET);
1364         return (HCRYPTPROV)INVALID_HANDLE_VALUE;
1365     }
1366 
1367     hKeyContainer = new_key_container(pszContainerName, dwFlags, pVTable);
1368     if (hKeyContainer != (HCRYPTPROV)INVALID_HANDLE_VALUE)
1369     {
1370         DWORD dwProtectFlags = (dwFlags & CRYPT_MACHINE_KEYSET) ?
1371             CRYPTPROTECT_LOCAL_MACHINE : 0;
1372 
1373         if (!lookup_handle(&handle_table, hKeyContainer, RSAENH_MAGIC_CONTAINER, 
1374                            (OBJECTHDR**)&pKeyContainer))
1375             return (HCRYPTPROV)INVALID_HANDLE_VALUE;
1376     
1377         if (read_key_value(hKeyContainer, hKey, AT_KEYEXCHANGE,
1378             dwProtectFlags, &hCryptKey))
1379             pKeyContainer->hKeyExchangeKeyPair = hCryptKey;
1380         if (read_key_value(hKeyContainer, hKey, AT_SIGNATURE,
1381             dwProtectFlags, &hCryptKey))
1382             pKeyContainer->hSignatureKeyPair = hCryptKey;
1383     }
1384 
1385     return hKeyContainer;
1386 }
1387 
1388 /******************************************************************************
1389  * build_hash_signature [Internal]
1390  *
1391  * Builds a padded version of a hash to match the length of the RSA key modulus.
1392  *
1393  * PARAMS
1394  *  pbSignature [O] The padded hash object is stored here.
1395  *  dwLen       [I] Length of the pbSignature buffer.
1396  *  aiAlgid     [I] Algorithm identifier of the hash to be padded.
1397  *  abHashValue [I] The value of the hash object.
1398  *  dwHashLen   [I] Length of the hash value.
1399  *  dwFlags     [I] Selection of padding algorithm.
1400  *
1401  * RETURNS
1402  *  Success: TRUE
1403  *  Failure: FALSE (NTE_BAD_ALGID)
1404  */
1405 static BOOL build_hash_signature(BYTE *pbSignature, DWORD dwLen, ALG_ID aiAlgid, 
1406                                  CONST BYTE *abHashValue, DWORD dwHashLen, DWORD dwFlags) 
1407 {
1408     /* These prefixes are meant to be concatenated with hash values of the
1409      * respective kind to form a PKCS #7 DigestInfo. */
1410     static const struct tagOIDDescriptor {
1411         ALG_ID aiAlgid;
1412         DWORD dwLen;
1413         CONST BYTE abOID[18];
1414     } aOIDDescriptor[5] = {
1415         { CALG_MD2, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48,
1416                           0x86, 0xf7, 0x0d, 0x02, 0x02, 0x05, 0x00, 0x04, 0x10 } },
1417         { CALG_MD4, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 
1418                           0x86, 0xf7, 0x0d, 0x02, 0x04, 0x05, 0x00, 0x04, 0x10 } },
1419         { CALG_MD5, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48,
1420                           0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10 } },
1421         { CALG_SHA, 15, { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 
1422                           0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 } },
1423         { 0,        0,  { 0 } }
1424     };
1425     DWORD dwIdxOID, i, j;
1426 
1427     for (dwIdxOID = 0; aOIDDescriptor[dwIdxOID].aiAlgid; dwIdxOID++) {
1428         if (aOIDDescriptor[dwIdxOID].aiAlgid == aiAlgid) break;
1429     }
1430     
1431     if (!aOIDDescriptor[dwIdxOID].aiAlgid) {
1432         SetLastError(NTE_BAD_ALGID);
1433         return FALSE;
1434     }
1435 
1436     /* Build the padded signature */
1437     if (dwFlags & CRYPT_X931_FORMAT) {
1438         pbSignature[0] = 0x6b;
1439         for (i=1; i < dwLen - dwHashLen - 3; i++) {
1440             pbSignature[i] = 0xbb;
1441         }
1442         pbSignature[i++] = 0xba;
1443         for (j=0; j < dwHashLen; j++, i++) {
1444             pbSignature[i] = abHashValue[j];
1445         }
1446         pbSignature[i++] = 0x33;
1447         pbSignature[i++] = 0xcc;
1448     } else {
1449         pbSignature[0] = 0x00;
1450         pbSignature[1] = 0x01;
1451         if (dwFlags & CRYPT_NOHASHOID) {
1452             for (i=2; i < dwLen - 1 - dwHashLen; i++) {
1453                 pbSignature[i] = 0xff;
1454             }
1455             pbSignature[i++] = 0x00;
1456         } else {
1457             for (i=2; i < dwLen - 1 - aOIDDescriptor[dwIdxOID].dwLen - dwHashLen; i++) {
1458                 pbSignature[i] = 0xff;
1459             }
1460             pbSignature[i++] = 0x00;
1461             for (j=0; j < aOIDDescriptor[dwIdxOID].dwLen; j++) {
1462                 pbSignature[i++] = aOIDDescriptor[dwIdxOID].abOID[j];
1463             }
1464         }
1465         for (j=0; j < dwHashLen; j++) {
1466             pbSignature[i++] = abHashValue[j];
1467         }
1468     }
1469     
1470     return TRUE;
1471 }
1472 
1473 /******************************************************************************
1474  * tls1_p [Internal]
1475  *
1476  * This is an implementation of the 'P_hash' helper function for TLS1's PRF.
1477  * It is used exclusively by tls1_prf. For details see RFC 2246, chapter 5.
1478  * The pseudo random stream generated by this function is exclusive or'ed with
1479  * the data in pbBuffer.
1480  *
1481  * PARAMS
1482  *  hHMAC       [I]   HMAC object, which will be used in pseudo random generation
1483  *  pblobSeed   [I]   Seed value
1484  *  pbBuffer    [I/O] Pseudo random stream will be xor'ed to the provided data
1485  *  dwBufferLen [I]   Number of pseudo random bytes desired
1486  *
1487  * RETURNS
1488  *  Success: TRUE
1489  *  Failure: FALSE
1490  */
1491 static BOOL tls1_p(HCRYPTHASH hHMAC, CONST PCRYPT_DATA_BLOB pblobSeed, PBYTE pbBuffer, DWORD dwBufferLen)
1492 {
1493     CRYPTHASH *pHMAC;
1494     BYTE abAi[RSAENH_MAX_HASH_SIZE];
1495     DWORD i = 0;
1496 
1497     if (!lookup_handle(&handle_table, hHMAC, RSAENH_MAGIC_HASH, (OBJECTHDR**)&pHMAC)) {
1498         SetLastError(NTE_BAD_HASH);
1499         return FALSE;
1500     }
1501     
1502     /* compute A_1 = HMAC(seed) */
1503     init_hash(pHMAC);
1504     update_hash(pHMAC, pblobSeed->pbData, pblobSeed->cbData);
1505     finalize_hash(pHMAC);
1506     memcpy(abAi, pHMAC->abHashValue, pHMAC->dwHashSize);
1507 
1508     do {
1509         /* compute HMAC(A_i + seed) */
1510         init_hash(pHMAC);
1511         update_hash(pHMAC, abAi, pHMAC->dwHashSize);
1512         update_hash(pHMAC, pblobSeed->pbData, pblobSeed->cbData);
1513         finalize_hash(pHMAC);
1514 
1515         /* pseudo random stream := CONCAT_{i=1..n} ( HMAC(A_i + seed) ) */
1516         do {
1517             if (i >= dwBufferLen) break;
1518             pbBuffer[i] ^= pHMAC->abHashValue[i % pHMAC->dwHashSize];
1519             i++;
1520         } while (i % pHMAC->dwHashSize);
1521 
1522         /* compute A_{i+1} = HMAC(A_i) */
1523         init_hash(pHMAC);
1524         update_hash(pHMAC, abAi, pHMAC->dwHashSize);
1525         finalize_hash(pHMAC);
1526         memcpy(abAi, pHMAC->abHashValue, pHMAC->dwHashSize);
1527     } while (i < dwBufferLen);
1528 
1529     return TRUE;
1530 }
1531 
1532 /******************************************************************************
1533  * tls1_prf [Internal]
1534  *
1535  * TLS1 pseudo random function as specified in RFC 2246, chapter 5
1536  *
1537  * PARAMS
1538  *  hProv       [I] Key container used to compute the pseudo random stream
1539  *  hSecret     [I] Key that holds the (pre-)master secret
1540  *  pblobLabel  [I] Descriptive label
1541  *  pblobSeed   [I] Seed value
1542  *  pbBuffer    [O] Pseudo random numbers will be stored here
1543  *  dwBufferLen [I] Number of pseudo random bytes desired
1544  *
1545  * RETURNS
1546  *  Success: TRUE
1547  *  Failure: FALSE
1548  */ 
1549 static BOOL tls1_prf(HCRYPTPROV hProv, HCRYPTPROV hSecret, CONST PCRYPT_DATA_BLOB pblobLabel,
1550                      CONST PCRYPT_DATA_BLOB pblobSeed, PBYTE pbBuffer, DWORD dwBufferLen)
1551 {
1552     HMAC_INFO hmacInfo = { 0, NULL, 0, NULL, 0 };
1553     HCRYPTHASH hHMAC = (HCRYPTHASH)INVALID_HANDLE_VALUE;
1554     HCRYPTKEY hHalfSecret = (HCRYPTKEY)INVALID_HANDLE_VALUE;
1555     CRYPTKEY *pHalfSecret, *pSecret;
1556     DWORD dwHalfSecretLen;
1557     BOOL result = FALSE;
1558     CRYPT_DATA_BLOB blobLabelSeed;
1559 
1560     TRACE("(hProv=%08lx, hSecret=%08lx, pblobLabel=%p, pblobSeed=%p, pbBuffer=%p, dwBufferLen=%d)\n",
1561           hProv, hSecret, pblobLabel, pblobSeed, pbBuffer, dwBufferLen);
1562 
1563     if (!lookup_handle(&handle_table, hSecret, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pSecret)) {
1564         SetLastError(NTE_FAIL);
1565         return FALSE;
1566     }
1567 
1568     dwHalfSecretLen = (pSecret->dwKeyLen+1)/2;
1569     
1570     /* concatenation of the label and the seed */
1571     if (!concat_data_blobs(&blobLabelSeed, pblobLabel, pblobSeed)) goto exit;
1572    
1573     /* zero out the buffer, since two random streams will be xor'ed into it. */
1574     memset(pbBuffer, 0, dwBufferLen);
1575    
1576     /* build a 'fake' key, to hold the secret. CALG_SSL2_MASTER is used since it provides
1577      * the biggest range of valid key lengths. */
1578     hHalfSecret = new_key(hProv, CALG_SSL2_MASTER, MAKELONG(0,dwHalfSecretLen*8), &pHalfSecret);
1579     if (hHalfSecret == (HCRYPTKEY)INVALID_HANDLE_VALUE) goto exit;
1580 
1581     /* Derive an HMAC_MD5 hash and call the helper function. */
1582     memcpy(pHalfSecret->abKeyValue, pSecret->abKeyValue, dwHalfSecretLen);
1583     if (!RSAENH_CPCreateHash(hProv, CALG_HMAC, hHalfSecret, 0, &hHMAC)) goto exit;
1584     hmacInfo.HashAlgid = CALG_MD5;
1585     if (!RSAENH_CPSetHashParam(hProv, hHMAC, HP_HMAC_INFO, (BYTE*)&hmacInfo, 0)) goto exit;
1586     if (!tls1_p(hHMAC, &blobLabelSeed, pbBuffer, dwBufferLen)) goto exit;
1587 
1588     /* Reconfigure to HMAC_SHA hash and call helper function again. */
1589     memcpy(pHalfSecret->abKeyValue, pSecret->abKeyValue + (pSecret->dwKeyLen/2), dwHalfSecretLen);
1590     hmacInfo.HashAlgid = CALG_SHA;
1591     if (!RSAENH_CPSetHashParam(hProv, hHMAC, HP_HMAC_INFO, (BYTE*)&hmacInfo, 0)) goto exit;
1592     if (!tls1_p(hHMAC, &blobLabelSeed, pbBuffer, dwBufferLen)) goto exit;
1593     
1594     result = TRUE;
1595 exit:
1596     release_handle(&handle_table, hHalfSecret, RSAENH_MAGIC_KEY);
1597     if (hHMAC != (HCRYPTHASH)INVALID_HANDLE_VALUE) RSAENH_CPDestroyHash(hProv, hHMAC);
1598     free_data_blob(&blobLabelSeed);
1599     return result;
1600 }
1601 
1602 /******************************************************************************
1603  * pad_data [Internal]
1604  *
1605  * Helper function for data padding according to PKCS1 #2
1606  *
1607  * PARAMS
1608  *  abData      [I] The data to be padded
1609  *  dwDataLen   [I] Length of the data 
1610  *  abBuffer    [O] Padded data will be stored here
1611  *  dwBufferLen [I] Length of the buffer (also length of padded data)
1612  *  dwFlags     [I] Padding format (CRYPT_SSL2_FALLBACK)
1613  *
1614  * RETURN
1615  *  Success: TRUE
1616  *  Failure: FALSE (NTE_BAD_LEN, too much data to pad)
1617  */
1618 static BOOL pad_data(CONST BYTE *abData, DWORD dwDataLen, BYTE *abBuffer, DWORD dwBufferLen, 
1619                      DWORD dwFlags)
1620 {
1621     DWORD i;
1622     
1623     /* Ensure there is enough space for PKCS1 #2 padding */
1624     if (dwDataLen > dwBufferLen-11) {
1625         SetLastError(NTE_BAD_LEN);
1626         return FALSE;
1627     }
1628 
1629     memmove(abBuffer + dwBufferLen - dwDataLen, abData, dwDataLen);            
1630     
1631     abBuffer[0] = 0x00;
1632     abBuffer[1] = RSAENH_PKC_BLOCKTYPE; 
1633     for (i=2; i < dwBufferLen - dwDataLen - 1; i++) 
1634         do gen_rand_impl(&abBuffer[i], 1); while (!abBuffer[i]);
1635     if (dwFlags & CRYPT_SSL2_FALLBACK) 
1636         for (i-=8; i < dwBufferLen - dwDataLen - 1; i++) 
1637             abBuffer[i] = 0x03;
1638     abBuffer[i] = 0x00;
1639     
1640     return TRUE; 
1641 }
1642 
1643 /******************************************************************************
1644  * unpad_data [Internal]
1645  *
1646  * Remove the PKCS1 padding from RSA decrypted data
1647  *
1648  * PARAMS
1649  *  abData      [I]   The padded data
1650  *  dwDataLen   [I]   Length of the padded data
1651  *  abBuffer    [O]   Data without padding will be stored here
1652  *  dwBufferLen [I/O] I: Length of the buffer, O: Length of unpadded data
1653  *  dwFlags     [I]   Currently none defined
1654  *
1655  * RETURNS
1656  *  Success: TRUE
1657  *  Failure: FALSE, (NTE_BAD_DATA, no valid PKCS1 padding or buffer too small)
1658  */
1659 static BOOL unpad_data(CONST BYTE *abData, DWORD dwDataLen, BYTE *abBuffer, DWORD *dwBufferLen, 
1660                        DWORD dwFlags)
1661 {
1662     DWORD i;
1663     
1664     for (i=2; i<dwDataLen; i++)
1665         if (!abData[i])
1666             break;
1667 
1668     if ((i == dwDataLen) || (*dwBufferLen < dwDataLen - i - 1) ||
1669         (abData[0] != 0x00) || (abData[1] != RSAENH_PKC_BLOCKTYPE))
1670     {
1671         SetLastError(NTE_BAD_DATA);
1672         return FALSE;
1673     }
1674 
1675     *dwBufferLen = dwDataLen - i - 1;
1676     memmove(abBuffer, abData + i + 1, *dwBufferLen);
1677     return TRUE;
1678 }
1679 
1680 /******************************************************************************
1681  * CPAcquireContext (RSAENH.@)
1682  *
1683  * Acquire a handle to the key container specified by pszContainer
1684  *
1685  * PARAMS
1686  *  phProv       [O] Pointer to the location the acquired handle will be written to.
1687  *  pszContainer [I] Name of the desired key container. See Notes
1688  *  dwFlags      [I] Flags. See Notes.
1689  *  pVTable      [I] Pointer to a PVTableProvStruct containing callbacks.
1690  * 
1691  * RETURNS
1692  *  Success: TRUE
1693  *  Failure: FALSE
1694  *
1695  * NOTES
1696  *  If pszContainer is NULL or points to a zero length string the user's login 
1697  *  name will be used as the key container name.
1698  *
1699  *  If the CRYPT_NEW_KEYSET flag is set in dwFlags a new keyset will be created.
1700  *  If a keyset with the given name already exists, the function fails and sets
1701  *  last error to NTE_EXISTS. If CRYPT_NEW_KEYSET is not set and the specified
1702  *  key container does not exist, function fails and sets last error to 
1703  *  NTE_BAD_KEYSET.
1704  */                         
1705 BOOL WINAPI RSAENH_CPAcquireContext(HCRYPTPROV *phProv, LPSTR pszContainer,
1706                    DWORD dwFlags, PVTableProvStruc pVTable)
1707 {
1708     CHAR szKeyContainerName[MAX_PATH];
1709 
1710     TRACE("(phProv=%p, pszContainer=%s, dwFlags=%08x, pVTable=%p)\n", phProv,
1711           debugstr_a(pszContainer), dwFlags, pVTable);
1712 
1713     if (pszContainer && *pszContainer)
1714     {
1715         lstrcpynA(szKeyContainerName, pszContainer, MAX_PATH);
1716     } 
1717     else
1718     {
1719         DWORD dwLen = sizeof(szKeyContainerName);
1720         if (!GetUserNameA(szKeyContainerName, &dwLen)) return FALSE;
1721     }
1722 
1723     switch (dwFlags & (CRYPT_NEWKEYSET|CRYPT_VERIFYCONTEXT|CRYPT_DELETEKEYSET)) 
1724     {
1725         case 0:
1726             *phProv = read_key_container(szKeyContainerName, dwFlags, pVTable);
1727             break;
1728 
1729         case CRYPT_DELETEKEYSET:
1730             return delete_container_key(szKeyContainerName, dwFlags);
1731 
1732         case CRYPT_NEWKEYSET:
1733             *phProv = read_key_container(szKeyContainerName, dwFlags, pVTable);
1734             if (*phProv != (HCRYPTPROV)INVALID_HANDLE_VALUE) 
1735             {
1736                 release_handle(&handle_table, *phProv, RSAENH_MAGIC_CONTAINER);
1737                 TRACE("Can't create new keyset, already exists\n");
1738                 SetLastError(NTE_EXISTS);
1739                 return FALSE;
1740             }
1741             *phProv = new_key_container(szKeyContainerName, dwFlags, pVTable);
1742             break;
1743 
1744         case CRYPT_VERIFYCONTEXT|CRYPT_NEWKEYSET:
1745         case CRYPT_VERIFYCONTEXT:
1746             if (pszContainer && *pszContainer) {
1747                 TRACE("pszContainer should be empty\n");
1748                 SetLastError(NTE_BAD_FLAGS);
1749                 return FALSE;
1750             }
1751             *phProv = new_key_container("", dwFlags, pVTable);
1752             break;
1753             
1754         default:
1755             *phProv = (HCRYPTPROV)INVALID_HANDLE_VALUE;
1756             SetLastError(NTE_BAD_FLAGS);
1757             return FALSE;
1758     }
1759                 
1760     if (*phProv != (HCRYPTPROV)INVALID_HANDLE_VALUE) {
1761         SetLastError(ERROR_SUCCESS);
1762         return TRUE;
1763     } else {
1764         return FALSE;
1765     }
1766 }
1767 
1768 /******************************************************************************
1769  * CPCreateHash (RSAENH.@)
1770  *
1771  * CPCreateHash creates and initalizes a new hash object.
1772  *
1773  * PARAMS
1774  *  hProv   [I] Handle to the key container to which the new hash will belong.
1775  *  Algid   [I] Identifies the hash algorithm, which will be used for the hash.
1776  *  hKey    [I] Handle to a session key applied for keyed hashes.
1777  *  dwFlags [I] Currently no flags defined. Must be zero.
1778  *  phHash  [O] Points to the location where a handle to the new hash will be stored.
1779  *
1780  * RETURNS
1781  *  Success: TRUE
1782  *  Failure: FALSE
1783  *
1784  * NOTES
1785  *  hKey is a handle to a session key applied in keyed hashes like MAC and HMAC.
1786  *  If a normal hash object is to be created (like e.g. MD2 or SHA1) hKey must be zero.
1787  */
1788 BOOL WINAPI RSAENH_CPCreateHash(HCRYPTPROV hProv, ALG_ID Algid, HCRYPTKEY hKey, DWORD dwFlags, 
1789                                 HCRYPTHASH *phHash)
1790 {
1791     CRYPTKEY *pCryptKey;
1792     CRYPTHASH *pCryptHash;
1793     const PROV_ENUMALGS_EX *peaAlgidInfo;
1794         
1795     TRACE("(hProv=%08lx, Algid=%08x, hKey=%08lx, dwFlags=%08x, phHash=%p)\n", hProv, Algid, hKey,
1796           dwFlags, phHash);
1797 
1798     peaAlgidInfo = get_algid_info(hProv, Algid);
1799     if (!peaAlgidInfo) return FALSE;
1800 
1801     if (dwFlags)
1802     {
1803         SetLastError(NTE_BAD_FLAGS);
1804         return FALSE;
1805     }
1806 
1807     if (Algid == CALG_MAC || Algid == CALG_HMAC || Algid == CALG_SCHANNEL_MASTER_HASH || 
1808         Algid == CALG_TLS1PRF) 
1809     {
1810         if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey)) {
1811             SetLastError(NTE_BAD_KEY);
1812             return FALSE;
1813         }
1814 
1815         if ((Algid == CALG_MAC) && (GET_ALG_TYPE(pCryptKey->aiAlgid) != ALG_TYPE_BLOCK)) {
1816             SetLastError(NTE_BAD_KEY);
1817             return FALSE;
1818         }
1819 
1820         if ((Algid == CALG_SCHANNEL_MASTER_HASH || Algid == CALG_TLS1PRF) && 
1821             (pCryptKey->aiAlgid != CALG_TLS1_MASTER)) 
1822         {
1823             SetLastError(NTE_BAD_KEY);
1824             return FALSE;
1825         }
1826 
1827         if ((Algid == CALG_TLS1PRF) && (pCryptKey->dwState != RSAENH_KEYSTATE_MASTERKEY)) {
1828             SetLastError(NTE_BAD_KEY_STATE);
1829             return FALSE;
1830         }
1831     }
1832 
1833     *phHash = new_object(&handle_table, sizeof(CRYPTHASH), RSAENH_MAGIC_HASH,
1834                          destroy_hash, (OBJECTHDR**)&pCryptHash);
1835     if (!pCryptHash) return FALSE;
1836 
1837     pCryptHash->aiAlgid = Algid;
1838     pCryptHash->hKey = hKey;
1839     pCryptHash->hProv = hProv;
1840     pCryptHash->dwState = RSAENH_HASHSTATE_HASHING;
1841     pCryptHash->pHMACInfo = NULL;
1842     pCryptHash->dwHashSize = peaAlgidInfo->dwDefaultLen >> 3;
1843     init_data_blob(&pCryptHash->tpPRFParams.blobLabel);
1844     init_data_blob(&pCryptHash->tpPRFParams.blobSeed);
1845 
1846     if (Algid == CALG_SCHANNEL_MASTER_HASH) {
1847         static const char keyex[] = "key expansion";
1848         BYTE key_expansion[sizeof keyex];
1849         CRYPT_DATA_BLOB blobRandom, blobKeyExpansion = { 13, key_expansion };
1850 
1851         memcpy( key_expansion, keyex, sizeof keyex );
1852         
1853         if (pCryptKey->dwState != RSAENH_KEYSTATE_MASTERKEY) {
1854             static const char msec[] = "master secret";
1855             BYTE master_secret[sizeof msec];
1856             CRYPT_DATA_BLOB blobLabel = { 13, master_secret };
1857             BYTE abKeyValue[48];
1858 
1859             memcpy( master_secret, msec, sizeof msec );
1860     
1861             /* See RFC 2246, chapter 8.1 */
1862             if (!concat_data_blobs(&blobRandom, 
1863                                    &pCryptKey->siSChannelInfo.blobClientRandom, 
1864                                    &pCryptKey->siSChannelInfo.blobServerRandom))
1865             {
1866                 return FALSE;
1867             }
1868             tls1_prf(hProv, hKey, &blobLabel, &blobRandom, abKeyValue, 48);
1869             pCryptKey->dwState = RSAENH_KEYSTATE_MASTERKEY; 
1870             memcpy(pCryptKey->abKeyValue, abKeyValue, 48);
1871             free_data_blob(&blobRandom);
1872         }
1873 
1874         /* See RFC 2246, chapter 6.3 */
1875         if (!concat_data_blobs(&blobRandom, 
1876                                   &pCryptKey->siSChannelInfo.blobServerRandom, 
1877                                   &pCryptKey->siSChannelInfo.blobClientRandom))
1878         {
1879             return FALSE;
1880         }
1881         tls1_prf(hProv, hKey, &blobKeyExpansion, &blobRandom, pCryptHash->abHashValue, 
1882                  RSAENH_MAX_HASH_SIZE);
1883         free_data_blob(&blobRandom);
1884     }
1885 
1886     return init_hash(pCryptHash);
1887 }
1888 
1889 /******************************************************************************
1890  * CPDestroyHash (RSAENH.@)
1891  * 
1892  * Releases the handle to a hash object. The object is destroyed if it's reference
1893  * count reaches zero.
1894  *
1895  * PARAMS
1896  *  hProv [I] Handle to the key container to which the hash object belongs.
1897  *  hHash [I] Handle to the hash object to be released.
1898  *
1899  * RETURNS
1900  *  Success: TRUE
1901  *  Failure: FALSE 
1902  */
1903 BOOL WINAPI RSAENH_CPDestroyHash(HCRYPTPROV hProv, HCRYPTHASH hHash)
1904 {
1905     TRACE("(hProv=%08lx, hHash=%08lx)\n", hProv, hHash);
1906      
1907     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
1908     {
1909         SetLastError(NTE_BAD_UID);
1910         return FALSE;
1911     }
1912         
1913     if (!release_handle(&handle_table, hHash, RSAENH_MAGIC_HASH)) 
1914     {
1915         SetLastError(NTE_BAD_HASH);
1916         return FALSE;
1917     }
1918     
1919     return TRUE;
1920 }
1921 
1922 /******************************************************************************
1923  * CPDestroyKey (RSAENH.@)
1924  *
1925  * Releases the handle to a key object. The object is destroyed if it's reference
1926  * count reaches zero.
1927  *
1928  * PARAMS
1929  *  hProv [I] Handle to the key container to which the key object belongs.
1930  *  hKey  [I] Handle to the key object to be released.
1931  *
1932  * RETURNS
1933  *  Success: TRUE
1934  *  Failure: FALSE
1935  */
1936 BOOL WINAPI RSAENH_CPDestroyKey(HCRYPTPROV hProv, HCRYPTKEY hKey)
1937 {
1938     TRACE("(hProv=%08lx, hKey=%08lx)\n", hProv, hKey);
1939         
1940     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
1941     {
1942         SetLastError(NTE_BAD_UID);
1943         return FALSE;
1944     }
1945         
1946     if (!release_handle(&handle_table, hKey, RSAENH_MAGIC_KEY)) 
1947     {
1948         SetLastError(NTE_BAD_KEY);
1949         return FALSE;
1950     }
1951     
1952     return TRUE;
1953 }
1954 
1955 /******************************************************************************
1956  * CPDuplicateHash (RSAENH.@)
1957  *
1958  * Clones a hash object including it's current state.
1959  *
1960  * PARAMS
1961  *  hUID        [I] Handle to the key container the hash belongs to.
1962  *  hHash       [I] Handle to the hash object to be cloned.
1963  *  pdwReserved [I] Reserved. Must be NULL.
1964  *  dwFlags     [I] No flags are currently defined. Must be 0.
1965  *  phHash      [O] Handle to the cloned hash object.
1966  *
1967  * RETURNS
1968  *  Success: TRUE.
1969  *  Failure: FALSE.
1970  */
1971 BOOL WINAPI RSAENH_CPDuplicateHash(HCRYPTPROV hUID, HCRYPTHASH hHash, DWORD *pdwReserved, 
1972                                    DWORD dwFlags, HCRYPTHASH *phHash)
1973 {
1974     CRYPTHASH *pSrcHash, *pDestHash;
1975     
1976     TRACE("(hUID=%08lx, hHash=%08lx, pdwReserved=%p, dwFlags=%08x, phHash=%p)\n", hUID, hHash,
1977            pdwReserved, dwFlags, phHash);
1978 
1979     if (!is_valid_handle(&handle_table, hUID, RSAENH_MAGIC_CONTAINER))
1980     {
1981         SetLastError(NTE_BAD_UID);
1982         return FALSE;
1983     }
1984 
1985     if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH, (OBJECTHDR**)&pSrcHash))
1986     {
1987         SetLastError(NTE_BAD_HASH);
1988         return FALSE;
1989     }
1990 
1991     if (!phHash || pdwReserved || dwFlags) 
1992     {
1993         SetLastError(ERROR_INVALID_PARAMETER);
1994         return FALSE;
1995     }
1996 
1997     *phHash = new_object(&handle_table, sizeof(CRYPTHASH), RSAENH_MAGIC_HASH,
1998                          destroy_hash, (OBJECTHDR**)&pDestHash);
1999     if (*phHash != (HCRYPTHASH)INVALID_HANDLE_VALUE)
2000     {
2001         *pDestHash = *pSrcHash;
2002         duplicate_hash_impl(pSrcHash->aiAlgid, &pSrcHash->context, &pDestHash->context);
2003         copy_hmac_info(&pDestHash->pHMACInfo, pSrcHash->pHMACInfo);
2004         copy_data_blob(&pDestHash->tpPRFParams.blobLabel, &pSrcHash->tpPRFParams.blobLabel);
2005         copy_data_blob(&pDestHash->tpPRFParams.blobSeed, &pSrcHash->tpPRFParams.blobSeed);
2006     }
2007 
2008     return *phHash != (HCRYPTHASH)INVALID_HANDLE_VALUE;
2009 }
2010 
2011 /******************************************************************************
2012  * CPDuplicateKey (RSAENH.@)
2013  *
2014  * Clones a key object including it's current state.
2015  *
2016  * PARAMS
2017  *  hUID        [I] Handle to the key container the hash belongs to.
2018  *  hKey        [I] Handle to the key object to be cloned.
2019  *  pdwReserved [I] Reserved. Must be NULL.
2020  *  dwFlags     [I] No flags are currently defined. Must be 0.
2021  *  phHash      [O] Handle to the cloned key object.
2022  *
2023  * RETURNS
2024  *  Success: TRUE.
2025  *  Failure: FALSE.
2026  */
2027 BOOL WINAPI RSAENH_CPDuplicateKey(HCRYPTPROV hUID, HCRYPTKEY hKey, DWORD *pdwReserved, 
2028                                   DWORD dwFlags, HCRYPTKEY *phKey)
2029 {
2030     CRYPTKEY *pSrcKey, *pDestKey;
2031     
2032     TRACE("(hUID=%08lx, hKey=%08lx, pdwReserved=%p, dwFlags=%08x, phKey=%p)\n", hUID, hKey,
2033           pdwReserved, dwFlags, phKey);
2034 
2035     if (!is_valid_handle(&handle_table, hUID, RSAENH_MAGIC_CONTAINER))
2036     {
2037         SetLastError(NTE_BAD_UID);
2038         return FALSE;
2039     }
2040 
2041     if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pSrcKey))
2042     {
2043         SetLastError(NTE_BAD_KEY);
2044         return FALSE;
2045     }
2046 
2047     if (!phKey || pdwReserved || dwFlags) 
2048     {
2049         SetLastError(ERROR_INVALID_PARAMETER);
2050         return FALSE;
2051     }
2052 
2053     *phKey = new_object(&handle_table, sizeof(CRYPTKEY), RSAENH_MAGIC_KEY, destroy_key,
2054                         (OBJECTHDR**)&pDestKey);
2055     if (*phKey != (HCRYPTKEY)INVALID_HANDLE_VALUE)
2056     {
2057         *pDestKey = *pSrcKey;
2058         copy_data_blob(&pDestKey->siSChannelInfo.blobServerRandom,
2059                        &pSrcKey->siSChannelInfo.blobServerRandom);
2060         copy_data_blob(&pDestKey->siSChannelInfo.blobClientRandom, 
2061                        &pSrcKey->siSChannelInfo.blobClientRandom);
2062         duplicate_key_impl(pSrcKey->aiAlgid, &pSrcKey->context, &pDestKey->context);
2063         return TRUE;
2064     }
2065     else
2066     {
2067         return FALSE;
2068     }
2069 }
2070 
2071 /******************************************************************************
2072  * CPEncrypt (RSAENH.@)
2073  *
2074  * Encrypt data.
2075  *
2076  * PARAMS
2077  *  hProv      [I]   The key container hKey and hHash belong to.
2078  *  hKey       [I]   The key used to encrypt the data.
2079  *  hHash      [I]   An optional hash object for parallel hashing. See notes.
2080  *  Final      [I]   Indicates if this is the last block of data to encrypt.
2081  *  dwFlags    [I]   Currently no flags defined. Must be zero.
2082  *  pbData     [I/O] Pointer to the data to encrypt. Encrypted data will also be stored there. 
2083  *  pdwDataLen [I/O] I: Length of data to encrypt, O: Length of encrypted data.
2084  *  dwBufLen   [I]   Size of the buffer at pbData.
2085  *
2086  * RETURNS
2087  *  Success: TRUE.
2088  *  Failure: FALSE.
2089  *
2090  * NOTES
2091  *  If a hash object handle is provided in hHash, it will be updated with the plaintext. 
2092  *  This is useful for message signatures.
2093  *
2094  *  This function uses the standard WINAPI protocol for querying data of dynamic length. 
2095  */
2096 BOOL WINAPI RSAENH_CPEncrypt(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final, 
2097                              DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen, DWORD dwBufLen)
2098 {
2099     CRYPTKEY *pCryptKey;
2100     BYTE *in, out[RSAENH_MAX_BLOCK_SIZE], o[RSAENH_MAX_BLOCK_SIZE];
2101     DWORD dwEncryptedLen, i, j, k;
2102         
2103     TRACE("(hProv=%08lx, hKey=%08lx, hHash=%08lx, Final=%d, dwFlags=%08x, pbData=%p, "
2104           "pdwDataLen=%p, dwBufLen=%d)\n", hProv, hKey, hHash, Final, dwFlags, pbData, pdwDataLen,
2105           dwBufLen);
2106     
2107     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2108     {
2109         SetLastError(NTE_BAD_UID);
2110         return FALSE;
2111     }
2112 
2113     if (dwFlags)
2114     {
2115         SetLastError(NTE_BAD_FLAGS);
2116         return FALSE;
2117     }
2118 
2119     if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2120     {
2121         SetLastError(NTE_BAD_KEY);
2122         return FALSE;
2123     }
2124 
2125     if (pCryptKey->dwState == RSAENH_KEYSTATE_IDLE) 
2126         pCryptKey->dwState = RSAENH_KEYSTATE_ENCRYPTING;
2127 
2128     if (pCryptKey->dwState != RSAENH_KEYSTATE_ENCRYPTING) 
2129     {
2130         SetLastError(NTE_BAD_DATA);
2131         return FALSE;
2132     }
2133 
2134     if (is_valid_handle(&handle_table, hHash, RSAENH_MAGIC_HASH)) {
2135         if (!RSAENH_CPHashData(hProv, hHash, pbData, *pdwDataLen, 0)) return FALSE;
2136     }
2137     
2138     if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_BLOCK) {
2139         if (!Final && (*pdwDataLen % pCryptKey->dwBlockLen)) {
2140             SetLastError(NTE_BAD_DATA);
2141             return FALSE;
2142         }
2143 
2144         dwEncryptedLen = (*pdwDataLen/pCryptKey->dwBlockLen+(Final?1:0))*pCryptKey->dwBlockLen;
2145 
2146         if (pbData == NULL) {
2147             *pdwDataLen = dwEncryptedLen;
2148             return TRUE;
2149         }
2150         else if (dwEncryptedLen > dwBufLen) {
2151             *pdwDataLen = dwEncryptedLen;
2152             SetLastError(ERROR_MORE_DATA);
2153             return FALSE;
2154         }
2155 
2156         /* Pad final block with length bytes */
2157         for (i=*pdwDataLen; i<dwEncryptedLen; i++) pbData[i] = dwEncryptedLen - *pdwDataLen;
2158         *pdwDataLen = dwEncryptedLen;
2159 
2160         for (i=0, in=pbData; i<*pdwDataLen; i+=pCryptKey->dwBlockLen, in+=pCryptKey->dwBlockLen) {
2161             switch (pCryptKey->dwMode) {
2162                 case CRYPT_MODE_ECB:
2163                     encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out, 
2164                                        RSAENH_ENCRYPT);
2165                     break;
2166                 
2167                 case CRYPT_MODE_CBC:
2168                     for (j=0; j<pCryptKey->dwBlockLen; j++) in[j] ^= pCryptKey->abChainVector[j];
2169                     encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out, 
2170                                        RSAENH_ENCRYPT);
2171                     memcpy(pCryptKey->abChainVector, out, pCryptKey->dwBlockLen);
2172                     break;
2173 
2174                 case CRYPT_MODE_CFB:
2175                     for (j=0; j<pCryptKey->dwBlockLen; j++) {
2176                         encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, 
2177                                            pCryptKey->abChainVector, o, RSAENH_ENCRYPT);
2178                         out[j] = in[j] ^ o[0];
2179                         for (k=0; k<pCryptKey->dwBlockLen-1; k++) 
2180                             pCryptKey->abChainVector[k] = pCryptKey->abChainVector[k+1];
2181                         pCryptKey->abChainVector[k] = out[j];
2182                     }
2183                     break;
2184                     
2185                 default:
2186                     SetLastError(NTE_BAD_ALGID);
2187                     return FALSE;
2188             }
2189             memcpy(in, out, pCryptKey->dwBlockLen); 
2190         }
2191     } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_STREAM) {
2192         if (pbData == NULL) {
2193             *pdwDataLen = dwBufLen;
2194             return TRUE;
2195         }
2196         encrypt_stream_impl(pCryptKey->aiAlgid, &pCryptKey->context, pbData, *pdwDataLen);
2197     } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_RSA) {
2198         if (pCryptKey->aiAlgid == CALG_RSA_SIGN) {
2199             SetLastError(NTE_BAD_KEY);
2200             return FALSE;
2201         }
2202         if (!pbData) {
2203             *pdwDataLen = pCryptKey->dwBlockLen;
2204             return TRUE;
2205         }
2206         if (dwBufLen < pCryptKey->dwBlockLen) {
2207             SetLastError(ERROR_MORE_DATA);
2208             return FALSE;
2209         }
2210         if (!pad_data(pbData, *pdwDataLen, pbData, pCryptKey->dwBlockLen, dwFlags)) return FALSE;
2211         encrypt_block_impl(pCryptKey->aiAlgid, PK_PUBLIC, &pCryptKey->context, pbData, pbData, RSAENH_ENCRYPT);
2212         *pdwDataLen = pCryptKey->dwBlockLen;
2213         Final = TRUE;
2214     } else {
2215         SetLastError(NTE_BAD_TYPE);
2216         return FALSE;
2217     }
2218 
2219     if (Final) setup_key(pCryptKey);
2220 
2221     return TRUE;
2222 }
2223 
2224 /******************************************************************************
2225  * CPDecrypt (RSAENH.@)
2226  *
2227  * Decrypt data.
2228  *
2229  * PARAMS
2230  *  hProv      [I]   The key container hKey and hHash belong to.
2231  *  hKey       [I]   The key used to decrypt the data.
2232  *  hHash      [I]   An optional hash object for parallel hashing. See notes.
2233  *  Final      [I]   Indicates if this is the last block of data to decrypt.
2234  *  dwFlags    [I]   Currently no flags defined. Must be zero.
2235  *  pbData     [I/O] Pointer to the data to decrypt. Plaintext will also be stored there. 
2236  *  pdwDataLen [I/O] I: Length of ciphertext, O: Length of plaintext.
2237  *
2238  * RETURNS
2239  *  Success: TRUE.
2240  *  Failure: FALSE.
2241  *
2242  * NOTES
2243  *  If a hash object handle is provided in hHash, it will be updated with the plaintext. 
2244  *  This is useful for message signatures.
2245  *
2246  *  This function uses the standard WINAPI protocol for querying data of dynamic length. 
2247  */
2248 BOOL WINAPI RSAENH_CPDecrypt(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final, 
2249                              DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2250 {
2251     CRYPTKEY *pCryptKey;
2252     BYTE *in, out[RSAENH_MAX_BLOCK_SIZE], o[RSAENH_MAX_BLOCK_SIZE];
2253     DWORD i, j, k;
2254     DWORD dwMax;
2255 
2256     TRACE("(hProv=%08lx, hKey=%08lx, hHash=%08lx, Final=%d, dwFlags=%08x, pbData=%p, "
2257           "pdwDataLen=%p)\n", hProv, hKey, hHash, Final, dwFlags, pbData, pdwDataLen);
2258     
2259     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2260     {
2261         SetLastError(NTE_BAD_UID);
2262         return FALSE;
2263     }
2264 
2265     if (dwFlags)
2266     {
2267         SetLastError(NTE_BAD_FLAGS);
2268         return FALSE;
2269     }
2270 
2271     if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2272     {
2273         SetLastError(NTE_BAD_KEY);
2274         return FALSE;
2275     }
2276 
2277     if (pCryptKey->dwState == RSAENH_KEYSTATE_IDLE) 
2278         pCryptKey->dwState = RSAENH_KEYSTATE_ENCRYPTING;
2279 
2280     if (pCryptKey->dwState != RSAENH_KEYSTATE_ENCRYPTING)
2281     {
2282         SetLastError(NTE_BAD_DATA);
2283         return FALSE;
2284     }
2285 
2286     dwMax=*pdwDataLen;
2287 
2288     if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_BLOCK) {
2289         for (i=0, in=pbData; i<*pdwDataLen; i+=pCryptKey->dwBlockLen, in+=pCryptKey->dwBlockLen) {
2290             switch (pCryptKey->dwMode) {
2291                 case CRYPT_MODE_ECB:
2292                     encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out, 
2293                                        RSAENH_DECRYPT);
2294                     break;
2295                 
2296                 case CRYPT_MODE_CBC:
2297                     encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out, 
2298                                        RSAENH_DECRYPT);
2299                     for (j=0; j<pCryptKey->dwBlockLen; j++) out[j] ^= pCryptKey->abChainVector[j];
2300                     memcpy(pCryptKey->abChainVector, in, pCryptKey->dwBlockLen);
2301                     break;
2302 
2303                 case CRYPT_MODE_CFB:
2304                     for (j=0; j<pCryptKey->dwBlockLen; j++) {
2305                         encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, 
2306                                            pCryptKey->abChainVector, o, RSAENH_ENCRYPT);
2307                         out[j] = in[j] ^ o[0];
2308                         for (k=0; k<pCryptKey->dwBlockLen-1; k++) 
2309                             pCryptKey->abChainVector[k] = pCryptKey->abChainVector[k+1];
2310                         pCryptKey->abChainVector[k] = in[j];
2311                     }
2312                     break;
2313                     
2314                 default:
2315                     SetLastError(NTE_BAD_ALGID);
2316                     return FALSE;
2317             }
2318             memcpy(in, out, pCryptKey->dwBlockLen);
2319         }
2320         if (Final) {
2321             if (pbData[*pdwDataLen-1] &&
2322              pbData[*pdwDataLen-1] <= pCryptKey->dwBlockLen &&
2323              pbData[*pdwDataLen-1] < *pdwDataLen) {
2324                 BOOL padOkay = TRUE;
2325 
2326                 /* check that every bad byte has the same value */
2327                 for (i = 1; padOkay && i < pbData[*pdwDataLen-1]; i++)
2328                     if (pbData[*pdwDataLen - i - 1] != pbData[*pdwDataLen - 1])
2329                         padOkay = FALSE;
2330                 if (padOkay)
2331                     *pdwDataLen -= pbData[*pdwDataLen-1];
2332                 else {
2333                     SetLastError(NTE_BAD_DATA);
2334                     return FALSE;
2335                 }
2336             }
2337             else {
2338                 SetLastError(NTE_BAD_DATA);
2339                 return FALSE;
2340             }
2341         }
2342 
2343     } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_STREAM) {
2344         encrypt_stream_impl(pCryptKey->aiAlgid, &pCryptKey->context, pbData, *pdwDataLen);
2345     } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_RSA) {
2346         if (pCryptKey->aiAlgid == CALG_RSA_SIGN) {
2347             SetLastError(NTE_BAD_KEY);
2348             return FALSE;
2349         }
2350         encrypt_block_impl(pCryptKey->aiAlgid, PK_PRIVATE, &pCryptKey->context, pbData, pbData, RSAENH_DECRYPT);
2351         if (!unpad_data(pbData, pCryptKey->dwBlockLen, pbData, pdwDataLen, dwFlags)) return FALSE;
2352         Final = TRUE;
2353     } else {
2354         SetLastError(NTE_BAD_TYPE);
2355         return FALSE;
2356     } 
2357     
2358     if (Final) setup_key(pCryptKey);
2359 
2360     if (is_valid_handle(&handle_table, hHash, RSAENH_MAGIC_HASH)) {
2361         if (*pdwDataLen>dwMax ||
2362             !RSAENH_CPHashData(hProv, hHash, pbData, *pdwDataLen, 0)) return FALSE;
2363     }
2364     
2365     return TRUE;
2366 }
2367 
2368 static BOOL crypt_export_simple(CRYPTKEY *pCryptKey, CRYPTKEY *pPubKey,
2369     DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2370 {
2371     BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2372     ALG_ID *pAlgid = (ALG_ID*)(pBlobHeader+1);
2373     DWORD dwDataLen;
2374 
2375     if (!(GET_ALG_CLASS(pCryptKey->aiAlgid)&(ALG_CLASS_DATA_ENCRYPT|ALG_CLASS_MSG_ENCRYPT))) {
2376         SetLastError(NTE_BAD_KEY); /* FIXME: error code? */
2377         return FALSE;
2378     }
2379 
2380     dwDataLen = sizeof(BLOBHEADER) + sizeof(ALG_ID) + pPubKey->dwBlockLen;
2381     if (pbData) {
2382         if (*pdwDataLen < dwDataLen) {
2383             SetLastError(ERROR_MORE_DATA);
2384             *pdwDataLen = dwDataLen;
2385             return FALSE;
2386         }
2387 
2388         pBlobHeader->bType = SIMPLEBLOB;
2389         pBlobHeader->bVersion = CUR_BLOB_VERSION;
2390         pBlobHeader->reserved = 0;
2391         pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2392 
2393         *pAlgid = pPubKey->aiAlgid;
2394 
2395         if (!pad_data(pCryptKey->abKeyValue, pCryptKey->dwKeyLen, (BYTE*)(pAlgid+1),
2396                       pPubKey->dwBlockLen, dwFlags))
2397         {
2398             return FALSE;
2399         }
2400 
2401         encrypt_block_impl(pPubKey->aiAlgid, PK_PUBLIC, &pPubKey->context, (BYTE*)(pAlgid+1),
2402                            (BYTE*)(pAlgid+1), RSAENH_ENCRYPT);
2403     }
2404     *pdwDataLen = dwDataLen;
2405     return TRUE;
2406 }
2407 
2408 static BOOL crypt_export_public_key(CRYPTKEY *pCryptKey, BYTE *pbData,
2409     DWORD *pdwDataLen)
2410 {
2411     BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2412     RSAPUBKEY *pRSAPubKey = (RSAPUBKEY*)(pBlobHeader+1);
2413     DWORD dwDataLen;
2414 
2415     if ((pCryptKey->aiAlgid != CALG_RSA_KEYX) && (pCryptKey->aiAlgid != CALG_RSA_SIGN)) {
2416         SetLastError(NTE_BAD_KEY);
2417         return FALSE;
2418     }
2419 
2420     dwDataLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) + pCryptKey->dwKeyLen;
2421     if (pbData) {
2422         if (*pdwDataLen < dwDataLen) {
2423             SetLastError(ERROR_MORE_DATA);
2424             *pdwDataLen = dwDataLen;
2425             return FALSE;
2426         }
2427 
2428         pBlobHeader->bType = PUBLICKEYBLOB;
2429         pBlobHeader->bVersion = CUR_BLOB_VERSION;
2430         pBlobHeader->reserved = 0;
2431         pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2432 
2433         pRSAPubKey->magic = RSAENH_MAGIC_RSA1;
2434         pRSAPubKey->bitlen = pCryptKey->dwKeyLen << 3;
2435 
2436         export_public_key_impl((BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2437                                pCryptKey->dwKeyLen, &pRSAPubKey->pubexp);
2438     }
2439     *pdwDataLen = dwDataLen;
2440     return TRUE;
2441 }
2442 
2443 static BOOL crypt_export_private_key(CRYPTKEY *pCryptKey, BOOL force,
2444     BYTE *pbData, DWORD *pdwDataLen)
2445 {
2446     BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2447     RSAPUBKEY *pRSAPubKey = (RSAPUBKEY*)(pBlobHeader+1);
2448     DWORD dwDataLen;
2449 
2450     if ((pCryptKey->aiAlgid != CALG_RSA_KEYX) && (pCryptKey->aiAlgid != CALG_RSA_SIGN)) {
2451         SetLastError(NTE_BAD_KEY);
2452         return FALSE;
2453     }
2454     if (!force && !(pCryptKey->dwPermissions & CRYPT_EXPORT))
2455     {
2456         SetLastError(NTE_BAD_KEY_STATE);
2457         return FALSE;
2458     }
2459 
2460     dwDataLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) +
2461                 2 * pCryptKey->dwKeyLen + 5 * ((pCryptKey->dwKeyLen + 1) >> 1);
2462     if (pbData) {
2463         if (*pdwDataLen < dwDataLen) {
2464             SetLastError(ERROR_MORE_DATA);
2465             *pdwDataLen = dwDataLen;
2466             return FALSE;
2467         }
2468 
2469         pBlobHeader->bType = PRIVATEKEYBLOB;
2470         pBlobHeader->bVersion = CUR_BLOB_VERSION;
2471         pBlobHeader->reserved = 0;
2472         pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2473 
2474         pRSAPubKey->magic = RSAENH_MAGIC_RSA2;
2475         pRSAPubKey->bitlen = pCryptKey->dwKeyLen << 3;
2476 
2477         export_private_key_impl((BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2478                                 pCryptKey->dwKeyLen, &pRSAPubKey->pubexp);
2479     }
2480     *pdwDataLen = dwDataLen;
2481     return TRUE;
2482 }
2483 
2484 static BOOL crypt_export_plaintext_key(CRYPTKEY *pCryptKey, BYTE *pbData,
2485     DWORD *pdwDataLen)
2486 {
2487     BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2488     DWORD *pKeyLen = (DWORD*)(pBlobHeader+1);
2489     BYTE *pbKey = (BYTE*)(pKeyLen+1);
2490     DWORD dwDataLen;
2491 
2492     dwDataLen = sizeof(BLOBHEADER) + sizeof(DWORD) + pCryptKey->dwKeyLen;
2493     if (pbData) {
2494         if (*pdwDataLen < dwDataLen) {
2495             SetLastError(ERROR_MORE_DATA);
2496             *pdwDataLen = dwDataLen;
2497             return FALSE;
2498         }
2499 
2500         pBlobHeader->bType = PLAINTEXTKEYBLOB;
2501         pBlobHeader->bVersion = CUR_BLOB_VERSION;
2502         pBlobHeader->reserved = 0;
2503         pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2504 
2505         *pKeyLen = pCryptKey->dwKeyLen;
2506         memcpy(pbKey, &pCryptKey->abKeyValue, pCryptKey->dwKeyLen);
2507     }
2508     *pdwDataLen = dwDataLen;
2509     return TRUE;
2510 }
2511 /******************************************************************************
2512  * crypt_export_key [Internal]
2513  *
2514  * Export a key into a binary large object (BLOB).  Called by CPExportKey and
2515  * by store_key_pair.
2516  *
2517  * PARAMS
2518  *  pCryptKey  [I]   Key to be exported.
2519  *  hPubKey    [I]   Key used to encrypt sensitive BLOB data.
2520  *  dwBlobType [I]   SIMPLEBLOB, PUBLICKEYBLOB or PRIVATEKEYBLOB.
2521  *  dwFlags    [I]   Currently none defined.
2522  *  force      [I]   If TRUE, the key is written no matter what the key's
2523  *                   permissions are.  Otherwise the key's permissions are
2524  *                   checked before exporting.
2525  *  pbData     [O]   Pointer to a buffer where the BLOB will be written to.
2526  *  pdwDataLen [I/O] I: Size of buffer at pbData, O: Size of BLOB
2527  *
2528  * RETURNS
2529  *  Success: TRUE.
2530  *  Failure: FALSE.
2531  */
2532 static BOOL crypt_export_key(CRYPTKEY *pCryptKey, HCRYPTKEY hPubKey,
2533                              DWORD dwBlobType, DWORD dwFlags, BOOL force,
2534                              BYTE *pbData, DWORD *pdwDataLen)
2535 {
2536     CRYPTKEY *pPubKey;
2537     
2538     if (dwFlags & CRYPT_SSL2_FALLBACK) {
2539         if (pCryptKey->aiAlgid != CALG_SSL2_MASTER) {
2540             SetLastError(NTE_BAD_KEY);
2541             return FALSE;
2542         }
2543     }
2544     
2545     switch ((BYTE)dwBlobType)
2546     {
2547         case SIMPLEBLOB:
2548             if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pPubKey)){
2549                 SetLastError(NTE_BAD_PUBLIC_KEY); /* FIXME: error_code? */
2550                 return FALSE;
2551             }
2552             return crypt_export_simple(pCryptKey, pPubKey, dwFlags, pbData,
2553                                        pdwDataLen);
2554             
2555         case PUBLICKEYBLOB:
2556             if (is_valid_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY)) {
2557                 SetLastError(NTE_BAD_KEY); /* FIXME: error code? */
2558                 return FALSE;
2559             }
2560 
2561             return crypt_export_public_key(pCryptKey, pbData, pdwDataLen);
2562 
2563         case PRIVATEKEYBLOB:
2564             return crypt_export_private_key(pCryptKey, force, pbData, pdwDataLen);
2565 
2566         case PLAINTEXTKEYBLOB:
2567             return crypt_export_plaintext_key(pCryptKey, pbData, pdwDataLen);
2568             
2569         default:
2570             SetLastError(NTE_BAD_TYPE); /* FIXME: error code? */
2571             return FALSE;
2572     }
2573 }
2574 
2575 /******************************************************************************
2576  * CPExportKey (RSAENH.@)
2577  *
2578  * Export a key into a binary large object (BLOB).
2579  *
2580  * PARAMS
2581  *  hProv      [I]   Key container from which a key is to be exported.
2582  *  hKey       [I]   Key to be exported.
2583  *  hPubKey    [I]   Key used to encrypt sensitive BLOB data.
2584  *  dwBlobType [I]   SIMPLEBLOB, PUBLICKEYBLOB or PRIVATEKEYBLOB.
2585  *  dwFlags    [I]   Currently none defined.
2586  *  pbData     [O]   Pointer to a buffer where the BLOB will be written to.
2587  *  pdwDataLen [I/O] I: Size of buffer at pbData, O: Size of BLOB
2588  *
2589  * RETURNS
2590  *  Success: TRUE.
2591  *  Failure: FALSE.
2592  */
2593 BOOL WINAPI RSAENH_CPExportKey(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTKEY hPubKey,
2594                                DWORD dwBlobType, DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2595 {
2596     CRYPTKEY *pCryptKey;
2597 
2598     TRACE("(hProv=%08lx, hKey=%08lx, hPubKey=%08lx, dwBlobType=%08x, dwFlags=%08x, pbData=%p,"
2599           "pdwDataLen=%p)\n", hProv, hKey, hPubKey, dwBlobType, dwFlags, pbData, pdwDataLen);
2600 
2601     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2602     {
2603         SetLastError(NTE_BAD_UID);
2604         return FALSE;
2605     }
2606 
2607     if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2608     {
2609         SetLastError(NTE_BAD_KEY);
2610         return FALSE;
2611     }
2612 
2613     return crypt_export_key(pCryptKey, hPubKey, dwBlobType, dwFlags, FALSE,
2614         pbData, pdwDataLen);
2615 }
2616 
2617 /******************************************************************************
2618  * release_and_install_key [Internal]
2619  *
2620  * Release an existing key, if present, and replaces it with a new one.
2621  *
2622  * PARAMS
2623  *  hProv     [I] Key container into which the key is to be imported.
2624  *  src       [I] Key which will replace *dest
2625  *  dest      [I] Points to key to be released and replaced with src
2626  *  fStoreKey [I] If TRUE, the newly installed key is stored to the registry.
2627  */
2628 static void release_and_install_key(HCRYPTPROV hProv, HCRYPTKEY src,
2629                                     HCRYPTKEY *dest, DWORD fStoreKey)
2630 {
2631     RSAENH_CPDestroyKey(hProv, *dest);
2632     copy_handle(&handle_table, src, RSAENH_MAGIC_KEY, dest);
2633     if (fStoreKey)
2634     {
2635         KEYCONTAINER *pKeyContainer;
2636 
2637         if (lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER,
2638                           (OBJECTHDR**)&pKeyContainer))
2639         {
2640             store_key_container_keys(pKeyContainer);
2641             store_key_container_permissions(pKeyContainer);
2642         }
2643     }
2644 }
2645 
2646 /******************************************************************************
2647  * import_private_key [Internal]
2648  *
2649  * Import a BLOB'ed private key into a key container.
2650  *
2651  * PARAMS
2652  *  hProv     [I] Key container into which the private key is to be imported.
2653  *  pbData    [I] Pointer to a buffer which holds the private key BLOB.
2654  *  dwDataLen [I] Length of data in buffer at pbData.
2655  *  dwFlags   [I] One of:
2656  *                CRYPT_EXPORTABLE: the imported key is marked exportable
2657  *  fStoreKey [I] If TRUE, the imported key is stored to the registry.
2658  *  phKey     [O] Handle to the imported key.
2659  *
2660  *
2661  * NOTES
2662  *  Assumes the caller has already checked the BLOBHEADER at pbData to ensure
2663  *  it's a PRIVATEKEYBLOB.
2664  *
2665  * RETURNS
2666  *  Success: TRUE.
2667  *  Failure: FALSE.
2668  */
2669 static BOOL import_private_key(HCRYPTPROV hProv, CONST BYTE *pbData, DWORD dwDataLen,
2670                                DWORD dwFlags, BOOL fStoreKey, HCRYPTKEY *phKey)
2671 {
2672     KEYCONTAINER *pKeyContainer;
2673     CRYPTKEY *pCryptKey;
2674     CONST BLOBHEADER *pBlobHeader = (CONST BLOBHEADER*)pbData;
2675     CONST RSAPUBKEY *pRSAPubKey = (CONST RSAPUBKEY*)(pBlobHeader+1);
2676     BOOL ret;
2677 
2678     if (!lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER,
2679                        (OBJECTHDR**)&pKeyContainer))
2680     {
2681         SetLastError(NTE_BAD_UID);
2682         return FALSE;
2683     }
2684 
2685     if ((dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY)) ||
2686         (pRSAPubKey->magic != RSAENH_MAGIC_RSA2) ||
2687         (dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) +
2688             (2 * pRSAPubKey->bitlen >> 3) + (5 * ((pRSAPubKey->bitlen+8)>>4))))
2689     {
2690         SetLastError(NTE_BAD_DATA);
2691         return FALSE;
2692     }
2693 
2694     *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, MAKELONG(0,pRSAPubKey->bitlen), &pCryptKey);
2695     if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
2696     setup_key(pCryptKey);
2697     ret = import_private_key_impl((CONST BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2698                                    pRSAPubKey->bitlen/8, pRSAPubKey->pubexp);
2699     if (ret) {
2700         if (dwFlags & CRYPT_EXPORTABLE)
2701             pCryptKey->dwPermissions |= CRYPT_EXPORT;
2702         switch (pBlobHeader->aiKeyAlg)
2703         {
2704         case AT_SIGNATURE:
2705         case CALG_RSA_SIGN:
2706             TRACE("installing signing key\n");
2707             release_and_install_key(hProv, *phKey, &pKeyContainer->hSignatureKeyPair,
2708                                     fStoreKey);
2709             break;
2710         case AT_KEYEXCHANGE:
2711         case CALG_RSA_KEYX:
2712             TRACE("installing key exchange key\n");
2713             release_and_install_key(hProv, *phKey, &pKeyContainer->hKeyExchangeKeyPair,
2714                                     fStoreKey);
2715             break;
2716         }
2717     }
2718     return ret;
2719 }
2720 
2721 /******************************************************************************
2722  * import_public_key [Internal]
2723  *
2724  * Import a BLOB'ed public key into a key container.
2725  *
2726  * PARAMS
2727  *  hProv     [I] Key container into which the public key is to be imported.
2728  *  pbData    [I] Pointer to a buffer which holds the public key BLOB.
2729  *  dwDataLen [I] Length of data in buffer at pbData.
2730  *  dwFlags   [I] One of:
2731  *                CRYPT_EXPORTABLE: the imported key is marked exportable
2732  *  fStoreKey [I] If TRUE, the imported key is stored to the registry.
2733  *  phKey     [O] Handle to the imported key.
2734  *
2735  *
2736  * NOTES
2737  *  Assumes the caller has already checked the BLOBHEADER at pbData to ensure
2738  *  it's a PUBLICKEYBLOB.
2739  *
2740  * RETURNS
2741  *  Success: TRUE.
2742  *  Failure: FALSE.
2743  */
2744 static BOOL import_public_key(HCRYPTPROV hProv, CONST BYTE *pbData, DWORD dwDataLen,
2745                               DWORD dwFlags, BOOL fStoreKey, HCRYPTKEY *phKey)
2746 {
2747     KEYCONTAINER *pKeyContainer;
2748     CRYPTKEY *pCryptKey;
2749     CONST BLOBHEADER *pBlobHeader = (CONST BLOBHEADER*)pbData;
2750     CONST RSAPUBKEY *pRSAPubKey = (CONST RSAPUBKEY*)(pBlobHeader+1);
2751     ALG_ID algID;
2752     BOOL ret;
2753 
2754     if (!lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER,
2755                        (OBJECTHDR**)&pKeyContainer))
2756     {
2757         SetLastError(NTE_BAD_UID);
2758         return FALSE;
2759     }
2760 
2761     if ((dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY)) ||
2762         (pRSAPubKey->magic != RSAENH_MAGIC_RSA1) ||
2763         (dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) + (pRSAPubKey->bitlen >> 3)))
2764     {
2765         SetLastError(NTE_BAD_DATA);
2766         return FALSE;
2767     }
2768 
2769     /* Since this is a public key blob, only the public key is
2770      * available, so only signature verification is possible.
2771      */
2772     algID = pBlobHeader->aiKeyAlg;
2773     *phKey = new_key(hProv, algID, MAKELONG(0,pRSAPubKey->bitlen), &pCryptKey);
2774     if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
2775     setup_key(pCryptKey);
2776     ret = import_public_key_impl((CONST BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2777                                   pRSAPubKey->bitlen >> 3, pRSAPubKey->pubexp);
2778     if (ret) {
2779         if (dwFlags & CRYPT_EXPORTABLE)
2780             pCryptKey->dwPermissions |= CRYPT_EXPORT;
2781         switch (pBlobHeader->aiKeyAlg)
2782         {
2783         case AT_KEYEXCHANGE:
2784         case CALG_RSA_KEYX:
2785             TRACE("installing public key\n");
2786             release_and_install_key(hProv, *phKey, &pKeyContainer->hKeyExchangeKeyPair,
2787                                     fStoreKey);
2788             break;
2789         }
2790     }
2791     return ret;
2792 }
2793 
2794 /******************************************************************************
2795  * import_symmetric_key [Internal]
2796  *
2797  * Import a BLOB'ed symmetric key into a key container.
2798  *
2799  * PARAMS
2800  *  hProv     [I] Key container into which the symmetric key is to be imported.
2801  *  pbData    [I] Pointer to a buffer which holds the symmetric key BLOB.
2802  *  dwDataLen [I] Length of data in buffer at pbData.
2803  *  hPubKey   [I] Key used to decrypt sensitive BLOB data.
2804  *  dwFlags   [I] One of:
2805  *                CRYPT_EXPORTABLE: the imported key is marked exportable
2806  *  phKey     [O] Handle to the imported key.
2807  *
2808  *
2809  * NOTES
2810  *  Assumes the caller has already checked the BLOBHEADER at pbData to ensure
2811  *  it's a SIMPLEBLOB.
2812  *
2813  * RETURNS
2814  *  Success: TRUE.
2815  *  Failure: FALSE.
2816  */
2817 static BOOL import_symmetric_key(HCRYPTPROV hProv, CONST BYTE *pbData,
2818                                  DWORD dwDataLen, HCRYPTKEY hPubKey,
2819                                  DWORD dwFlags, HCRYPTKEY *phKey)
2820 {
2821     CRYPTKEY *pCryptKey, *pPubKey;
2822     CONST BLOBHEADER *pBlobHeader = (CONST BLOBHEADER*)pbData;
2823     CONST ALG_ID *pAlgid = (CONST ALG_ID*)(pBlobHeader+1);
2824     CONST BYTE *pbKeyStream = (CONST BYTE*)(pAlgid + 1);
2825     BYTE *pbDecrypted;
2826     DWORD dwKeyLen;
2827 
2828     if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pPubKey) ||
2829         pPubKey->aiAlgid != CALG_RSA_KEYX)
2830     {
2831         SetLastError(NTE_BAD_PUBLIC_KEY); /* FIXME: error code? */
2832         return FALSE;
2833     }
2834 
2835     if (dwDataLen < sizeof(BLOBHEADER)+sizeof(ALG_ID)+pPubKey->dwBlockLen)
2836     {
2837         SetLastError(NTE_BAD_DATA); /* FIXME: error code */
2838         return FALSE;
2839     }
2840 
2841     pbDecrypted = HeapAlloc(GetProcessHeap(), 0, pPubKey->dwBlockLen);
2842     if (!pbDecrypted) return FALSE;
2843     encrypt_block_impl(pPubKey->aiAlgid, PK_PRIVATE, &pPubKey->context, pbKeyStream, pbDecrypted,
2844                        RSAENH_DECRYPT);
2845 
2846     dwKeyLen = RSAENH_MAX_KEY_SIZE;
2847     if (!unpad_data(pbDecrypted, pPubKey->dwBlockLen, pbDecrypted, &dwKeyLen, dwFlags)) {
2848         HeapFree(GetProcessHeap(), 0, pbDecrypted);
2849         return FALSE;
2850     }
2851 
2852     *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, dwKeyLen<<19, &pCryptKey);
2853     if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
2854     {
2855         HeapFree(GetProcessHeap(), 0, pbDecrypted);
2856         return FALSE;
2857     }
2858     memcpy(pCryptKey->abKeyValue, pbDecrypted, dwKeyLen);
2859     HeapFree(GetProcessHeap(), 0, pbDecrypted);
2860     setup_key(pCryptKey);
2861     if (dwFlags & CRYPT_EXPORTABLE)
2862         pCryptKey->dwPermissions |= CRYPT_EXPORT;
2863     return TRUE;
2864 }
2865 
2866 /******************************************************************************
2867  * import_plaintext_key [Internal]
2868  *
2869  * Import a plaintext key into a key container.
2870  *
2871  * PARAMS
2872  *  hProv     [I] Key container into which the symmetric key is to be imported.
2873  *  pbData    [I] Pointer to a buffer which holds the plaintext key BLOB.
2874  *  dwDataLen [I] Length of data in buffer at pbData.
2875  *  dwFlags   [I] One of:
2876  *                CRYPT_EXPORTABLE: the imported key is marked exportable
2877  *  phKey     [O] Handle to the imported key.
2878  *
2879  *
2880  * NOTES
2881  *  Assumes the caller has already checked the BLOBHEADER at pbData to ensure
2882  *  it's a PLAINTEXTKEYBLOB.
2883  *
2884  * RETURNS
2885  *  Success: TRUE.
2886  *  Failure: FALSE.
2887  */
2888 static BOOL import_plaintext_key(HCRYPTPROV hProv, CONST BYTE *pbData,
2889                                  DWORD dwDataLen, DWORD dwFlags,
2890                                  HCRYPTKEY *phKey)
2891 {
2892     CRYPTKEY *pCryptKey;
2893     CONST BLOBHEADER *pBlobHeader = (CONST BLOBHEADER*)pbData;
2894     CONST DWORD *pKeyLen = (CONST DWORD *)(pBlobHeader + 1);
2895     CONST BYTE *pbKeyStream = (CONST BYTE*)(pKeyLen + 1);
2896 
2897     if (dwDataLen < sizeof(BLOBHEADER)+sizeof(DWORD)+*pKeyLen)
2898     {
2899         SetLastError(NTE_BAD_DATA); /* FIXME: error code */
2900         return FALSE;
2901     }
2902 
2903     *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, *pKeyLen<<19, &pCryptKey);
2904     if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
2905         return FALSE;
2906     memcpy(pCryptKey->abKeyValue, pbKeyStream, *pKeyLen);
2907     setup_key(pCryptKey);
2908     if (dwFlags & CRYPT_EXPORTABLE)
2909         pCryptKey->dwPermissions |= CRYPT_EXPORT;
2910     return TRUE;
2911 }
2912 
2913 /******************************************************************************
2914  * import_key [Internal]
2915  *
2916  * Import a BLOB'ed key into a key container, optionally storing the key's
2917  * value to the registry.
2918  *
2919  * PARAMS
2920  *  hProv     [I] Key container into which the key is to be imported.
2921  *  pbData    [I] Pointer to a buffer which holds the BLOB.
2922  *  dwDataLen [I] Length of data in buffer at pbData.
2923  *  hPubKey   [I] Key used to decrypt sensitive BLOB data.
2924  *  dwFlags   [I] One of:
2925  *                CRYPT_EXPORTABLE: the imported key is marked exportable
2926  *  fStoreKey [I] If TRUE, the imported key is stored to the registry.
2927  *  phKey     [O] Handle to the imported key.
2928  *
2929  * RETURNS
2930  *  Success: TRUE.
2931  *  Failure: FALSE.
2932  */
2933 static BOOL import_key(HCRYPTPROV hProv, CONST BYTE *pbData, DWORD dwDataLen,
2934                        HCRYPTKEY hPubKey, DWORD dwFlags, BOOL fStoreKey,
2935                        HCRYPTKEY *phKey)
2936 {
2937     KEYCONTAINER *pKeyContainer;
2938     CONST BLOBHEADER *pBlobHeader = (CONST BLOBHEADER*)pbData;
2939 
2940     if (!lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER,
2941                        (OBJECTHDR**)&pKeyContainer)) 
2942     {
2943         SetLastError(NTE_BAD_UID);
2944         return FALSE;
2945     }
2946 
2947     if (dwDataLen < sizeof(BLOBHEADER) || 
2948         pBlobHeader->bVersion != CUR_BLOB_VERSION ||
2949         pBlobHeader->reserved != 0) 
2950     {
2951         SetLastError(NTE_BAD_DATA);
2952         return FALSE;
2953     }
2954 
2955     /* If this is a verify-only context, the key is not persisted regardless of
2956      * fStoreKey's original value.
2957      */
2958     fStoreKey = fStoreKey && !(dwFlags & CRYPT_VERIFYCONTEXT);
2959     switch (pBlobHeader->bType)
2960     {
2961         case PRIVATEKEYBLOB:    
2962             return import_private_key(hProv, pbData, dwDataLen, dwFlags,
2963                                       fStoreKey, phKey);
2964                 
2965         case PUBLICKEYBLOB:
2966             return import_public_key(hProv, pbData, dwDataLen, dwFlags,
2967                                      fStoreKey, phKey);
2968                 
2969         case SIMPLEBLOB:
2970             return import_symmetric_key(hProv, pbData, dwDataLen, hPubKey,
2971                                         dwFlags, phKey);
2972 
2973         case PLAINTEXTKEYBLOB:
2974             return import_plaintext_key(hProv, pbData, dwDataLen, dwFlags,
2975                                         phKey);
2976 
2977         default:
2978             SetLastError(NTE_BAD_TYPE); /* FIXME: error code? */
2979             return FALSE;
2980     }
2981 }
2982 
2983 /******************************************************************************
2984  * CPImportKey (RSAENH.@)
2985  *
2986  * Import a BLOB'ed key into a key container.
2987  *
2988  * PARAMS
2989  *  hProv     [I] Key container into which the key is to be imported.
2990  *  pbData    [I] Pointer to a buffer which holds the BLOB.
2991  *  dwDataLen [I] Length of data in buffer at pbData.
2992  *  hPubKey   [I] Key used to decrypt sensitive BLOB data.
2993  *  dwFlags   [I] One of:
2994  *                CRYPT_EXPORTABLE: the imported key is marked exportable
2995  *  phKey     [O] Handle to the imported key.
2996  *
2997  * RETURNS
2998  *  Success: TRUE.
2999  *  Failure: FALSE.
3000  */
3001 BOOL WINAPI RSAENH_CPImportKey(HCRYPTPROV hProv, CONST BYTE *pbData, DWORD dwDataLen,
3002                                HCRYPTKEY hPubKey, DWORD dwFlags, HCRYPTKEY *phKey)
3003 {
3004     TRACE("(hProv=%08lx, pbData=%p, dwDataLen=%d, hPubKey=%08lx, dwFlags=%08x, phKey=%p)\n",
3005         hProv, pbData, dwDataLen, hPubKey, dwFlags, phKey);
3006 
3007     return import_key(hProv, pbData, dwDataLen, hPubKey, dwFlags, TRUE, phKey);
3008 }
3009 
3010 /******************************************************************************
3011  * CPGenKey (RSAENH.@)
3012  *
3013  * Generate a key in the key container
3014  *
3015  * PARAMS
3016  *  hProv   [I] Key container for which a key is to be generated.
3017  *  Algid   [I] Crypto algorithm identifier for the key to be generated.
3018  *  dwFlags [I] Upper 16 bits: Binary length of key. Lower 16 bits: Flags. See Notes
3019  *  phKey   [O] Handle to the generated key.
3020  *
3021  * RETURNS
3022  *  Success: TRUE.
3023  *  Failure: FALSE.
3024  *
3025  * FIXME
3026  *  Flags currently not considered.
3027  *
3028  * NOTES
3029  *  Private key-exchange- and signature-keys can be generated with Algid AT_KEYEXCHANGE
3030  *  and AT_SIGNATURE values.
3031  */
3032 BOOL WINAPI RSAENH_CPGenKey(HCRYPTPROV hProv, ALG_ID Algid, DWORD dwFlags, HCRYPTKEY *phKey)
3033 {
3034     KEYCONTAINER *pKeyContainer;
3035     CRYPTKEY *pCryptKey;
3036 
3037     TRACE("(hProv=%08lx, aiAlgid=%d, dwFlags=%08x, phKey=%p)\n", hProv, Algid, dwFlags, phKey);
3038 
3039     if (!lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER,
3040                        (OBJECTHDR**)&pKeyContainer)) 
3041     {
3042         /* MSDN: hProv not containing valid context handle */
3043         SetLastError(NTE_BAD_UID);
3044         return FALSE;
3045     }
3046     
3047     switch (Algid)
3048     {
3049         case AT_SIGNATURE:
3050         case CALG_RSA_SIGN:
3051             *phKey = new_key(hProv, CALG_RSA_SIGN, dwFlags, &pCryptKey);
3052             if (pCryptKey) { 
3053                 new_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen);
3054                 setup_key(pCryptKey);
3055                 if (Algid == AT_SIGNATURE) {
3056                     RSAENH_CPDestroyKey(hProv, pKeyContainer->hSignatureKeyPair);
3057                     copy_handle(&handle_table, *phKey, RSAENH_MAGIC_KEY,
3058                                 &pKeyContainer->hSignatureKeyPair);
3059                 }
3060             }
3061             break;
3062 
3063         case AT_KEYEXCHANGE:
3064         case CALG_RSA_KEYX:
3065             *phKey = new_key(hProv, CALG_RSA_KEYX, dwFlags, &pCryptKey);
3066             if (pCryptKey) { 
3067                 new_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen);
3068                 setup_key(pCryptKey);
3069                 if (Algid == AT_KEYEXCHANGE) {
3070                     RSAENH_CPDestroyKey(hProv, pKeyContainer->hKeyExchangeKeyPair);
3071                     copy_handle(&handle_table, *phKey, RSAENH_MAGIC_KEY,
3072                                 &pKeyContainer->hKeyExchangeKeyPair);
3073                 }
3074             }
3075             break;
3076             
3077         case CALG_RC2:
3078         case CALG_RC4:
3079         case CALG_DES:
3080         case CALG_3DES_112:
3081         case CALG_3DES:
3082         case CALG_AES:
3083         case CALG_AES_128:
3084         case CALG_AES_192:
3085         case CALG_AES_256:
3086         case CALG_PCT1_MASTER:
3087         case CALG_SSL2_MASTER:
3088         case CALG_SSL3_MASTER:
3089         case CALG_TLS1_MASTER:
3090             *phKey = new_key(hProv, Algid, dwFlags, &pCryptKey);
3091             if (pCryptKey) {
3092                 gen_rand_impl(pCryptKey->abKeyValue, RSAENH_MAX_KEY_SIZE);
3093                 switch (Algid) {
3094                     case CALG_SSL3_MASTER:
3095                         pCryptKey->abKeyValue[0] = RSAENH_SSL3_VERSION_MAJOR;
3096                         pCryptKey->abKeyValue[1] = RSAENH_SSL3_VERSION_MINOR;
3097                         break;
3098 
3099                     case CALG_TLS1_MASTER:
3100                         pCryptKey->abKeyValue[0] = RSAENH_TLS1_VERSION_MAJOR;
3101                         pCryptKey->abKeyValue[1] = RSAENH_TLS1_VERSION_MINOR;
3102                         break;
3103                 }
3104                 setup_key(pCryptKey);
3105             }
3106             break;
3107             
3108         default:
3109             /* MSDN: Algorithm not supported specified by Algid */
3110             SetLastError(NTE_BAD_ALGID);
3111             return FALSE;
3112     }
3113             
3114     return *phKey != (HCRYPTKEY)INVALID_HANDLE_VALUE;
3115 }
3116 
3117 /******************************************************************************
3118  * CPGenRandom (RSAENH.@)
3119  *
3120  * Generate a random byte stream.
3121  *
3122  * PARAMS
3123  *  hProv    [I] Key container that is used to generate random bytes.
3124  *  dwLen    [I] Specifies the number of requested random data bytes.
3125  *  pbBuffer [O] Random bytes will be stored here.
3126  *
3127  * RETURNS
3128  *  Success: TRUE
3129  *  Failure: FALSE
3130  */
3131 BOOL WINAPI RSAENH_CPGenRandom(HCRYPTPROV hProv, DWORD dwLen, BYTE *pbBuffer)
3132 {
3133     TRACE("(hProv=%08lx, dwLen=%d, pbBuffer=%p)\n", hProv, dwLen, pbBuffer);
3134     
3135     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3136     {
3137         /* MSDN: hProv not containing valid context handle */
3138         SetLastError(NTE_BAD_UID);
3139         return FALSE;
3140     }
3141 
3142     return gen_rand_impl(pbBuffer, dwLen);
3143 }
3144 
3145 /******************************************************************************
3146  * CPGetHashParam (RSAENH.@)
3147  *
3148  * Query parameters of an hash object.
3149  *
3150  * PARAMS
3151  *  hProv      [I]   The kea container, which the hash belongs to.
3152  *  hHash      [I]   The hash object that is to be queried.
3153  *  dwParam    [I]   Specifies the parameter that is to be queried.
3154  *  pbData     [I]   Pointer to the buffer where the parameter value will be stored.
3155  *  pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
3156  *  dwFlags    [I]   None currently defined.
3157  *
3158  * RETURNS
3159  *  Success: TRUE
3160  *  Failure: FALSE
3161  *
3162  * NOTES
3163  *  Valid dwParams are: HP_ALGID, HP_HASHSIZE, HP_HASHVALUE. The hash will be 
3164  *  finalized if HP_HASHVALUE is queried.
3165  */
3166 BOOL WINAPI RSAENH_CPGetHashParam(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwParam, BYTE *pbData, 
3167                                   DWORD *pdwDataLen, DWORD dwFlags) 
3168 {
3169     CRYPTHASH *pCryptHash;
3170         
3171     TRACE("(hProv=%08lx, hHash=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p, dwFlags=%08x)\n",
3172         hProv, hHash, dwParam, pbData, pdwDataLen, dwFlags);
3173     
3174     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3175     {
3176         SetLastError(NTE_BAD_UID);
3177         return FALSE;
3178     }
3179 
3180     if (dwFlags)
3181     {
3182         SetLastError(NTE_BAD_FLAGS);
3183         return FALSE;
3184     }
3185     
3186     if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH,
3187                        (OBJECTHDR**)&pCryptHash))
3188     {
3189         SetLastError(NTE_BAD_HASH);
3190         return FALSE;
3191     }
3192 
3193     if (!pdwDataLen)
3194     {
3195         SetLastError(ERROR_INVALID_PARAMETER);
3196         return FALSE;
3197     }
3198     
3199     switch (dwParam)
3200     {
3201         case HP_ALGID:
3202             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptHash->aiAlgid, 
3203                               sizeof(ALG_ID));
3204 
3205         case HP_HASHSIZE:
3206             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptHash->dwHashSize, 
3207                               sizeof(DWORD));
3208 
3209         case HP_HASHVAL:
3210             if (pCryptHash->aiAlgid == CALG_TLS1PRF) {
3211                 return tls1_prf(hProv, pCryptHash->hKey, &pCryptHash->tpPRFParams.blobLabel,
3212                                 &pCryptHash->tpPRFParams.blobSeed, pbData, *pdwDataLen);
3213             }
3214 
3215             if ( pbData == NULL ) {
3216                 *pdwDataLen = pCryptHash->dwHashSize;
3217                 return TRUE;
3218             }
3219 
3220             if (pbData && (pCryptHash->dwState != RSAENH_HASHSTATE_FINISHED))
3221             {
3222                 finalize_hash(pCryptHash);
3223                 pCryptHash->dwState = RSAENH_HASHSTATE_FINISHED;
3224             }
3225 
3226             return copy_param(pbData, pdwDataLen, pCryptHash->abHashValue,
3227                               pCryptHash->dwHashSize);
3228 
3229         default:
3230             SetLastError(NTE_BAD_TYPE);
3231             return FALSE;
3232     }
3233 }
3234 
3235 /******************************************************************************
3236  * CPSetKeyParam (RSAENH.@)
3237  *
3238  * Set a parameter of a key object
3239  *
3240  * PARAMS
3241  *  hProv   [I] The key container to which the key belongs.
3242  *  hKey    [I] The key for which a parameter is to be set.
3243  *  dwParam [I] Parameter type. See Notes.
3244  *  pbData  [I] Pointer to the parameter value.
3245  *  dwFlags [I] Currently none defined.
3246  *
3247  * RETURNS
3248  *  Success: TRUE.
3249  *  Failure: FALSE.
3250  *
3251  * NOTES:
3252  *  Defined dwParam types are:
3253  *   - KP_MODE: Values MODE_CBC, MODE_ECB, MODE_CFB.
3254  *   - KP_MODE_BITS: Shift width for cipher feedback mode. (Currently ignored by MS CSP's)
3255  *   - KP_PERMISSIONS: Or'ed combination of CRYPT_ENCRYPT, CRYPT_DECRYPT, 
3256  *                     CRYPT_EXPORT, CRYPT_READ, CRYPT_WRITE, CRYPT_MAC
3257  *   - KP_IV: Initialization vector
3258  */
3259 BOOL WINAPI RSAENH_CPSetKeyParam(HCRYPTPROV hProv, HCRYPTKEY hKey, DWORD dwParam, BYTE *pbData, 
3260                                  DWORD dwFlags)
3261 {
3262     CRYPTKEY *pCryptKey;
3263 
3264     TRACE("(hProv=%08lx, hKey=%08lx, dwParam=%08x, pbData=%p, dwFlags=%08x)\n", hProv, hKey,
3265           dwParam, pbData, dwFlags);
3266 
3267     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3268     {
3269         SetLastError(NTE_BAD_UID);
3270         return FALSE;
3271     }
3272 
3273     if (dwFlags) {
3274         SetLastError(NTE_BAD_FLAGS);
3275         return FALSE;
3276     }
3277     
3278     if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
3279     {
3280         SetLastError(NTE_BAD_KEY);
3281         return FALSE;
3282     }
3283     
3284     switch (dwParam) {
3285         case KP_PADDING:
3286             /* The MS providers only support PKCS5_PADDING */
3287             if (*(DWORD *)pbData != PKCS5_PADDING) {
3288                 SetLastError(NTE_BAD_DATA);
3289                 return FALSE;
3290             }
3291             return TRUE;
3292 
3293         case KP_MODE:
3294             pCryptKey->dwMode = *(DWORD*)pbData;
3295             return TRUE;
3296 
3297         case KP_MODE_BITS:
3298             pCryptKey->dwModeBits = *(DWORD*)pbData;
3299             return TRUE;
3300 
3301         case KP_PERMISSIONS:
3302         {
3303             DWORD perms = *(DWORD *)pbData;
3304 
3305             if ((perms & CRYPT_EXPORT) &&
3306                 !(pCryptKey->dwPermissions & CRYPT_EXPORT))
3307             {
3308                 SetLastError(NTE_BAD_DATA);
3309                 return FALSE;
3310             }
3311             else if (!(perms & CRYPT_EXPORT) &&
3312                 (pCryptKey->dwPermissions & CRYPT_EXPORT))
3313             {
3314                 /* Clearing the export permission appears to be ignored,
3315                  * see tests.
3316                  */
3317                 perms |= CRYPT_EXPORT;
3318             }
3319             pCryptKey->dwPermissions = perms;
3320             return TRUE;
3321         }
3322 
3323         case KP_IV:
3324             memcpy(pCryptKey->abInitVector, pbData, pCryptKey->dwBlockLen);
3325             setup_key(pCryptKey);
3326             return TRUE;
3327 
3328         case KP_SALT_EX:
3329         {
3330             CRYPT_INTEGER_BLOB *blob = (CRYPT_INTEGER_BLOB *)pbData;
3331 
3332             /* salt length can't be greater than 184 bits = 24 bytes */
3333             if (blob->cbData > 24)
3334             {
3335                 SetLastError(NTE_BAD_DATA);
3336                 return FALSE;
3337             }
3338             memcpy(pCryptKey->abKeyValue + pCryptKey->dwKeyLen, blob->pbData,
3339                    blob->cbData);
3340             pCryptKey->dwSaltLen = blob->cbData;
3341             setup_key(pCryptKey);
3342             return TRUE;
3343         }
3344 
3345         case KP_EFFECTIVE_KEYLEN:
3346             switch (pCryptKey->aiAlgid) {
3347                 case CALG_RC2:
3348                     if (!pbData)
3349                     {
3350                         SetLastError(ERROR_INVALID_PARAMETER);
3351                         return FALSE;
3352                     }
3353                     else if (!*(DWORD *)pbData || *(DWORD *)pbData > 1024)
3354                     {
3355                         SetLastError(NTE_BAD_DATA);
3356                         return FALSE;
3357                     }
3358                     else
3359                     {
3360                         pCryptKey->dwEffectiveKeyLen = *(DWORD *)pbData;
3361                         setup_key(pCryptKey);
3362                     }
3363                     break;
3364                 default:
3365                     SetLastError(NTE_BAD_TYPE);
3366                     return FALSE;
3367             }
3368             return TRUE;
3369 
3370         case KP_SCHANNEL_ALG:
3371             switch (((PSCHANNEL_ALG)pbData)->dwUse) {
3372                 case SCHANNEL_ENC_KEY:
3373                     memcpy(&pCryptKey->siSChannelInfo.saEncAlg, pbData, sizeof(SCHANNEL_ALG));
3374                     break;
3375 
3376                 case SCHANNEL_MAC_KEY:
3377                     memcpy(&pCryptKey->siSChannelInfo.saMACAlg, pbData, sizeof(SCHANNEL_ALG));
3378                     break;
3379 
3380                 default:
3381                     SetLastError(NTE_FAIL); /* FIXME: error code */
3382                     return FALSE;
3383             }
3384             return TRUE;
3385 
3386         case KP_CLIENT_RANDOM:
3387             return copy_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom, (PCRYPT_DATA_BLOB)pbData);
3388             
3389         case KP_SERVER_RANDOM:
3390             return copy_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom, (PCRYPT_DATA_BLOB)pbData);
3391 
3392         default:
3393             SetLastError(NTE_BAD_TYPE);
3394             return FALSE;
3395     }
3396 }
3397 
3398 /******************************************************************************
3399  * CPGetKeyParam (RSAENH.@)
3400  *
3401  * Query a key parameter.
3402  *
3403  * PARAMS
3404  *  hProv      [I]   The key container, which the key belongs to.
3405  *  hHash      [I]   The key object that is to be queried.
3406  *  dwParam    [I]   Specifies the parameter that is to be queried.
3407  *  pbData     [I]   Pointer to the buffer where the parameter value will be stored.
3408  *  pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
3409  *  dwFlags    [I]   None currently defined.
3410  *
3411  * RETURNS
3412  *  Success: TRUE
3413  *  Failure: FALSE
3414  *
3415  * NOTES
3416  *  Defined dwParam types are:
3417  *   - KP_MODE: Values MODE_CBC, MODE_ECB, MODE_CFB.
3418  *   - KP_MODE_BITS: Shift width for cipher feedback mode. 
3419  *                   (Currently ignored by MS CSP's - always eight)
3420  *   - KP_PERMISSIONS: Or'ed combination of CRYPT_ENCRYPT, CRYPT_DECRYPT, 
3421  *                     CRYPT_EXPORT, CRYPT_READ, CRYPT_WRITE, CRYPT_MAC
3422  *   - KP_IV: Initialization vector.
3423  *   - KP_KEYLEN: Bitwidth of the key.
3424  *   - KP_BLOCKLEN: Size of a block cipher block.
3425  *   - KP_SALT: Salt value.
3426  */
3427 BOOL WINAPI RSAENH_CPGetKeyParam(HCRYPTPROV hProv, HCRYPTKEY hKey, DWORD dwParam, BYTE *pbData, 
3428                                  DWORD *pdwDataLen, DWORD dwFlags)
3429 {
3430     CRYPTKEY *pCryptKey;
3431     DWORD dwValue;
3432         
3433     TRACE("(hProv=%08lx, hKey=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p dwFlags=%08x)\n",
3434           hProv, hKey, dwParam, pbData, pdwDataLen, dwFlags);
3435 
3436     if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3437     {
3438         SetLastError(NTE_BAD_UID);
3439         return FALSE;
3440     }
3441 
3442     if (dwFlags) {
3443         SetLastError(NTE_BAD_FLAGS);
3444         return FALSE;
3445     }
3446 
3447     if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
3448     {
3449         SetLastError(NTE_BAD_KEY);
3450         return FALSE;
3451     }
3452 
3453     switch (dwParam) 
3454     {
3455         case KP_IV:
3456             return copy_param(pbData, pdwDataLen, pCryptKey->abInitVector,
3457                               pCryptKey->dwBlockLen);
3458         
3459         case KP_SALT:
3460             return copy_param(pbData, pdwDataLen, 
3461                     &pCryptKey->abKeyValue[pCryptKey->dwKeyLen], pCryptKey->dwSaltLen);
3462 
3463         case KP_PADDING:
3464             dwValue = PKCS5_PADDING;
3465             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwValue, sizeof(DWORD));
3466 
3467         case KP_KEYLEN:
3468             dwValue = pCryptKey->dwKeyLen << 3;
3469             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwValue, sizeof(DWORD));
3470         
3471         case KP_EFFECTIVE_KEYLEN:
3472             if (pCryptKey->dwEffectiveKeyLen)
3473                 dwValue = pCryptKey->dwEffectiveKeyLen;
3474             else
3475                 dwValue = pCryptKey->dwKeyLen << 3;
3476             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwValue, sizeof(DWORD));
3477 
3478         case KP_BLOCKLEN:
3479             dwValue = pCryptKey->dwBlockLen << 3;
3480             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwValue, sizeof(DWORD));
3481     
3482         case KP_MODE:
3483             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptKey->dwMode, sizeof(DWORD));
3484 
3485         case KP_MODE_BITS:
3486             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptKey->dwModeBits, 
3487                               sizeof(DWORD));
3488     
3489         case KP_PERMISSIONS:
3490             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptKey->dwPermissions, 
3491                               sizeof(DWORD));
3492 
3493         case KP_ALGID:
3494             return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptKey->aiAlgid, sizeof(DWORD));
3495             
3496         default:
3497             SetLastError(NTE_BAD_TYPE);
3498             return FALSE;
3499     }
3500 }
3501                         
3502 /******************************************************************************
3503  * CPGetProvParam (RSAENH.@)
3504  *
3505  * Query a CSP parameter.
3506  *
3507  * PARAMS
3508  *  hProv      [I]   The key container that is to be queried.
3509  *  dwParam    [I]   Specifies the parameter that is to be queried.
3510  *  pbData     [I]   Pointer to the buffer where the parameter value will be stored.
3511  *  pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
3512  *  dwFlags    [I]   CRYPT_FIRST: Start enumeration (for PP_ENUMALGS{_EX}).
3513  *
3514  * RETURNS
3515  *  Success: TRUE
3516  *  Failure: FALSE
3517  * NOTES:
3518  *  Defined dwParam types:
3519  *   - PP_CONTAINER: Name of the key container.
3520  *   - PP_NAME: Name of the cryptographic service provider.
3521  *   - PP_SIG_KEYSIZE_INC: RSA signature keywidth granularity in bits.
3522  *   - PP_KEYX_KEYSIZE_INC: RSA key-exchange keywidth granularity in bits.