dbghelp: Extend dwarf stack unwinding by reading information out of .debug_frame...
[wine] / dlls / advapi32 / crypt.c
1 /*
2  * Copyright 1999 Ian Schmidt
3  * Copyright 2001 Travis Michielsen
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
18  */
19
20 /***********************************************************************
21  *
22  *  TODO:
23  *  - Reference counting
24  *  - Thread-safing
25  */
26
27 #include "config.h"
28 #include "wine/port.h"
29
30 #include <time.h>
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <sys/types.h>
34 #ifdef HAVE_SYS_STAT_H
35 # include <sys/stat.h>
36 #endif
37 #include <fcntl.h>
38 #ifdef HAVE_UNISTD_H
39 # include <unistd.h>
40 #endif
41
42 #include "ntstatus.h"
43 #define WIN32_NO_STATUS
44 #include "crypt.h"
45 #include "winnls.h"
46 #include "winreg.h"
47 #include "rpc.h"
48 #include "wine/debug.h"
49 #include "wine/unicode.h"
50 #include "winternl.h"
51
52 WINE_DEFAULT_DEBUG_CHANNEL(crypt);
53
54 static HWND crypt_hWindow;
55
56 #define CRYPT_Alloc(size) (LocalAlloc(LMEM_ZEROINIT, size))
57 #define CRYPT_Free(buffer) (LocalFree(buffer))
58
59 static inline PWSTR CRYPT_GetProvKeyName(PCWSTR pProvName)
60 {
61         static const WCHAR KEYSTR[] = {
62                 'S','o','f','t','w','a','r','e','\\',
63                 'M','i','c','r','o','s','o','f','t','\\',
64                 'C','r','y','p','t','o','g','r','a','p','h','y','\\',
65                 'D','e','f','a','u','l','t','s','\\',
66                 'P','r','o','v','i','d','e','r','\\',0
67         };
68         PWSTR keyname;
69
70         keyname = CRYPT_Alloc((strlenW(KEYSTR) + strlenW(pProvName) +1)*sizeof(WCHAR));
71         if (keyname)
72         {
73                 strcpyW(keyname, KEYSTR);
74                 strcpyW(keyname + strlenW(KEYSTR), pProvName);
75         } else
76                 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
77         return keyname;
78 }
79
80 static inline PWSTR CRYPT_GetTypeKeyName(DWORD dwType, BOOL user)
81 {
82         static const WCHAR MACHINESTR[] = {
83                 'S','o','f','t','w','a','r','e','\\',
84                 'M','i','c','r','o','s','o','f','t','\\',
85                 'C','r','y','p','t','o','g','r','a','p','h','y','\\',
86                 'D','e','f','a','u','l','t','s','\\',
87                 'P','r','o','v','i','d','e','r',' ','T','y','p','e','s','\\',
88                 'T','y','p','e',' ','X','X','X',0
89         };
90         static const WCHAR USERSTR[] = {
91                 'S','o','f','t','w','a','r','e','\\',
92                 'M','i','c','r','o','s','o','f','t','\\',
93                 'C','r','y','p','t','o','g','r','a','p','h','y','\\',
94                 'P','r','o','v','i','d','e','r',' ','T','y','p','e',' ','X','X','X',0
95         };
96         PWSTR keyname;
97         PWSTR ptr;
98
99         keyname = CRYPT_Alloc( ((user ? strlenW(USERSTR) : strlenW(MACHINESTR)) +1)*sizeof(WCHAR));
100         if (keyname)
101         {
102                 user ? strcpyW(keyname, USERSTR) : strcpyW(keyname, MACHINESTR);
103                 ptr = keyname + strlenW(keyname);
104                 *(--ptr) = (dwType % 10) + '0';
105                 *(--ptr) = ((dwType / 10) % 10) + '0';
106                 *(--ptr) = (dwType / 100) + '0';
107         } else
108                 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
109         return keyname;
110 }
111
112 /* CRYPT_UnicodeTOANSI
113  * wstr - unicode string
114  * str - pointer to ANSI string
115  * strsize - size of buffer pointed to by str or -1 if we have to do the allocation
116  *
117  * returns TRUE if unsuccessful, FALSE otherwise.
118  * if wstr is NULL, returns TRUE and sets str to NULL! Value of str should be checked after call
119  */
120 static inline BOOL CRYPT_UnicodeToANSI(LPCWSTR wstr, LPSTR* str, int strsize)
121 {
122         int count;
123
124         if (!wstr)
125         {
126                 *str = NULL;
127                 return TRUE;
128         }
129         count = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);
130         if (strsize == -1)
131                 *str = CRYPT_Alloc(count * sizeof(CHAR));
132         else
133                 count = min( count, strsize );
134         if (*str)
135         {
136                 WideCharToMultiByte(CP_ACP, 0, wstr, -1, *str, count, NULL, NULL);
137                 return TRUE;
138         }
139         SetLastError(ERROR_NOT_ENOUGH_MEMORY);
140         return FALSE;
141 }
142
143 /* CRYPT_ANSITOUnicode
144  * str - ANSI string
145  * wstr - pointer to unicode string
146  * wstrsize - size of buffer pointed to by wstr or -1 if we have to do the allocation
147  */
148 static inline BOOL CRYPT_ANSIToUnicode(LPCSTR str, LPWSTR* wstr, int wstrsize)
149 {
150         unsigned int wcount;
151
152         if (!str)
153         {
154                 *wstr = NULL;
155                 return TRUE;
156         }
157         wcount = MultiByteToWideChar(CP_ACP, 0, str, -1, NULL, 0);
158         if (wstrsize == -1)
159                 *wstr = CRYPT_Alloc(wcount * sizeof(WCHAR));
160         else
161                 wcount = min( wcount, wstrsize/sizeof(WCHAR) );
162         if (*wstr)
163         {
164                 MultiByteToWideChar(CP_ACP, 0, str, -1, *wstr, wcount);
165                 return TRUE;
166         }
167         SetLastError(ERROR_NOT_ENOUGH_MEMORY);
168         return FALSE;
169 }
170
171 /* These next 2 functions are used by the VTableProvStruc structure */
172 static BOOL CALLBACK CRYPT_VerifyImage(LPCSTR lpszImage, BYTE* pData)
173 {
174         if (!lpszImage || !pData)
175         {
176                 SetLastError(ERROR_INVALID_PARAMETER);
177                 return FALSE;
178         }
179
180         FIXME("(%s, %p): not verifying image\n", lpszImage, pData);
181
182         return TRUE;
183 }
184
185 static void CALLBACK CRYPT_ReturnhWnd(HWND *phWnd)
186 {
187         if (phWnd) *phWnd = crypt_hWindow;
188 }
189
190 #define CRYPT_GetProvFunc(name) \
191         if ( !(provider->pFuncs->p##name = (void*)GetProcAddress(provider->hModule, #name)) ) goto error
192 #define CRYPT_GetProvFuncOpt(name) \
193         provider->pFuncs->p##name = (void*)GetProcAddress(provider->hModule, #name)
194 static PCRYPTPROV CRYPT_LoadProvider(PCWSTR pImage)
195 {
196         PCRYPTPROV provider;
197         DWORD errorcode = ERROR_NOT_ENOUGH_MEMORY;
198
199         if ( !(provider = CRYPT_Alloc(sizeof(CRYPTPROV))) ) goto error;
200         if ( !(provider->pFuncs = CRYPT_Alloc(sizeof(PROVFUNCS))) ) goto error;
201         if ( !(provider->pVTable = CRYPT_Alloc(sizeof(VTableProvStruc))) ) goto error;
202         if ( !(provider->hModule = LoadLibraryW(pImage)) )
203         {
204                 errorcode = (GetLastError() == ERROR_FILE_NOT_FOUND) ? NTE_PROV_DLL_NOT_FOUND : NTE_PROVIDER_DLL_FAIL;
205                 FIXME("Failed to load dll %s\n", debugstr_w(pImage));
206                 goto error;
207         }
208         provider->dwMagic = MAGIC_CRYPTPROV;
209         provider->refcount = 1;
210
211         errorcode = NTE_PROVIDER_DLL_FAIL;
212         CRYPT_GetProvFunc(CPAcquireContext);
213         CRYPT_GetProvFunc(CPCreateHash);
214         CRYPT_GetProvFunc(CPDecrypt);
215         CRYPT_GetProvFunc(CPDeriveKey);
216         CRYPT_GetProvFunc(CPDestroyHash);
217         CRYPT_GetProvFunc(CPDestroyKey);
218         CRYPT_GetProvFuncOpt(CPDuplicateHash);
219         CRYPT_GetProvFuncOpt(CPDuplicateKey);
220         CRYPT_GetProvFunc(CPEncrypt);
221         CRYPT_GetProvFunc(CPExportKey);
222         CRYPT_GetProvFunc(CPGenKey);
223         CRYPT_GetProvFunc(CPGenRandom);
224         CRYPT_GetProvFunc(CPGetHashParam);
225         CRYPT_GetProvFunc(CPGetKeyParam);
226         CRYPT_GetProvFunc(CPGetProvParam);
227         CRYPT_GetProvFunc(CPGetUserKey);
228         CRYPT_GetProvFunc(CPHashData);
229         CRYPT_GetProvFunc(CPHashSessionKey);
230         CRYPT_GetProvFunc(CPImportKey);
231         CRYPT_GetProvFunc(CPReleaseContext);
232         CRYPT_GetProvFunc(CPSetHashParam);
233         CRYPT_GetProvFunc(CPSetKeyParam);
234         CRYPT_GetProvFunc(CPSetProvParam);
235         CRYPT_GetProvFunc(CPSignHash);
236         CRYPT_GetProvFunc(CPVerifySignature);
237
238         /* FIXME: Not sure what the pbContextInfo field is for.
239          *        Does it need memory allocation?
240          */
241         provider->pVTable->Version = 3;
242         provider->pVTable->FuncVerifyImage = CRYPT_VerifyImage;
243         provider->pVTable->FuncReturnhWnd = CRYPT_ReturnhWnd;
244         provider->pVTable->dwProvType = 0;
245         provider->pVTable->pbContextInfo = NULL;
246         provider->pVTable->cbContextInfo = 0;
247         provider->pVTable->pszProvName = NULL;
248         return provider;
249
250 error:
251         SetLastError(errorcode);
252         if (provider)
253         {
254                 provider->dwMagic = 0;
255                 if (provider->hModule)
256                         FreeLibrary(provider->hModule);
257                 CRYPT_Free(provider->pVTable);
258                 CRYPT_Free(provider->pFuncs);
259                 CRYPT_Free(provider);
260         }
261         return NULL;
262 }
263 #undef CRYPT_GetProvFunc
264 #undef CRYPT_GetProvFuncOpt
265
266
267 static void CRYPT_CreateMachineGuid(void)
268 {
269         static const WCHAR cryptographyW[] = {
270                 'S','o','f','t','w','a','r','e','\\',
271                 'M','i','c','r','o','s','o','f','t','\\',
272                 'C','r','y','p','t','o','g','r','a','p','h','y',0 };
273         static const WCHAR machineGuidW[] = {
274                 'M','a','c','h','i','n','e','G','u','i','d',0 };
275         LONG r;
276         HKEY key;
277
278         r = RegOpenKeyExW(HKEY_LOCAL_MACHINE, cryptographyW, 0, KEY_ALL_ACCESS,
279                           &key);
280         if (!r)
281         {
282                 DWORD size;
283
284                 r = RegQueryValueExW(key, machineGuidW, NULL, NULL, NULL, &size);
285                 if (r == ERROR_FILE_NOT_FOUND)
286                 {
287                         static const WCHAR rpcrt4[] = {
288                                 'r','p','c','r','t','4',0 };
289                         HMODULE lib = LoadLibraryW(rpcrt4);
290
291                         if (lib)
292                         {
293                                 RPC_STATUS (RPC_ENTRY *pUuidCreate)(UUID *);
294                                 UUID uuid;
295                                 WCHAR buf[37];
296                                 RPC_STATUS rs;
297                                 static const WCHAR uuidFmt[] = {
298                                     '%','0','8','x','-','%','0','4','x','-',
299                                     '%','0','4','x','-','%','0','2','x',
300                                     '%','0','2','x','-','%','0','2','x',
301                                     '%','0','2','x','%','0','2','x',
302                                     '%','0','2','x','%','0','2','x',
303                                     '%','0','2','x',0 };
304
305                                 pUuidCreate = (void *)GetProcAddress(lib, "UuidCreate");
306                                 rs = pUuidCreate(&uuid);
307                                 if (rs == S_OK)
308                                 {
309                                     sprintfW(buf, uuidFmt,
310                                              uuid.Data1, uuid.Data2, uuid.Data3,
311                                              uuid.Data4[0], uuid.Data4[1],
312                                              uuid.Data4[2], uuid.Data4[3],
313                                              uuid.Data4[4], uuid.Data4[5],
314                                              uuid.Data4[6], uuid.Data4[7] );
315                                     RegSetValueExW(key, machineGuidW, 0, REG_SZ,
316                                                    (const BYTE *)buf,
317                                                    (lstrlenW(buf)+1)*sizeof(WCHAR));
318                                 }
319                                 FreeLibrary(lib);
320                         }
321                 }
322                 RegCloseKey(key);
323         }
324 }
325
326 /******************************************************************************
327  * CryptAcquireContextW (ADVAPI32.@)
328  *
329  * Acquire a crypto provider context handle.
330  *
331  * PARAMS
332  *  phProv       [O] Pointer to HCRYPTPROV for the output.
333  *  pszContainer [I] Key Container Name
334  *  pszProvider  [I] Cryptographic Service Provider Name
335  *  dwProvType   [I] Crypto provider type to get a handle.
336  *  dwFlags      [I] flags for the operation
337  *
338  * RETURNS 
339  *  TRUE on success, FALSE on failure.
340  */
341 BOOL WINAPI CryptAcquireContextW (HCRYPTPROV *phProv, LPCWSTR pszContainer,
342                 LPCWSTR pszProvider, DWORD dwProvType, DWORD dwFlags)
343 {
344         PCRYPTPROV pProv = NULL;
345         HKEY key;
346         PWSTR imagepath = NULL, keyname = NULL, provname = NULL, temp = NULL;
347         PSTR provnameA = NULL, pszContainerA = NULL;
348         DWORD keytype, type, len;
349         ULONG r;
350         static const WCHAR nameW[] = {'N','a','m','e',0};
351         static const WCHAR typeW[] = {'T','y','p','e',0};
352         static const WCHAR imagepathW[] = {'I','m','a','g','e',' ','P','a','t','h',0};
353
354         TRACE("(%p, %s, %s, %d, %08x)\n", phProv, debugstr_w(pszContainer),
355                 debugstr_w(pszProvider), dwProvType, dwFlags);
356
357         if (dwProvType < 1 || dwProvType > MAXPROVTYPES)
358         {
359                 SetLastError(NTE_BAD_PROV_TYPE);
360                 return FALSE;
361         }
362         
363         if (!phProv)
364         {
365                 SetLastError(ERROR_INVALID_PARAMETER);
366                 return FALSE;
367         }
368
369         /* Make sure the MachineGuid value exists */
370         CRYPT_CreateMachineGuid();
371
372         if (!pszProvider || !*pszProvider)
373         {
374                 /* No CSP name specified so try the user default CSP first
375                  * then try the machine default CSP
376                  */
377                 if ( !(keyname = CRYPT_GetTypeKeyName(dwProvType, TRUE)) ) {
378                         TRACE("No provider registered for crypto provider type %d.\n", dwProvType);
379                         SetLastError(NTE_PROV_TYPE_NOT_DEF);
380                         return FALSE;
381                 }
382                 if (RegOpenKeyW(HKEY_CURRENT_USER, keyname, &key))
383                 {
384                         CRYPT_Free(keyname);
385                         if ( !(keyname = CRYPT_GetTypeKeyName(dwProvType, FALSE)) ) {
386                                 TRACE("No type registered for crypto provider type %d.\n", dwProvType);
387                                 RegCloseKey(key);
388                                 SetLastError(NTE_PROV_TYPE_NOT_DEF);
389                                 goto error;
390                         }
391                         if (RegOpenKeyW(HKEY_LOCAL_MACHINE, keyname, &key)) {
392                                 TRACE("Did not find registry entry of crypto provider for %s.\n", debugstr_w(keyname));
393                                 CRYPT_Free(keyname);
394                                 RegCloseKey(key);
395                                 SetLastError(NTE_PROV_TYPE_NOT_DEF);
396                                 goto error;
397                         }
398                 }
399                 CRYPT_Free(keyname);
400                 r = RegQueryValueExW(key, nameW, NULL, &keytype, NULL, &len);
401                 if( r != ERROR_SUCCESS || !len || keytype != REG_SZ)
402                 {
403                         TRACE("error %d reading size of 'Name' from registry\n", r );
404                         RegCloseKey(key);
405                         SetLastError(NTE_PROV_TYPE_ENTRY_BAD);
406                         goto error;
407                 }
408                 if(!(provname = CRYPT_Alloc(len)))
409                 {
410                         RegCloseKey(key);
411                         SetLastError(ERROR_NOT_ENOUGH_MEMORY);
412                         goto error;
413                 }
414                 r = RegQueryValueExW(key, nameW, NULL, NULL, (LPBYTE)provname, &len);
415                 if( r != ERROR_SUCCESS )
416                 {
417                         TRACE("error %d reading 'Name' from registry\n", r );
418                         RegCloseKey(key);
419                         SetLastError(NTE_PROV_TYPE_ENTRY_BAD);
420                         goto error;
421                 }
422                 RegCloseKey(key);
423         } else {
424                 if ( !(provname = CRYPT_Alloc((strlenW(pszProvider) +1)*sizeof(WCHAR))) )
425                 {
426                         SetLastError(ERROR_NOT_ENOUGH_MEMORY);
427                         goto error;
428                 }
429                 strcpyW(provname, pszProvider);
430         }
431
432         keyname = CRYPT_GetProvKeyName(provname);
433         r = RegOpenKeyW(HKEY_LOCAL_MACHINE, keyname, &key);
434         CRYPT_Free(keyname);
435         if (r != ERROR_SUCCESS)
436         {
437                 SetLastError(NTE_KEYSET_NOT_DEF);
438                 goto error;
439         }
440         len = sizeof(DWORD);
441         r = RegQueryValueExW(key, typeW, NULL, NULL, (BYTE*)&type, &len);
442         if (r != ERROR_SUCCESS)
443         {
444                 SetLastError(NTE_PROV_TYPE_ENTRY_BAD);
445                 goto error;
446         }
447         if (type != dwProvType)
448         {
449                 TRACE("Crypto provider has wrong type (%d vs expected %d).\n", type, dwProvType);
450                 SetLastError(NTE_PROV_TYPE_NO_MATCH);
451                 goto error;
452         }
453
454         r = RegQueryValueExW(key, imagepathW, NULL, &keytype, NULL, &len);
455         if ( r != ERROR_SUCCESS || keytype != REG_SZ)
456         {
457                 TRACE("error %d reading size of 'Image Path' from registry\n", r );
458                 RegCloseKey(key);
459                 SetLastError(NTE_PROV_TYPE_ENTRY_BAD);
460                 goto error;
461         }
462         if (!(temp = CRYPT_Alloc(len)))
463         {
464                 RegCloseKey(key);
465                 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
466                 goto error;
467         }
468         r = RegQueryValueExW(key, imagepathW, NULL, NULL, (LPBYTE)temp, &len);
469         if( r != ERROR_SUCCESS )
470         {
471                 TRACE("error %d reading 'Image Path' from registry\n", r );
472                 RegCloseKey(key);
473                 SetLastError(NTE_PROV_TYPE_ENTRY_BAD);
474                 goto error;
475         }
476         RegCloseKey(key);
477         len = ExpandEnvironmentStringsW(temp, NULL, 0);
478         if ( !(imagepath = CRYPT_Alloc(len*sizeof(WCHAR))) )
479         {
480                 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
481                 goto error;
482         }
483         if (!ExpandEnvironmentStringsW(temp, imagepath, len))
484         {
485                 /* ExpandEnvironmentStrings will call SetLastError */
486                 goto error;
487         }
488         pProv = CRYPT_LoadProvider(imagepath);
489         if (!pProv) {
490                 /* CRYPT_LoadProvider calls SetLastError */
491                 goto error;
492         }
493         pProv->pVTable->dwProvType = dwProvType;
494         if(!CRYPT_UnicodeToANSI(provname, &provnameA, -1))
495         {
496                 /* CRYPT_UnicodeToANSI calls SetLastError */
497                 goto error;
498         }
499         pProv->pVTable->pszProvName = provnameA;
500         if(!CRYPT_UnicodeToANSI(pszContainer, &pszContainerA, -1))
501         {
502                 /* CRYPT_UnicodeToANSI calls SetLastError */
503                 goto error;
504         }
505         if (pProv->pFuncs->pCPAcquireContext(&pProv->hPrivate, pszContainerA, dwFlags, pProv->pVTable))
506         {
507                 /* MSDN: When this flag is set, the value returned in phProv is undefined,
508                  *       and thus, the CryptReleaseContext function need not be called afterwards.
509                  *       Therefore, we must clean up everything now.
510                  */
511                 if (dwFlags & CRYPT_DELETEKEYSET)
512                 {
513                         pProv->dwMagic = 0;
514                         FreeLibrary(pProv->hModule);
515                         CRYPT_Free(provnameA);
516                         CRYPT_Free(pProv->pVTable);
517                         CRYPT_Free(pProv->pFuncs);
518                         CRYPT_Free(pProv);
519                 } else {
520                         *phProv = (HCRYPTPROV)pProv;
521                 }
522                 CRYPT_Free(pszContainerA);
523                 CRYPT_Free(provname);
524                 CRYPT_Free(temp);
525                 CRYPT_Free(imagepath);
526                 return TRUE;
527         }
528         /* FALLTHROUGH TO ERROR IF FALSE - CSP internal error! */
529 error:
530         if (pProv)
531         {
532                 pProv->dwMagic = 0;
533                 if (pProv->hModule)
534                         FreeLibrary(pProv->hModule);
535                 CRYPT_Free(pProv->pVTable);
536                 CRYPT_Free(pProv->pFuncs);
537                 CRYPT_Free(pProv);
538         }
539         CRYPT_Free(pszContainerA);
540         CRYPT_Free(provnameA);
541         CRYPT_Free(provname);
542         CRYPT_Free(temp);
543         CRYPT_Free(imagepath);
544         return FALSE;
545 }
546
547 /******************************************************************************
548  * CryptAcquireContextA (ADVAPI32.@)
549  *
550  * See CryptAcquireContextW.
551  */
552 BOOL WINAPI CryptAcquireContextA (HCRYPTPROV *phProv, LPCSTR pszContainer,
553                 LPCSTR pszProvider, DWORD dwProvType, DWORD dwFlags)
554 {
555         PWSTR pProvider = NULL, pContainer = NULL;
556         BOOL ret = FALSE;
557
558         TRACE("(%p, %s, %s, %d, %08x)\n", phProv, pszContainer,
559                 pszProvider, dwProvType, dwFlags);
560
561         if ( !CRYPT_ANSIToUnicode(pszContainer, &pContainer, -1) )
562         {
563                 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
564                 return FALSE;
565         }
566         if ( !CRYPT_ANSIToUnicode(pszProvider, &pProvider, -1) )
567         {
568                 CRYPT_Free(pContainer);
569                 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
570                 return FALSE;
571         }
572
573         ret = CryptAcquireContextW(phProv, pContainer, pProvider, dwProvType, dwFlags);
574
575         CRYPT_Free(pContainer);
576         CRYPT_Free(pProvider);
577
578         return ret;
579 }
580
581 /******************************************************************************
582  * CryptContextAddRef (ADVAPI32.@)
583  *
584  * Increases reference count of a cryptographic service provider handle
585  * by one.
586  *
587  * PARAMS
588  *  hProv       [I] Handle to the CSP whose reference is being incremented.
589  *  pdwReserved [IN] Reserved for future use and must be NULL.
590  *  dwFlags     [I] Reserved for future use and must be NULL.
591  *
592  * RETURNS
593  *  Success: TRUE
594  *  Failure: FALSE
595  */
596 BOOL WINAPI CryptContextAddRef (HCRYPTPROV hProv, DWORD *pdwReserved, DWORD dwFlags)
597 {
598         PCRYPTPROV pProv = (PCRYPTPROV)hProv;   
599
600         TRACE("(0x%lx, %p, %08x)\n", hProv, pdwReserved, dwFlags);
601
602         if (!pProv)
603         {
604                 SetLastError(NTE_BAD_UID);
605                 return FALSE;
606         }
607
608         if (pProv->dwMagic != MAGIC_CRYPTPROV)
609         {
610                 SetLastError(ERROR_INVALID_PARAMETER);
611                 return FALSE;
612         }
613
614         pProv->refcount++;
615         return TRUE;
616 }
617
618 /******************************************************************************
619  * CryptReleaseContext (ADVAPI32.@)
620  *
621  * Releases the handle of a CSP.  Reference count is decreased.
622  *
623  * PARAMS
624  *  hProv   [I] Handle of a CSP.
625  *  dwFlags [I] Reserved for future use and must be NULL.
626  *
627  * RETURNS
628  *  Success: TRUE
629  *  Failure: FALSE
630  */
631 BOOL WINAPI CryptReleaseContext (HCRYPTPROV hProv, ULONG_PTR dwFlags)
632 {
633         PCRYPTPROV pProv = (PCRYPTPROV)hProv;
634         BOOL ret = TRUE;
635
636         TRACE("(0x%lx, %08lx)\n", hProv, dwFlags);
637
638         if (!pProv)
639         {
640                 SetLastError(NTE_BAD_UID);
641                 return FALSE;
642         }
643
644         if (pProv->dwMagic != MAGIC_CRYPTPROV)
645         {
646                 SetLastError(ERROR_INVALID_PARAMETER);
647                 return FALSE;
648         }
649
650         pProv->refcount--;
651         if (pProv->refcount <= 0) 
652         {
653                 ret = pProv->pFuncs->pCPReleaseContext(pProv->hPrivate, dwFlags);
654                 pProv->dwMagic = 0;
655                 FreeLibrary(pProv->hModule);
656 #if 0
657                 CRYPT_Free(pProv->pVTable->pContextInfo);
658 #endif
659                 CRYPT_Free(pProv->pVTable->pszProvName);
660                 CRYPT_Free(pProv->pVTable);
661                 CRYPT_Free(pProv->pFuncs);
662                 CRYPT_Free(pProv);
663         }
664         return ret;
665 }
666
667 /******************************************************************************
668  * CryptGenRandom (ADVAPI32.@)
669  *
670  * Fills a buffer with cryptographically random bytes.
671  *
672  * PARAMS
673  *  hProv    [I] Handle of a CSP.
674  *  dwLen    [I] Number of bytes to generate.
675  *  pbBuffer [I/O] Buffer to contain random bytes.
676  *
677  * RETURNS
678  *  Success: TRUE
679  *  Failure: FALSE
680  *
681  * NOTES
682  *  pdBuffer must be at least dwLen bytes long.
683  */
684 BOOL WINAPI CryptGenRandom (HCRYPTPROV hProv, DWORD dwLen, BYTE *pbBuffer)
685 {
686         PCRYPTPROV prov = (PCRYPTPROV)hProv;
687
688         TRACE("(0x%lx, %d, %p)\n", hProv, dwLen, pbBuffer);
689
690         if (!hProv)
691         {
692                 SetLastError(ERROR_INVALID_HANDLE);
693                 return FALSE;
694         }
695
696         if (prov->dwMagic != MAGIC_CRYPTPROV)
697         {
698                 SetLastError(ERROR_INVALID_PARAMETER);
699                 return FALSE;
700         }
701
702         return prov->pFuncs->pCPGenRandom(prov->hPrivate, dwLen, pbBuffer);
703 }
704
705 /******************************************************************************
706  * CryptCreateHash (ADVAPI32.@)
707  *
708  * Initiates the hashing of a stream of data.
709  *
710  * PARAMS
711  *  hProv   [I] Handle of a CSP.
712  *  Algid   [I] Identifies the hash algorithm to use.
713  *  hKey    [I] Key for the hash (if required).
714  *  dwFlags [I] Reserved for future use and must be NULL.
715  *  phHash  [O] Address of the future handle to the new hash object.
716  *
717  * RETURNS
718  *  Success: TRUE
719  *  Failure: FALSE
720  *
721  * NOTES
722  *  If the algorithm is a keyed hash, hKey is the key.
723  */
724 BOOL WINAPI CryptCreateHash (HCRYPTPROV hProv, ALG_ID Algid, HCRYPTKEY hKey,
725                 DWORD dwFlags, HCRYPTHASH *phHash)
726 {
727         PCRYPTPROV prov = (PCRYPTPROV)hProv;
728         PCRYPTKEY key = (PCRYPTKEY)hKey;
729         PCRYPTHASH hash;
730
731         TRACE("(0x%lx, 0x%x, 0x%lx, %08x, %p)\n", hProv, Algid, hKey, dwFlags, phHash);
732
733         if (!prov)
734         {
735                 SetLastError(ERROR_INVALID_HANDLE);
736                 return FALSE;
737         }
738         if (!phHash || prov->dwMagic != MAGIC_CRYPTPROV)
739         {
740                 SetLastError(ERROR_INVALID_PARAMETER);
741                 return FALSE;
742         }
743         if (dwFlags)
744         {
745                 SetLastError(NTE_BAD_FLAGS);
746                 return FALSE;
747         }
748         if ( !(hash = CRYPT_Alloc(sizeof(CRYPTHASH))) )
749         {
750                 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
751                 return FALSE;
752         }
753
754         hash->pProvider = prov;
755
756         if (prov->pFuncs->pCPCreateHash(prov->hPrivate, Algid,
757                         key ? key->hPrivate : 0, 0, &hash->hPrivate))
758         {
759             *phHash = (HCRYPTHASH)hash;
760             return TRUE;
761         }
762
763         /* CSP error! */
764         CRYPT_Free(hash);
765         *phHash = 0;
766         return FALSE;
767 }
768
769 /******************************************************************************
770  * CryptDecrypt (ADVAPI32.@)
771  *
772  * Decrypts data encrypted by CryptEncrypt.
773  *
774  * PARAMS
775  *  hKey       [I] Handle to the decryption key.
776  *  hHash      [I] Handle to a hash object.
777  *  Final      [I] TRUE if this is the last section to be decrypted.
778  *  dwFlags    [I] Reserved for future use. Can be CRYPT_OAEP.
779  *  pbData     [I/O] Buffer that holds the encrypted data. Holds decrypted
780  *                   data on return
781  *  pdwDataLen [I/O] Length of pbData before and after the call.
782  *
783  *  RETURNS
784  *   Success: TRUE
785  *   Failure: FALSE
786  */
787 BOOL WINAPI CryptDecrypt (HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final,
788                 DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
789 {
790         PCRYPTPROV prov;
791         PCRYPTKEY key = (PCRYPTKEY)hKey;
792         PCRYPTHASH hash = (PCRYPTHASH)hHash;
793
794         TRACE("(0x%lx, 0x%lx, %d, %08x, %p, %p)\n", hKey, hHash, Final, dwFlags, pbData, pdwDataLen);
795
796         if (!key || !pbData || !pdwDataLen || !key->pProvider || key->pProvider->dwMagic != MAGIC_CRYPTPROV)
797         {
798                 SetLastError(ERROR_INVALID_PARAMETER);
799                 return FALSE;
800         }
801
802         prov = key->pProvider;
803         return prov->pFuncs->pCPDecrypt(prov->hPrivate, key->hPrivate, hash ? hash->hPrivate : 0,
804                         Final, dwFlags, pbData, pdwDataLen);
805 }
806
807 /******************************************************************************
808  * CryptDeriveKey (ADVAPI32.@)
809  *
810  * Generates session keys derived from a base data value.
811  *
812  * PARAMS
813  *  hProv     [I] Handle to a CSP.
814  *  Algid     [I] Identifies the symmetric encryption algorithm to use.
815  *  hBaseData [I] Handle to a hash object.
816  *  dwFlags   [I] Type of key to generate.
817  *  phKey     [I/O] Address of the newly generated key.
818  *
819  * RETURNS
820  *  Success: TRUE
821  *  Failure: FALSE
822  */
823 BOOL WINAPI CryptDeriveKey (HCRYPTPROV hProv, ALG_ID Algid, HCRYPTHASH hBaseData,
824                 DWORD dwFlags, HCRYPTKEY *phKey)
825 {
826         PCRYPTPROV prov = (PCRYPTPROV)hProv;
827         PCRYPTHASH hash = (PCRYPTHASH)hBaseData;
828         PCRYPTKEY key;
829
830         TRACE("(0x%lx, 0x%08x, 0x%lx, 0x%08x, %p)\n", hProv, Algid, hBaseData, dwFlags, phKey);
831
832         if (!prov || !hash)
833         {
834                 SetLastError(ERROR_INVALID_HANDLE);
835                 return FALSE;
836         }
837         if (!phKey || prov->dwMagic != MAGIC_CRYPTPROV)
838         {
839                 SetLastError(ERROR_INVALID_PARAMETER);
840                 return FALSE;
841         }
842         if ( !(key = CRYPT_Alloc(sizeof(CRYPTKEY))) )
843         {
844                 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
845                 return FALSE;
846         }
847
848         key->pProvider = prov;
849         if (prov->pFuncs->pCPDeriveKey(prov->hPrivate, Algid, hash->hPrivate, dwFlags, &key->hPrivate))
850         {
851             *phKey = (HCRYPTKEY)key;
852             return TRUE;
853         }
854
855         /* CSP error! */
856         CRYPT_Free(key);
857         *phKey = 0;
858         return FALSE;
859 }
860
861 /******************************************************************************
862  * CryptDestroyHash (ADVAPI32.@)
863  *
864  * Destroys the hash object referenced by hHash.
865  *
866  * PARAMS
867  *  hHash [I] Handle of the hash object to be destroyed.
868  *
869  * RETURNS
870  *  Success: TRUE
871  *  Failure: FALSE
872  */
873 BOOL WINAPI CryptDestroyHash (HCRYPTHASH hHash)
874 {
875         PCRYPTHASH hash = (PCRYPTHASH)hHash;
876         PCRYPTPROV prov;
877         BOOL ret;
878
879         TRACE("(0x%lx)\n", hHash);
880
881         if (!hash)
882         {
883                 SetLastError(ERROR_INVALID_HANDLE);
884                 return FALSE;
885         }
886
887         if (!hash->pProvider || hash->pProvider->dwMagic != MAGIC_CRYPTPROV)
888         {
889                 SetLastError(ERROR_INVALID_PARAMETER);
890                 return FALSE;
891         }
892
893         prov = hash->pProvider;
894         ret = prov->pFuncs->pCPDestroyHash(prov->hPrivate, hash->hPrivate);
895         CRYPT_Free(hash);
896         return ret;
897 }
898
899 /******************************************************************************
900  * CryptDestroyKey (ADVAPI32.@)
901  *
902  * Releases the handle referenced by hKey.
903  *
904  * PARAMS
905  *  hKey [I] Handle of the key to be destroyed.
906  *
907  * RETURNS
908  *  Success: TRUE
909  *  Failure: FALSE
910  */
911 BOOL WINAPI CryptDestroyKey (HCRYPTKEY hKey)
912 {
913         PCRYPTKEY key = (PCRYPTKEY)hKey;
914         PCRYPTPROV prov;
915         BOOL ret;
916
917         TRACE("(0x%lx)\n", hKey);
918
919         if (!key)
920         {
921                 SetLastError(ERROR_INVALID_HANDLE);
922                 return FALSE;
923         }
924
925         if (!key->pProvider || key->pProvider->dwMagic != MAGIC_CRYPTPROV)
926         {
927                 SetLastError(ERROR_INVALID_PARAMETER);
928                 return FALSE;
929         }
930
931         prov = key->pProvider;
932         ret = prov->pFuncs->pCPDestroyKey(prov->hPrivate, key->hPrivate);
933         CRYPT_Free(key);
934         return ret;
935 }
936
937 /******************************************************************************
938  * CryptDuplicateHash (ADVAPI32.@)
939  *
940  * Duplicates a hash.
941  *
942  * PARAMS
943  *  hHash       [I] Handle to the hash to be copied.
944  *  pdwReserved [I] Reserved for future use and must be zero.
945  *  dwFlags     [I] Reserved for future use and must be zero.
946  *  phHash      [O] Address of the handle to receive the copy.
947  *
948  * RETURNS
949  *  Success: TRUE
950  *  Failure: FALSE
951  */
952 BOOL WINAPI CryptDuplicateHash (HCRYPTHASH hHash, DWORD *pdwReserved,
953                 DWORD dwFlags, HCRYPTHASH *phHash)
954 {
955         PCRYPTPROV prov;
956         PCRYPTHASH orghash, newhash;
957
958         TRACE("(0x%lx, %p, %08x, %p)\n", hHash, pdwReserved, dwFlags, phHash);
959
960         orghash = (PCRYPTHASH)hHash;
961         if (!orghash || pdwReserved || !phHash || !orghash->pProvider || 
962                 orghash->pProvider->dwMagic != MAGIC_CRYPTPROV)
963         {
964                 SetLastError(ERROR_INVALID_PARAMETER);
965                 return FALSE;
966         }
967
968         prov = orghash->pProvider;
969         if (!prov->pFuncs->pCPDuplicateHash)
970         {
971                 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
972                 return FALSE;
973         }
974
975         if ( !(newhash = CRYPT_Alloc(sizeof(CRYPTHASH))) )
976         {
977                 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
978                 return FALSE;
979         }
980
981         newhash->pProvider = prov;
982         if (prov->pFuncs->pCPDuplicateHash(prov->hPrivate, orghash->hPrivate, pdwReserved, dwFlags, &newhash->hPrivate))
983         {
984                 *phHash = (HCRYPTHASH)newhash;
985                 return TRUE;
986         }
987         CRYPT_Free(newhash);
988         return FALSE;
989 }
990
991 /******************************************************************************
992  * CryptDuplicateKey (ADVAPI32.@)
993  *
994  * Duplicate a key and the key's state.
995  *
996  * PARAMS
997  *  hKey        [I] Handle of the key to copy.
998  *  pdwReserved [I] Reserved for future use and must be NULL.
999  *  dwFlags     [I] Reserved for future use and must be zero.
1000  *  phKey       [I] Address of the handle to the duplicated key.
1001  *
1002  * RETURNS
1003  *  Success: TRUE
1004  *  Failure: FALSE
1005  */
1006 BOOL WINAPI CryptDuplicateKey (HCRYPTKEY hKey, DWORD *pdwReserved, DWORD dwFlags, HCRYPTKEY *phKey)
1007 {
1008         PCRYPTPROV prov;
1009         PCRYPTKEY orgkey, newkey;
1010
1011         TRACE("(0x%lx, %p, %08x, %p)\n", hKey, pdwReserved, dwFlags, phKey);
1012
1013         orgkey = (PCRYPTKEY)hKey;
1014         if (!orgkey || pdwReserved || !phKey || !orgkey->pProvider || 
1015                 orgkey->pProvider->dwMagic != MAGIC_CRYPTPROV)
1016         {
1017                 SetLastError(ERROR_INVALID_PARAMETER);
1018                 return FALSE;
1019         }
1020
1021         prov = orgkey->pProvider;
1022         if (!prov->pFuncs->pCPDuplicateKey)
1023         {
1024                 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1025                 return FALSE;
1026         }
1027
1028         if ( !(newkey = CRYPT_Alloc(sizeof(CRYPTKEY))) )
1029         {
1030                 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1031                 return FALSE;
1032         }
1033
1034         newkey->pProvider = prov;
1035         if (prov->pFuncs->pCPDuplicateKey(prov->hPrivate, orgkey->hPrivate, pdwReserved, dwFlags, &newkey->hPrivate))
1036         {
1037                 *phKey = (HCRYPTKEY)newkey;
1038                 return TRUE;
1039         }
1040         CRYPT_Free(newkey);
1041         return FALSE;
1042 }
1043
1044 /******************************************************************************
1045  * CryptEncrypt (ADVAPI32.@)
1046  *
1047  * Encrypts data.
1048  *
1049  * PARAMS
1050  *  hKey       [I] Handle to the encryption key.
1051  *  hHash      [I] Handle to a hash object.
1052  *  Final      [I] TRUE if this is the last section to encrypt.
1053  *  dwFlags    [I] Can be CRYPT_OAEP.
1054  *  pbData     [I/O] Data to be encrypted. Contains encrypted data after call.
1055  *  pdwDataLen [I/O] Length of the data to encrypt. Contains the length of the
1056  *                   encrypted data after call.
1057  *  dwBufLen   [I] Length of the input pbData buffer.
1058  *
1059  * RETURNS
1060  *  Success: TRUE
1061  *  Failure: FALSE
1062  *
1063  *  NOTES
1064  *   If pbData is NULL, CryptEncrypt determines stores the number of bytes
1065  *   required for the returned data in pdwDataLen.
1066  */
1067 BOOL WINAPI CryptEncrypt (HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final,
1068                 DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen, DWORD dwBufLen)
1069 {
1070         PCRYPTPROV prov;
1071         PCRYPTKEY key = (PCRYPTKEY)hKey;
1072         PCRYPTHASH hash = (PCRYPTHASH)hHash;
1073
1074         TRACE("(0x%lx, 0x%lx, %d, %08x, %p, %p, %d)\n", hKey, hHash, Final, dwFlags, pbData, pdwDataLen, dwBufLen);
1075
1076         if (!key || !pdwDataLen || !key->pProvider || key->pProvider->dwMagic != MAGIC_CRYPTPROV)
1077         {
1078                 SetLastError(ERROR_INVALID_PARAMETER);
1079                 return FALSE;
1080         }
1081
1082         prov = key->pProvider;
1083         return prov->pFuncs->pCPEncrypt(prov->hPrivate, key->hPrivate, hash ? hash->hPrivate : 0,
1084                         Final, dwFlags, pbData, pdwDataLen, dwBufLen);
1085 }
1086
1087 /******************************************************************************
1088  * CryptEnumProvidersW (ADVAPI32.@)
1089  *
1090  * Returns the next available CSP.
1091  *
1092  * PARAMS
1093  *  dwIndex     [I] Index of the next provider to be enumerated.
1094  *  pdwReserved [I] Reserved for future use and must be NULL.
1095  *  dwFlags     [I] Reserved for future use and must be zero.
1096  *  pdwProvType [O] DWORD designating the type of the provider.
1097  *  pszProvName [O] Buffer that receives data from the provider.
1098  *  pcbProvName [I/O] Specifies the size of pszProvName. Contains the number
1099  *                    of bytes stored in the buffer on return.
1100  *
1101  *  RETURNS
1102  *   Success: TRUE
1103  *   Failure: FALSE
1104  *
1105  *  NOTES
1106  *   If pszProvName is NULL, CryptEnumProvidersW sets the size of the name
1107  *   for memory allocation purposes.
1108  */
1109 BOOL WINAPI CryptEnumProvidersW (DWORD dwIndex, DWORD *pdwReserved,
1110                 DWORD dwFlags, DWORD *pdwProvType, LPWSTR pszProvName, DWORD *pcbProvName)
1111 {
1112         HKEY hKey;
1113         static const WCHAR providerW[] = {
1114                 'S','o','f','t','w','a','r','e','\\',
1115                 'M','i','c','r','o','s','o','f','t','\\',
1116                 'C','r','y','p','t','o','g','r','a','p','h','y','\\',
1117                 'D','e','f','a','u','l','t','s','\\',
1118                 'P','r','o','v','i','d','e','r',0
1119         };
1120         static const WCHAR typeW[] = {'T','y','p','e',0};
1121
1122         TRACE("(%d, %p, %d, %p, %p, %p)\n", dwIndex, pdwReserved, dwFlags,
1123                         pdwProvType, pszProvName, pcbProvName);
1124
1125         if (pdwReserved || !pcbProvName)
1126         {
1127                 SetLastError(ERROR_INVALID_PARAMETER);
1128                 return FALSE;
1129         }
1130         if (dwFlags)
1131         {
1132                 SetLastError(NTE_BAD_FLAGS);
1133                 return FALSE;
1134         }
1135
1136         if (RegOpenKeyW(HKEY_LOCAL_MACHINE, providerW, &hKey))
1137         {
1138                 SetLastError(NTE_FAIL);
1139                 return FALSE;
1140         }
1141
1142         if (!pszProvName)
1143         {
1144                 DWORD numkeys;
1145                 WCHAR *provNameW;
1146                 
1147                 RegQueryInfoKeyW(hKey, NULL, NULL, NULL, &numkeys, pcbProvName,
1148                                  NULL, NULL, NULL, NULL, NULL, NULL);
1149                 
1150                 if (!(provNameW = CRYPT_Alloc(*pcbProvName * sizeof(WCHAR))))
1151                 {
1152                         SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1153                         return FALSE;
1154                 }
1155
1156                 RegEnumKeyExW(hKey, dwIndex, provNameW, pcbProvName, NULL, NULL, NULL, NULL);
1157                 CRYPT_Free(provNameW);
1158                 (*pcbProvName)++;
1159                 *pcbProvName *= sizeof(WCHAR);
1160
1161                 if (dwIndex >= numkeys)
1162                 {
1163                         SetLastError(ERROR_NO_MORE_ITEMS);
1164                         return FALSE;
1165                 }
1166         } else {
1167                 DWORD size = sizeof(DWORD);
1168                 DWORD result;
1169                 HKEY subkey;
1170                 
1171                 result = RegEnumKeyW(hKey, dwIndex, pszProvName, *pcbProvName / sizeof(WCHAR));
1172                 if (result)
1173                 {
1174                         SetLastError(result);
1175                         return FALSE;
1176                 }
1177                 if (RegOpenKeyW(hKey, pszProvName, &subkey))
1178                         return FALSE;
1179                 if (RegQueryValueExW(subkey, typeW, NULL, NULL, (BYTE*)pdwProvType, &size))
1180                         return FALSE;
1181                 RegCloseKey(subkey);
1182         }
1183         RegCloseKey(hKey);
1184         return TRUE;
1185 }
1186
1187 /******************************************************************************
1188  * CryptEnumProvidersA (ADVAPI32.@)
1189  *
1190  * See CryptEnumProvidersW.
1191  */
1192 BOOL WINAPI CryptEnumProvidersA (DWORD dwIndex, DWORD *pdwReserved,
1193                 DWORD dwFlags, DWORD *pdwProvType, LPSTR pszProvName, DWORD *pcbProvName)
1194 {
1195         PWSTR str = NULL;
1196         DWORD bufsize;
1197         BOOL ret; /* = FALSE; */
1198
1199         TRACE("(%d, %p, %08x, %p, %p, %p)\n", dwIndex, pdwReserved, dwFlags,
1200                         pdwProvType, pszProvName, pcbProvName);
1201
1202         if(!CryptEnumProvidersW(dwIndex, pdwReserved, dwFlags, pdwProvType, NULL, &bufsize))
1203                 return FALSE;
1204         if ( pszProvName && !(str = CRYPT_Alloc(bufsize)) )
1205         {
1206                 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1207                 return FALSE;
1208         }
1209         ret = CryptEnumProvidersW(dwIndex, pdwReserved, dwFlags, pdwProvType, str, &bufsize);
1210         if (str)
1211                 CRYPT_UnicodeToANSI(str, &pszProvName, *pcbProvName);
1212         *pcbProvName = bufsize / sizeof(WCHAR);  /* FIXME: not correct */
1213         if (str)
1214         {
1215                 CRYPT_Free(str);
1216                 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
1217                 {
1218                         SetLastError(ERROR_MORE_DATA);
1219                         return FALSE;
1220                 }
1221         }
1222         return ret;
1223 }
1224
1225 /******************************************************************************
1226  * CryptEnumProviderTypesW (ADVAPI32.@)
1227  *
1228  * Retrieves the next type of CSP supported.
1229  *
1230  * PARAMS
1231  *  dwIndex     [I] Index of the next provider to be enumerated.
1232  *  pdwReserved [I] Reserved for future use and must be NULL.
1233  *  dwFlags     [I] Reserved for future use and must be zero.
1234  *  pdwProvType [O] DWORD designating the type of the provider.
1235  *  pszTypeName [O] Buffer that receives data from the provider type.
1236  *  pcbTypeName [I/O] Specifies the size of pszTypeName. Contains the number
1237  *                    of bytes stored in the buffer on return.
1238  *
1239  *  RETURNS
1240  *   Success: TRUE
1241  *   Failure: FALSE
1242  *
1243  *  NOTES
1244  *   If pszTypeName is NULL, CryptEnumProviderTypesW sets the size of the name
1245  *   for memory allocation purposes.
1246  */
1247 BOOL WINAPI CryptEnumProviderTypesW (DWORD dwIndex, DWORD *pdwReserved,
1248                 DWORD dwFlags, DWORD *pdwProvType, LPWSTR pszTypeName, DWORD *pcbTypeName)
1249 {
1250         HKEY hKey, hSubkey;
1251         DWORD keylen, numkeys, dwType;
1252         PWSTR keyname, ch;
1253         DWORD result;
1254         static const WCHAR KEYSTR[] = {
1255                 'S','o','f','t','w','a','r','e','\\',
1256                 'M','i','c','r','o','s','o','f','t','\\',
1257                 'C','r','y','p','t','o','g','r','a','p','h','y','\\',
1258                 'D','e','f','a','u','l','t','s','\\',
1259                 'P','r','o','v','i','d','e','r',' ','T','y','p','e','s',0
1260         };
1261         static const WCHAR typenameW[] = {'T','y','p','e','N','a','m','e',0};
1262
1263         TRACE("(%d, %p, %08x, %p, %p, %p)\n", dwIndex, pdwReserved,
1264                 dwFlags, pdwProvType, pszTypeName, pcbTypeName);
1265
1266         if (pdwReserved || !pdwProvType || !pcbTypeName)
1267         {
1268                 SetLastError(ERROR_INVALID_PARAMETER);
1269                 return FALSE;
1270         }
1271         if (dwFlags)
1272         {
1273                 SetLastError(NTE_BAD_FLAGS);
1274                 return FALSE;
1275         }
1276
1277         if (RegOpenKeyW(HKEY_LOCAL_MACHINE, KEYSTR, &hKey))
1278                 return FALSE;
1279
1280         RegQueryInfoKeyW(hKey, NULL, NULL, NULL, &numkeys, &keylen, NULL, NULL, NULL, NULL, NULL, NULL);
1281         if (dwIndex >= numkeys)
1282         {
1283                 SetLastError(ERROR_NO_MORE_ITEMS);
1284                 return FALSE;
1285         }
1286         keylen++;
1287         if ( !(keyname = CRYPT_Alloc(keylen*sizeof(WCHAR))) )
1288         {
1289                 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1290                 return FALSE;
1291         }
1292         if ( RegEnumKeyW(hKey, dwIndex, keyname, keylen) ) {
1293                 CRYPT_Free(keyname);
1294                 return FALSE;
1295         }
1296         RegOpenKeyW(hKey, keyname, &hSubkey);
1297         ch = keyname + strlenW(keyname);
1298         /* Convert "Type 000" to 0, etc/ */
1299         *pdwProvType = *(--ch) - '0';
1300         *pdwProvType += (*(--ch) - '0') * 10;
1301         *pdwProvType += (*(--ch) - '0') * 100;
1302         CRYPT_Free(keyname);
1303         
1304         result = RegQueryValueExW(hSubkey, typenameW, NULL, &dwType, (LPBYTE)pszTypeName, pcbTypeName);
1305         if (result)
1306         {
1307                 SetLastError(result);
1308                 return FALSE;
1309         }
1310
1311         RegCloseKey(hSubkey);
1312         RegCloseKey(hKey);
1313         return TRUE;
1314 }
1315
1316 /******************************************************************************
1317  * CryptEnumProviderTypesA (ADVAPI32.@)
1318  *
1319  * See CryptEnumProviderTypesW.
1320  */
1321 BOOL WINAPI CryptEnumProviderTypesA (DWORD dwIndex, DWORD *pdwReserved,
1322                 DWORD dwFlags, DWORD *pdwProvType, LPSTR pszTypeName, DWORD *pcbTypeName)
1323 {
1324         PWSTR str = NULL;
1325         DWORD bufsize;
1326         BOOL ret;
1327
1328         TRACE("(%d, %p, %08x, %p, %p, %p)\n", dwIndex, pdwReserved, dwFlags,
1329                         pdwProvType, pszTypeName, pcbTypeName);
1330
1331         if(!CryptEnumProviderTypesW(dwIndex, pdwReserved, dwFlags, pdwProvType, NULL, &bufsize))
1332                 return FALSE;
1333         if ( pszTypeName && !(str = CRYPT_Alloc(bufsize)) )
1334         {
1335                 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1336                 return FALSE;
1337         }
1338         ret = CryptEnumProviderTypesW(dwIndex, pdwReserved, dwFlags, pdwProvType, str, &bufsize);
1339         if (str)
1340                 CRYPT_UnicodeToANSI(str, &pszTypeName, *pcbTypeName);
1341         *pcbTypeName = bufsize / sizeof(WCHAR);
1342         if (str)
1343         {
1344                 CRYPT_Free(str);
1345                 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
1346                 {
1347                         SetLastError(ERROR_MORE_DATA);
1348                         return FALSE;
1349                 }
1350         }
1351         return ret;
1352 }
1353
1354 /******************************************************************************
1355  * CryptExportKey (ADVAPI32.@)
1356  * 
1357  * Exports a cryptographic key from a CSP.
1358  *
1359  * PARAMS
1360  *  hKey       [I] Handle to the key to export.
1361  *  hExpKey    [I] Handle to a cryptographic key of the end user.
1362  *  dwBlobType [I] Type of BLOB to be exported.
1363  *  dwFlags    [I] CRYPT_DESTROYKEY/SSL2_FALLBACK/OAEP.
1364  *  pbData     [O] Buffer to receive BLOB data.
1365  *  pdwDataLen [I/O] Specifies the size of pbData.
1366  *
1367  * RETURNS
1368  *  Success: TRUE
1369  *  Failure: FALSE
1370  *
1371  * NOTES
1372  *  if pbData is NULL, CryptExportKey sets pdwDataLen as the size of the
1373  *  buffer needed to hold the BLOB.
1374  */
1375 BOOL WINAPI CryptExportKey (HCRYPTKEY hKey, HCRYPTKEY hExpKey, DWORD dwBlobType,
1376                 DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
1377 {
1378         PCRYPTPROV prov;
1379         PCRYPTKEY key = (PCRYPTKEY)hKey, expkey = (PCRYPTKEY)hExpKey;
1380
1381         TRACE("(0x%lx, 0x%lx, %d, %08x, %p, %p)\n", hKey, hExpKey, dwBlobType, dwFlags, pbData, pdwDataLen);
1382
1383         if (!key || !pdwDataLen || !key->pProvider || key->pProvider->dwMagic != MAGIC_CRYPTPROV)
1384         {
1385                 SetLastError(ERROR_INVALID_PARAMETER);
1386                 return FALSE;
1387         }
1388
1389         prov = key->pProvider;
1390         return prov->pFuncs->pCPExportKey(prov->hPrivate, key->hPrivate, expkey ? expkey->hPrivate : 0,
1391                         dwBlobType, dwFlags, pbData, pdwDataLen);
1392 }
1393
1394 /******************************************************************************
1395  * CryptGenKey (ADVAPI32.@)
1396  *
1397  * Generates a random cryptographic session key or a pub/priv key pair.
1398  *
1399  * PARAMS
1400  *  hProv   [I] Handle to a CSP.
1401  *  Algid   [I] Algorithm to use to make key.
1402  *  dwFlags [I] Specifies type of key to make.
1403  *  phKey   [I] Address of the handle to which the new key is copied.
1404  *
1405  *  RETURNS
1406  *   Success: TRUE
1407  *   Failure: FALSE
1408  */
1409 BOOL WINAPI CryptGenKey (HCRYPTPROV hProv, ALG_ID Algid, DWORD dwFlags, HCRYPTKEY *phKey)
1410 {
1411         PCRYPTPROV prov = (PCRYPTPROV)hProv;
1412         PCRYPTKEY key;
1413
1414         TRACE("(0x%lx, %d, %08x, %p)\n", hProv, Algid, dwFlags, phKey);
1415
1416         if (!prov)
1417         {
1418                 SetLastError(ERROR_INVALID_HANDLE);
1419                 return FALSE;
1420         }
1421         if (!phKey || !prov || prov->dwMagic != MAGIC_CRYPTPROV)
1422         {
1423                 SetLastError(ERROR_INVALID_PARAMETER);
1424                 return FALSE;
1425         }
1426         if ( !(key = CRYPT_Alloc(sizeof(CRYPTKEY))) )
1427         {
1428                 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1429                 return FALSE;
1430         }
1431
1432         key->pProvider = prov;
1433
1434         if (prov->pFuncs->pCPGenKey(prov->hPrivate, Algid, dwFlags, &key->hPrivate))
1435         {
1436             *phKey = (HCRYPTKEY)key;
1437             return TRUE;
1438         }
1439
1440         /* CSP error! */
1441         CRYPT_Free(key);
1442         return FALSE;
1443 }
1444
1445 /******************************************************************************
1446  * CryptGetDefaultProviderW (ADVAPI32.@)
1447  *
1448  * Finds the default CSP of a certain provider type.
1449  *
1450  * PARAMS
1451  *  dwProvType  [I] Provider type to look for.
1452  *  pdwReserved [I] Reserved for future use and must be NULL.
1453  *  dwFlags     [I] CRYPT_MACHINE_DEFAULT/USER_DEFAULT
1454  *  pszProvName [O] Name of the default CSP.
1455  *  pcbProvName [I/O] Size of pszProvName
1456  *
1457  * RETURNS
1458  *  Success: TRUE
1459  *  Failure: FALSE
1460  *
1461  * NOTES
1462  *  If pszProvName is NULL, pcbProvName will hold the size of the buffer for
1463  *  memory allocation purposes on return.
1464  */
1465 BOOL WINAPI CryptGetDefaultProviderW (DWORD dwProvType, DWORD *pdwReserved,
1466                 DWORD dwFlags, LPWSTR pszProvName, DWORD *pcbProvName)
1467 {
1468         HKEY hKey;
1469         PWSTR keyname;
1470         DWORD result;
1471         static const WCHAR nameW[] = {'N','a','m','e',0};
1472
1473         if (pdwReserved || !pcbProvName)
1474         {
1475                 SetLastError(ERROR_INVALID_PARAMETER);
1476                 return FALSE;
1477         }
1478         if (dwFlags & ~(CRYPT_USER_DEFAULT | CRYPT_MACHINE_DEFAULT))
1479         {
1480                 SetLastError(NTE_BAD_FLAGS);
1481                 return FALSE;
1482         }
1483         if (dwProvType > 999)
1484         {
1485                 SetLastError(NTE_BAD_PROV_TYPE);
1486                 return FALSE;
1487         }
1488         if ( !(keyname = CRYPT_GetTypeKeyName(dwProvType, dwFlags & CRYPT_USER_DEFAULT)) )
1489         {
1490                 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1491                 return FALSE;
1492         }
1493         if (RegOpenKeyW((dwFlags & CRYPT_USER_DEFAULT) ?  HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE ,keyname, &hKey))
1494         {
1495                 CRYPT_Free(keyname);
1496                 SetLastError(NTE_PROV_TYPE_NOT_DEF);
1497                 return FALSE;
1498         }
1499         CRYPT_Free(keyname);
1500         
1501         result = RegQueryValueExW(hKey, nameW, NULL, NULL, (LPBYTE)pszProvName, pcbProvName); 
1502         if (result)
1503         {
1504                 if (result != ERROR_MORE_DATA)
1505                         SetLastError(NTE_PROV_TYPE_ENTRY_BAD);
1506                 else
1507                         SetLastError(result);
1508                 
1509                 return FALSE;
1510         }
1511         
1512         RegCloseKey(hKey);
1513         return TRUE;
1514 }
1515
1516 /******************************************************************************
1517  * CryptGetDefaultProviderA (ADVAPI32.@)
1518  *
1519  * See CryptGetDefaultProviderW.
1520  */
1521 BOOL WINAPI CryptGetDefaultProviderA (DWORD dwProvType, DWORD *pdwReserved,
1522                 DWORD dwFlags, LPSTR pszProvName, DWORD *pcbProvName)
1523 {
1524         PWSTR str = NULL;
1525         DWORD bufsize;
1526         BOOL ret = FALSE;
1527
1528         TRACE("(%d, %p, %08x, %p, %p)\n", dwProvType, pdwReserved, dwFlags, pszProvName, pcbProvName);
1529
1530         CryptGetDefaultProviderW(dwProvType, pdwReserved, dwFlags, NULL, &bufsize);
1531         if ( pszProvName && !(str = CRYPT_Alloc(bufsize)) )
1532         {
1533                 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1534                 return FALSE;
1535         }
1536         ret = CryptGetDefaultProviderW(dwProvType, pdwReserved, dwFlags, str, &bufsize);
1537         if (str)
1538                 CRYPT_UnicodeToANSI(str, &pszProvName, *pcbProvName);
1539         *pcbProvName = bufsize / sizeof(WCHAR);
1540         if (str)
1541         {
1542                 CRYPT_Free(str);
1543                 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
1544                 {
1545                         SetLastError(ERROR_MORE_DATA);
1546                         return FALSE;
1547                 }
1548         }
1549         return ret;
1550 }
1551
1552 /******************************************************************************
1553  * CryptGetHashParam (ADVAPI32.@)
1554  *
1555  * Retrieves data that controls the operations of a hash object.
1556  *
1557  * PARAMS
1558  *  hHash      [I] Handle of the hash object to question.
1559  *  dwParam    [I] Query type.
1560  *  pbData     [O] Buffer that receives the value data.
1561  *  pdwDataLen [I/O] Size of the pbData buffer.
1562  *  dwFlags    [I] Reserved for future use and must be zero.
1563  *
1564  * RETURNS
1565  *  Success: TRUE
1566  *  Failure: FALSE
1567  *
1568  * NOTES
1569  *  If pbData is NULL, pdwDataLen will contain the length required.
1570  */
1571 BOOL WINAPI CryptGetHashParam (HCRYPTHASH hHash, DWORD dwParam, BYTE *pbData,
1572                 DWORD *pdwDataLen, DWORD dwFlags)
1573 {
1574         PCRYPTPROV prov;
1575         PCRYPTHASH hash = (PCRYPTHASH)hHash;
1576
1577         TRACE("(0x%lx, %d, %p, %p, %08x)\n", hHash, dwParam, pbData, pdwDataLen, dwFlags);
1578
1579         if (!hash || !pdwDataLen || !hash->pProvider || hash->pProvider->dwMagic != MAGIC_CRYPTPROV)
1580         {
1581                 SetLastError(ERROR_INVALID_PARAMETER);
1582                 return FALSE;
1583         }
1584
1585         prov = hash->pProvider;
1586         return prov->pFuncs->pCPGetHashParam(prov->hPrivate, hash->hPrivate, dwParam,
1587                         pbData, pdwDataLen, dwFlags);
1588 }
1589
1590 /******************************************************************************
1591  * CryptGetKeyParam (ADVAPI32.@)
1592  *
1593  * Retrieves data that controls the operations of a key.
1594  *
1595  * PARAMS
1596  *  hKey       [I] Handle to they key in question.
1597  *  dwParam    [I] Specifies query type.
1598  *  pbData     [O] Sequence of bytes to receive data.
1599  *  pdwDataLen [I/O] Size of pbData.
1600  *  dwFlags    [I] Reserved for future use and must be zero.
1601  *
1602  * RETURNS
1603  *  Success: TRUE
1604  *  Failure: FALSE
1605  *
1606  * NOTES
1607  *  If pbData is NULL, pdwDataLen is set to the needed length of the buffer.
1608  */
1609 BOOL WINAPI CryptGetKeyParam (HCRYPTKEY hKey, DWORD dwParam, BYTE *pbData,
1610                 DWORD *pdwDataLen, DWORD dwFlags)
1611 {
1612         PCRYPTPROV prov;
1613         PCRYPTKEY key = (PCRYPTKEY)hKey;
1614
1615         TRACE("(0x%lx, %d, %p, %p, %08x)\n", hKey, dwParam, pbData, pdwDataLen, dwFlags);
1616
1617         if (!key || !pdwDataLen || !key->pProvider || key->pProvider->dwMagic != MAGIC_CRYPTPROV)
1618         {
1619                 SetLastError(ERROR_INVALID_PARAMETER);
1620                 return FALSE;
1621         }
1622
1623         prov = key->pProvider;
1624         return prov->pFuncs->pCPGetKeyParam(prov->hPrivate, key->hPrivate, dwParam,
1625                         pbData, pdwDataLen, dwFlags);
1626 }
1627
1628 /******************************************************************************
1629  * CryptGetProvParam (ADVAPI32.@)
1630  *
1631  * Retrieves parameters that control the operations of a CSP.
1632  *
1633  * PARAMS
1634  *  hProv      [I] Handle of the CSP in question.
1635  *  dwParam    [I] Specifies query type.
1636  *  pbData     [O] Buffer to receive the data.
1637  *  pdwDataLen [I/O] Size of pbData.
1638  *  dwFlags    [I] see MSDN Docs.
1639  *
1640  * RETURNS
1641  *  Success: TRUE
1642  *  Failure: FALSE
1643  *
1644  * NOTES
1645  *  If pbData is NULL, pdwDataLen is set to the needed buffer length.
1646  */
1647 BOOL WINAPI CryptGetProvParam (HCRYPTPROV hProv, DWORD dwParam, BYTE *pbData,
1648                 DWORD *pdwDataLen, DWORD dwFlags)
1649 {
1650         PCRYPTPROV prov = (PCRYPTPROV)hProv;
1651
1652         TRACE("(0x%lx, %d, %p, %p, %08x)\n", hProv, dwParam, pbData, pdwDataLen, dwFlags);
1653
1654         if (!prov || prov->dwMagic != MAGIC_CRYPTPROV)
1655         {
1656                 SetLastError(ERROR_INVALID_PARAMETER);
1657                 return FALSE;
1658         }
1659
1660         return prov->pFuncs->pCPGetProvParam(prov->hPrivate, dwParam, pbData, pdwDataLen, dwFlags);
1661 }
1662
1663 /******************************************************************************
1664  * CryptGetUserKey (ADVAPI32.@)
1665  *
1666  * Gets a handle of one of a user's two public/private key pairs.
1667  *
1668  * PARAMS
1669  *  hProv     [I] Handle of a CSP.
1670  *  dwKeySpec [I] Private key to use.
1671  *  phUserKey [O] Pointer to the handle of the retrieved keys.
1672  *
1673  * RETURNS
1674  *  Success: TRUE
1675  *  Failure: FALSE
1676  */
1677 BOOL WINAPI CryptGetUserKey (HCRYPTPROV hProv, DWORD dwKeySpec, HCRYPTKEY *phUserKey)
1678 {
1679         PCRYPTPROV prov = (PCRYPTPROV)hProv;
1680         PCRYPTKEY key;
1681
1682         TRACE("(0x%lx, %d, %p)\n", hProv, dwKeySpec, phUserKey);
1683
1684         if (!prov)
1685         {
1686                 SetLastError(ERROR_INVALID_HANDLE);
1687                 return FALSE;
1688         }
1689         if (!phUserKey || prov->dwMagic != MAGIC_CRYPTPROV)
1690         {
1691                 SetLastError(ERROR_INVALID_PARAMETER);
1692                 return FALSE;
1693         }
1694         if ( !(key = CRYPT_Alloc(sizeof(CRYPTKEY))) )
1695         {
1696                 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1697                 return FALSE;
1698         }
1699
1700         key->pProvider = prov;
1701
1702         if (prov->pFuncs->pCPGetUserKey(prov->hPrivate, dwKeySpec, &key->hPrivate))
1703         {
1704             *phUserKey = (HCRYPTKEY)key;
1705             return TRUE;
1706         }
1707
1708         /* CSP Error */
1709         CRYPT_Free(key);
1710         *phUserKey = 0;
1711         return FALSE;
1712 }
1713
1714 /******************************************************************************
1715  * CryptHashData (ADVAPI32.@)
1716  *
1717  * Adds data to a hash object.
1718  *
1719  * PARAMS
1720  *  hHash     [I] Handle of the hash object.
1721  *  pbData    [I] Buffer of data to be hashed.
1722  *  dwDataLen [I] Number of bytes to add.
1723  *  dwFlags   [I] Can be CRYPT_USERDATA
1724  *
1725  * RETURNS
1726  *  Success: TRUE
1727  *  Failure: FALSE
1728  */
1729 BOOL WINAPI CryptHashData (HCRYPTHASH hHash, const BYTE *pbData, DWORD dwDataLen, DWORD dwFlags)
1730 {
1731         PCRYPTHASH hash = (PCRYPTHASH)hHash;
1732         PCRYPTPROV prov;
1733
1734         TRACE("(0x%lx, %p, %d, %08x)\n", hHash, pbData, dwDataLen, dwFlags);
1735
1736         if (!hash)
1737         {
1738                 SetLastError(ERROR_INVALID_HANDLE);
1739                 return FALSE;
1740         }
1741         if (!hash->pProvider || hash->pProvider->dwMagic != MAGIC_CRYPTPROV)
1742         {
1743                 SetLastError(ERROR_INVALID_PARAMETER);
1744                 return FALSE;
1745         }
1746
1747         prov = hash->pProvider;
1748         return prov->pFuncs->pCPHashData(prov->hPrivate, hash->hPrivate, pbData, dwDataLen, dwFlags);
1749 }
1750
1751 /******************************************************************************
1752  * CryptHashSessionKey (ADVAPI32.@)
1753  *
1754  * Compute the cryptographic hash of a session key object.
1755  *
1756  * PARAMS 
1757  *  hHash   [I] Handle to the hash object.
1758  *  hKey    [I] Handle to the key to be hashed.
1759  *  dwFlags [I] Can be CRYPT_LITTLE_ENDIAN.
1760  *
1761  * RETURNS
1762  *  Success: TRUE
1763  *  Failure: FALSE
1764  */
1765 BOOL WINAPI CryptHashSessionKey (HCRYPTHASH hHash, HCRYPTKEY hKey, DWORD dwFlags)
1766 {
1767         PCRYPTHASH hash = (PCRYPTHASH)hHash;
1768         PCRYPTKEY key = (PCRYPTKEY)hKey;
1769         PCRYPTPROV prov;
1770
1771         TRACE("(0x%lx, 0x%lx, %08x)\n", hHash, hKey, dwFlags);
1772
1773         if (!hash || !key)
1774         {
1775                 SetLastError(ERROR_INVALID_HANDLE);
1776                 return FALSE;
1777         }
1778
1779         if (!hash->pProvider || hash->pProvider->dwMagic != MAGIC_CRYPTPROV)
1780         {
1781                 SetLastError(ERROR_INVALID_PARAMETER);
1782                 return FALSE;
1783         }
1784
1785         prov = hash->pProvider;
1786         return prov->pFuncs->pCPHashSessionKey(prov->hPrivate, hash->hPrivate, key->hPrivate, dwFlags);
1787 }
1788
1789 /******************************************************************************
1790  * CryptImportKey (ADVAPI32.@)
1791  *
1792  * Transfer a cryptographic key from a key BLOB into a cryptographic service provider (CSP).
1793  *
1794  * PARAMS
1795  *  hProv     [I] Handle of a CSP.
1796  *  pbData    [I] Contains the key to be imported.
1797  *  dwDataLen [I] Length of the key.
1798  *  hPubKey   [I] Cryptographic key that decrypts pdData
1799  *  dwFlags   [I] Used only with a public/private key pair.
1800  *  phKey     [O] Imported key.
1801  *
1802  * RETURNS
1803  *  Success: TRUE
1804  *  Failure: FALSE
1805  */
1806 BOOL WINAPI CryptImportKey (HCRYPTPROV hProv, CONST BYTE *pbData, DWORD dwDataLen,
1807                 HCRYPTKEY hPubKey, DWORD dwFlags, HCRYPTKEY *phKey)
1808 {
1809         PCRYPTPROV prov = (PCRYPTPROV)hProv;
1810         PCRYPTKEY pubkey = (PCRYPTKEY)hPubKey, importkey;
1811
1812         TRACE("(0x%lx, %p, %d, 0x%lx, %08x, %p)\n", hProv, pbData, dwDataLen, hPubKey, dwFlags, phKey);
1813
1814         if (!prov || !pbData || !dwDataLen || !phKey || prov->dwMagic != MAGIC_CRYPTPROV)
1815         {
1816                 SetLastError(ERROR_INVALID_PARAMETER);
1817                 return FALSE;
1818         }
1819
1820         if ( !(importkey = CRYPT_Alloc(sizeof(CRYPTKEY))) )
1821         {
1822                 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1823                 return FALSE;
1824         }
1825
1826         importkey->pProvider = prov;
1827         if (prov->pFuncs->pCPImportKey(prov->hPrivate, pbData, dwDataLen,
1828                         pubkey ? pubkey->hPrivate : 0, dwFlags, &importkey->hPrivate))
1829         {
1830                 *phKey = (HCRYPTKEY)importkey;
1831                 return TRUE;
1832         }
1833
1834         CRYPT_Free(importkey);
1835         return FALSE;
1836 }
1837
1838 /******************************************************************************
1839  * CryptSignHashW (ADVAPI32.@)
1840  *
1841  * Signs data.
1842  *
1843  * PARAMS
1844  *  hHash        [I] Handle of the hash object to be signed.
1845  *  dwKeySpec    [I] Private key to use.
1846  *  sDescription [I] Should be NULL.
1847  *  dwFlags      [I] CRYPT_NOHASHOID/X931_FORMAT.
1848  *  pbSignature  [O] Buffer of the signature data.
1849  *  pdwSigLen    [I/O] Size of the pbSignature buffer.
1850  *
1851  * RETURNS
1852  *  Success: TRUE
1853  *  Failure: FALSE
1854  *
1855  * NOTES
1856  *  Because of security flaws sDescription should not be used and should thus be
1857  *  NULL. It is supported only for compatibility with Microsoft's Cryptographic
1858  *  Providers.
1859  */
1860 BOOL WINAPI CryptSignHashW (HCRYPTHASH hHash, DWORD dwKeySpec, LPCWSTR sDescription,
1861                 DWORD dwFlags, BYTE *pbSignature, DWORD *pdwSigLen)
1862 {
1863         PCRYPTHASH hash = (PCRYPTHASH)hHash;
1864         PCRYPTPROV prov;
1865
1866         TRACE("(0x%lx, %d, %s, %08x, %p, %p)\n", 
1867                 hHash, dwKeySpec, debugstr_w(sDescription), dwFlags, pbSignature, pdwSigLen);
1868
1869         if (!hash)
1870         {
1871                 SetLastError(ERROR_INVALID_HANDLE);
1872                 return FALSE;
1873         }
1874         if (!pdwSigLen || !hash->pProvider || hash->pProvider->dwMagic != MAGIC_CRYPTPROV)
1875         {
1876                 SetLastError(ERROR_INVALID_PARAMETER);
1877                 return FALSE;
1878         }
1879
1880         prov = hash->pProvider;
1881         return prov->pFuncs->pCPSignHash(prov->hPrivate, hash->hPrivate, dwKeySpec, sDescription,
1882                 dwFlags, pbSignature, pdwSigLen);
1883 }
1884
1885 /******************************************************************************
1886  * CryptSignHashA (ADVAPI32.@)
1887  *
1888  * See CryptSignHashW.
1889  */
1890 BOOL WINAPI CryptSignHashA (HCRYPTHASH hHash, DWORD dwKeySpec, LPCSTR sDescription,
1891                 DWORD dwFlags, BYTE *pbSignature, DWORD *pdwSigLen)
1892 {
1893         LPWSTR wsDescription;
1894         BOOL result;
1895
1896         TRACE("(0x%lx, %d, %s, %08x, %p, %p)\n", 
1897                 hHash, dwKeySpec, debugstr_a(sDescription), dwFlags, pbSignature, pdwSigLen);
1898
1899         CRYPT_ANSIToUnicode(sDescription, &wsDescription, -1);
1900         result = CryptSignHashW(hHash, dwKeySpec, wsDescription, dwFlags, pbSignature, pdwSigLen);
1901         CRYPT_Free(wsDescription);
1902
1903         return result;
1904 }
1905
1906 /******************************************************************************
1907  * CryptSetHashParam (ADVAPI32.@)
1908  *
1909  * Customizes the operations of a hash object.
1910  *
1911  * PARAMS
1912  *  hHash   [I] Handle of the hash object to set parameters.
1913  *  dwParam [I] HP_HMAC_INFO/HASHVAL.
1914  *  pbData  [I] Value data buffer.
1915  *  dwFlags [I] Reserved for future use and must be zero.
1916  *
1917  * RETURNS
1918  *  Success: TRUE
1919  *  Failure: FALSE
1920  */
1921 BOOL WINAPI CryptSetHashParam (HCRYPTHASH hHash, DWORD dwParam, CONST BYTE *pbData, DWORD dwFlags)
1922 {
1923         PCRYPTPROV prov;
1924         PCRYPTHASH hash = (PCRYPTHASH)hHash;
1925
1926         TRACE("(0x%lx, %d, %p, %08x)\n", hHash, dwParam, pbData, dwFlags);
1927
1928         if (!hash || !pbData || !hash->pProvider || hash->pProvider->dwMagic != MAGIC_CRYPTPROV)
1929         {
1930                 SetLastError(ERROR_INVALID_PARAMETER);
1931                 return FALSE;
1932         }
1933
1934         prov = hash->pProvider;
1935         return prov->pFuncs->pCPSetHashParam(prov->hPrivate, hash->hPrivate,
1936                         dwParam, pbData, dwFlags);
1937 }
1938
1939 /******************************************************************************
1940  * CryptSetKeyParam (ADVAPI32.@)
1941  *
1942  * Customizes a session key's operations.
1943  *
1944  * PARAMS
1945  *  hKey    [I] Handle to the key to set values.
1946  *  dwParam [I] See MSDN Doc.
1947  *  pbData  [I] Buffer of values to set.
1948  *  dwFlags [I] Only used when dwParam == KP_ALGID.
1949  *
1950  * RETURNS
1951  *  Success: TRUE
1952  *  Failure: FALSE
1953  */
1954 BOOL WINAPI CryptSetKeyParam (HCRYPTKEY hKey, DWORD dwParam, CONST BYTE *pbData, DWORD dwFlags)
1955 {
1956         PCRYPTPROV prov;
1957         PCRYPTKEY key = (PCRYPTKEY)hKey;
1958
1959         TRACE("(0x%lx, %d, %p, %08x)\n", hKey, dwParam, pbData, dwFlags);
1960
1961         if (!key || !pbData || !key->pProvider || key->pProvider->dwMagic != MAGIC_CRYPTPROV)
1962         {
1963                 SetLastError(ERROR_INVALID_PARAMETER);
1964                 return FALSE;
1965         }
1966
1967         prov = key->pProvider;
1968         return prov->pFuncs->pCPSetKeyParam(prov->hPrivate, key->hPrivate,
1969                         dwParam, pbData, dwFlags);
1970 }
1971
1972 /******************************************************************************
1973  * CryptSetProviderA (ADVAPI32.@)
1974  *
1975  * Specifies the current user's default CSP.
1976  *
1977  * PARAMS
1978  *  pszProvName [I] Name of the new default CSP.
1979  *  dwProvType  [I] Provider type of the CSP.
1980  *
1981  * RETURNS
1982  *  Success: TRUE
1983  *  Failure: FALSE
1984  */
1985 BOOL WINAPI CryptSetProviderA (LPCSTR pszProvName, DWORD dwProvType)
1986 {
1987         TRACE("(%s, %d)\n", pszProvName, dwProvType);
1988         return CryptSetProviderExA(pszProvName, dwProvType, NULL, CRYPT_USER_DEFAULT);
1989 }
1990
1991 /******************************************************************************
1992  * CryptSetProviderW (ADVAPI32.@)
1993  *
1994  * See CryptSetProviderA.
1995  */
1996 BOOL WINAPI CryptSetProviderW (LPCWSTR pszProvName, DWORD dwProvType)
1997 {
1998         TRACE("(%s, %d)\n", debugstr_w(pszProvName), dwProvType);
1999         return CryptSetProviderExW(pszProvName, dwProvType, NULL, CRYPT_USER_DEFAULT);
2000 }
2001
2002 /******************************************************************************
2003  * CryptSetProviderExW (ADVAPI32.@)
2004  *
2005  * Specifies the default CSP.
2006  *
2007  * PARAMS
2008  *  pszProvName [I] Name of the new default CSP.
2009  *  dwProvType  [I] Provider type of the CSP.
2010  *  pdwReserved [I] Reserved for future use and must be NULL.
2011  *  dwFlags     [I] See MSDN Doc.
2012  *
2013  * RETURNS
2014  *  Success: TRUE
2015  *  Failure: FALSE
2016  */
2017 BOOL WINAPI CryptSetProviderExW (LPCWSTR pszProvName, DWORD dwProvType, DWORD *pdwReserved, DWORD dwFlags)
2018 {
2019         HKEY hProvKey, hTypeKey;
2020         PWSTR keyname;
2021         static const WCHAR nameW[] = {'N','a','m','e',0};
2022
2023         TRACE("(%s, %d, %p, %08x)\n", debugstr_w(pszProvName), dwProvType, pdwReserved, dwFlags);
2024
2025         if (!pszProvName || pdwReserved)
2026         {
2027                 SetLastError(ERROR_INVALID_PARAMETER);
2028                 return FALSE;
2029         }
2030         if (dwProvType > MAXPROVTYPES)
2031         {
2032                 SetLastError(NTE_BAD_PROV_TYPE);
2033                 return FALSE;
2034         }
2035         if (dwFlags & ~(CRYPT_MACHINE_DEFAULT | CRYPT_USER_DEFAULT | CRYPT_DELETE_DEFAULT)
2036                         || dwFlags == CRYPT_DELETE_DEFAULT)
2037         {
2038                 SetLastError(NTE_BAD_FLAGS);
2039                 return FALSE;
2040         }
2041
2042         if (!(keyname = CRYPT_GetTypeKeyName(dwProvType, dwFlags & CRYPT_USER_DEFAULT)))
2043         {
2044                 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
2045                 return FALSE;
2046         }
2047         if (RegOpenKeyW((dwFlags & CRYPT_USER_DEFAULT) ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE,
2048                 keyname, &hTypeKey))
2049         {
2050                 CRYPT_Free(keyname);
2051                 SetLastError(NTE_BAD_PROVIDER);
2052                 return FALSE;
2053         }
2054         CRYPT_Free(keyname);
2055         
2056         if (dwFlags & CRYPT_DELETE_DEFAULT)
2057         {
2058                 RegDeleteValueW(hTypeKey, nameW);
2059         }
2060         else
2061         {
2062                 if (!(keyname = CRYPT_GetProvKeyName(pszProvName)))
2063                 {
2064                         RegCloseKey(hTypeKey);
2065                         SetLastError(ERROR_NOT_ENOUGH_MEMORY);
2066                         return FALSE;
2067                 }
2068                 if (RegOpenKeyW((dwFlags & CRYPT_USER_DEFAULT) ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE,
2069                         keyname, &hProvKey))
2070                 {
2071                         CRYPT_Free(keyname);
2072                         RegCloseKey(hTypeKey);
2073                         SetLastError(NTE_BAD_PROVIDER);
2074                         return FALSE;
2075                 }
2076                 CRYPT_Free(keyname);
2077                 
2078                 if (RegSetValueExW(hTypeKey, nameW, 0, REG_SZ, (const BYTE *)pszProvName,
2079                         (strlenW(pszProvName) + 1)*sizeof(WCHAR)))
2080                 {
2081                         RegCloseKey(hTypeKey);
2082                         RegCloseKey(hProvKey);
2083                         return FALSE;
2084                 }
2085                 
2086                 RegCloseKey(hProvKey);
2087         }
2088         RegCloseKey(hTypeKey);
2089
2090         return TRUE;
2091 }
2092
2093 /******************************************************************************
2094  * CryptSetProviderExA (ADVAPI32.@)
2095  *
2096  * See CryptSetProviderExW.
2097  */
2098 BOOL WINAPI CryptSetProviderExA (LPCSTR pszProvName, DWORD dwProvType, DWORD *pdwReserved, DWORD dwFlags)
2099 {
2100         BOOL ret = FALSE;
2101         PWSTR str = NULL;
2102
2103         TRACE("(%s, %d, %p, %08x)\n", pszProvName, dwProvType, pdwReserved, dwFlags);
2104
2105         if (CRYPT_ANSIToUnicode(pszProvName, &str, -1))
2106         {
2107                 ret = CryptSetProviderExW(str, dwProvType, pdwReserved, dwFlags);
2108                 CRYPT_Free(str);
2109         }
2110         return ret;
2111 }
2112
2113 /******************************************************************************
2114  * CryptSetProvParam (ADVAPI32.@)
2115  *
2116  * Customizes the operations of a CSP.
2117  *
2118  * PARAMS
2119  *  hProv   [I] Handle of a CSP.
2120  *  dwParam [I] See MSDN Doc.
2121  *  pbData  [I] Buffer that contains a value to set as a parameter.
2122  *  dwFlags [I] if dwParam is PP_USE_HARDWARE_RNG, dwFlags must be zero.
2123  *
2124  * RETURNS
2125  *  Success: TRUE
2126  *  Failure: FALSE
2127  */
2128 BOOL WINAPI CryptSetProvParam (HCRYPTPROV hProv, DWORD dwParam, CONST BYTE *pbData, DWORD dwFlags)
2129 {
2130         PCRYPTPROV prov = (PCRYPTPROV)hProv;
2131
2132         TRACE("(0x%lx, %d, %p, %08x)\n", hProv, dwParam, pbData, dwFlags);
2133
2134         if (!prov)
2135         {
2136                 SetLastError(ERROR_INVALID_HANDLE);
2137                 return FALSE;
2138         }
2139         if (prov->dwMagic != MAGIC_CRYPTPROV)
2140         {
2141                 SetLastError(ERROR_INVALID_PARAMETER);
2142                 return FALSE;
2143         }
2144         if (dwFlags & PP_USE_HARDWARE_RNG)
2145         {
2146                 FIXME("PP_USE_HARDWARE_RNG: What do I do with this?\n");
2147                 FIXME("\tLetting the CSP decide.\n");
2148         }
2149         if (dwFlags & PP_CLIENT_HWND)
2150         {
2151                 /* FIXME: Should verify the parameter */
2152                 if (pbData /* && IsWindow((HWND)pbData) */)
2153                 {
2154                         crypt_hWindow = (HWND)(pbData);
2155                         return TRUE;
2156                 } else {
2157                         SetLastError(ERROR_INVALID_PARAMETER);
2158                         return FALSE;
2159                 }
2160         }
2161         /* All other flags go to the CSP */
2162         return prov->pFuncs->pCPSetProvParam(prov->hPrivate, dwParam, pbData, dwFlags);
2163 }
2164
2165 /******************************************************************************
2166  * CryptVerifySignatureW (ADVAPI32.@)
2167  *
2168  * Verifies the signature of a hash object.
2169  *
2170  * PARAMS
2171  *  hHash        [I] Handle of the hash object to verify.
2172  *  pbSignature  [I] Signature data to verify.
2173  *  dwSigLen     [I] Size of pbSignature.
2174  *  hPubKey      [I] Handle to the public key to authenticate signature.
2175  *  sDescription [I] Should be NULL.
2176  *  dwFlags      [I] See MSDN doc.
2177  *
2178  * RETURNS
2179  *  Success: TRUE
2180  *  Failure: FALSE
2181  * 
2182  * NOTES
2183  *  Because of security flaws sDescription should not be used and should thus be
2184  *  NULL. It is supported only for compatibility with Microsoft's Cryptographic
2185  *  Providers.
2186  */
2187 BOOL WINAPI CryptVerifySignatureW (HCRYPTHASH hHash, CONST BYTE *pbSignature, DWORD dwSigLen,
2188                 HCRYPTKEY hPubKey, LPCWSTR sDescription, DWORD dwFlags)
2189 {
2190         PCRYPTHASH hash = (PCRYPTHASH)hHash;
2191         PCRYPTKEY key = (PCRYPTKEY)hPubKey;
2192         PCRYPTPROV prov;
2193
2194         TRACE("(0x%lx, %p, %d, 0x%lx, %s, %08x)\n", hHash, pbSignature,
2195                         dwSigLen, hPubKey, debugstr_w(sDescription), dwFlags);
2196
2197         if (!hash || !key ||
2198             !hash->pProvider || hash->pProvider->dwMagic != MAGIC_CRYPTPROV ||
2199             !key->pProvider || key->pProvider->dwMagic != MAGIC_CRYPTPROV)
2200         {
2201                 SetLastError(ERROR_INVALID_PARAMETER);
2202                 return FALSE;
2203         }
2204                 
2205         prov = hash->pProvider;
2206         return prov->pFuncs->pCPVerifySignature(prov->hPrivate, hash->hPrivate, pbSignature, dwSigLen,
2207                 key->hPrivate, sDescription, dwFlags);
2208 }
2209
2210 /******************************************************************************
2211  * CryptVerifySignatureA (ADVAPI32.@)
2212  *
2213  * See CryptVerifySignatureW.
2214  */
2215 BOOL WINAPI CryptVerifySignatureA (HCRYPTHASH hHash, CONST BYTE *pbSignature, DWORD dwSigLen,
2216                 HCRYPTKEY hPubKey, LPCSTR sDescription, DWORD dwFlags)
2217 {
2218         LPWSTR wsDescription;
2219         BOOL result;
2220
2221         TRACE("(0x%lx, %p, %d, 0x%lx, %s, %08x)\n", hHash, pbSignature,
2222                         dwSigLen, hPubKey, debugstr_a(sDescription), dwFlags);
2223
2224         CRYPT_ANSIToUnicode(sDescription, &wsDescription, -1);
2225         result = CryptVerifySignatureW(hHash, pbSignature, dwSigLen, hPubKey, wsDescription, dwFlags);
2226         CRYPT_Free(wsDescription);
2227
2228         return result;
2229 }
2230
2231 /******************************************************************************
2232  * SystemFunction030   (ADVAPI32.@)
2233  *
2234  * Tests if two blocks of 16 bytes are equal
2235  *
2236  * PARAMS
2237  *  b1,b2   [I] block of 16 bytes
2238  *
2239  * RETURNS
2240  *  TRUE  if blocks are the same
2241  *  FALSE if blocks are different
2242  */
2243 BOOL WINAPI SystemFunction030(LPCVOID b1, LPCVOID b2)
2244 {
2245     return !memcmp(b1, b2, 0x10);
2246 }
2247
2248 /******************************************************************************
2249  * SystemFunction035   (ADVAPI32.@)
2250  *
2251  * Described here:
2252 http://disc.server.com/discussion.cgi?disc=148775;article=942;title=Coding%2FASM%2FSystem
2253  *
2254  * NOTES
2255  *  Stub, always return TRUE.
2256  */
2257 BOOL WINAPI SystemFunction035(LPCSTR lpszDllFilePath)
2258 {
2259     FIXME("%s: stub\n", debugstr_a(lpszDllFilePath));
2260     return TRUE;
2261 }
2262
2263 /******************************************************************************
2264  * SystemFunction036   (ADVAPI32.@)
2265  *
2266  * MSDN documents this function as RtlGenRandom and declares it in ntsecapi.h
2267  *
2268  * PARAMS
2269  *  pbBufer [O] Pointer to memory to receive random bytes.
2270  *  dwLen   [I] Number of random bytes to fetch.
2271  *
2272  * RETURNS
2273  *  Success: TRUE
2274  *  Failure: FALSE
2275  */
2276
2277 BOOLEAN WINAPI SystemFunction036(PVOID pbBuffer, ULONG dwLen)
2278 {
2279     int dev_random;
2280
2281     dev_random = open("/dev/urandom", O_RDONLY);
2282     if (dev_random != -1)
2283     {
2284         if (read(dev_random, pbBuffer, dwLen) == (ssize_t)dwLen)
2285         {
2286             close(dev_random);
2287             return TRUE;
2288         }
2289         close(dev_random);
2290     }
2291     else
2292         FIXME("couldn't open /dev/urandom\n");
2293     SetLastError(NTE_FAIL);
2294     return FALSE;
2295 }    
2296     
2297 /*
2298    These functions have nearly identical prototypes to CryptProtectMemory and CryptUnprotectMemory,
2299    in crypt32.dll.
2300  */
2301
2302 /******************************************************************************
2303  * SystemFunction040   (ADVAPI32.@)
2304  *
2305  * MSDN documents this function as RtlEncryptMemory and declares it in ntsecapi.h.
2306  *
2307  * PARAMS
2308  *  memory [I/O] Pointer to memory to encrypt.
2309  *  length [I] Length of region to encrypt in bytes.
2310  *  flags  [I] Control whether other processes are able to decrypt the memory.
2311  *    RTL_ENCRYPT_OPTION_SAME_PROCESS 
2312  *    RTL_ENCRYPT_OPTION_CROSS_PROCESS 
2313  *    RTL_ENCRYPT_OPTION_SAME_LOGON
2314  *    
2315  * RETURNS
2316  *  Success: STATUS_SUCCESS
2317  *  Failure: NTSTATUS error code
2318  *
2319  * NOTES
2320  *  length must be a multiple of RTL_ENCRYPT_MEMORY_SIZE.
2321  *  If flags are specified when encrypting, the same flag value must be given
2322  *  when decrypting the memory.
2323  */
2324 NTSTATUS WINAPI SystemFunction040(PVOID memory, ULONG length, ULONG flags)
2325 {
2326         FIXME("(%p, %x, %x): stub [RtlEncryptMemory]\n", memory, length, flags);
2327         return STATUS_SUCCESS;
2328 }
2329
2330 /******************************************************************************
2331  * SystemFunction041  (ADVAPI32.@)
2332  *
2333  * MSDN documents this function as RtlDecryptMemory and declares it in ntsecapi.h.
2334  *
2335  * PARAMS
2336  *  memory [I/O] Pointer to memory to decrypt.
2337  *  length [I] Length of region to decrypt in bytes.
2338  *  flags  [I] Control whether other processes are able to decrypt the memory.
2339  *    RTL_ENCRYPT_OPTION_SAME_PROCESS
2340  *    RTL_ENCRYPT_OPTION_CROSS_PROCESS
2341  *    RTL_ENCRYPT_OPTION_SAME_LOGON
2342  *
2343  * RETURNS
2344  *  Success: STATUS_SUCCESS
2345  *  Failure: NTSTATUS error code
2346  *
2347  * NOTES
2348  *  length must be a multiple of RTL_ENCRYPT_MEMORY_SIZE.
2349  *  If flags are specified when encrypting, the same flag value must be given
2350  *  when decrypting the memory.
2351  */
2352 NTSTATUS WINAPI SystemFunction041(PVOID memory, ULONG length, ULONG flags)
2353 {
2354         FIXME("(%p, %x, %x): stub [RtlDecryptMemory]\n", memory, length, flags);
2355         return STATUS_SUCCESS;
2356 }