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