gphoto2.ds: Set supported groups.
[wine.git] / dlls / rsaenh / rsaenh.c
blobfdf410a4ede1d3821a751e9f2bd7f52d26630180
1 /*
2 * dlls/rsaenh/rsaenh.c
3 * RSAENH - RSA encryption for Wine
5 * Copyright 2002 TransGaming Technologies (David Hammerton)
6 * Copyright 2004 Mike McCormack for CodeWeavers
7 * Copyright 2004, 2005 Michael Jung
8 * Copyright 2007 Vijay Kiran Kamuju
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
25 #include "config.h"
26 #include "wine/port.h"
27 #include "wine/library.h"
28 #include "wine/debug.h"
30 #include <stdarg.h>
31 #include <stdio.h>
33 #include "windef.h"
34 #include "winbase.h"
35 #include "winreg.h"
36 #include "wincrypt.h"
37 #include "handle.h"
38 #include "implglue.h"
39 #include "objbase.h"
40 #include "rpcproxy.h"
41 #include "aclapi.h"
43 WINE_DEFAULT_DEBUG_CHANNEL(crypt);
45 static HINSTANCE instance;
47 /******************************************************************************
48 * CRYPTHASH - hash objects
50 #define RSAENH_MAGIC_HASH 0x85938417u
51 #define RSAENH_HASHSTATE_HASHING 1
52 #define RSAENH_HASHSTATE_FINISHED 2
53 typedef struct _RSAENH_TLS1PRF_PARAMS
55 CRYPT_DATA_BLOB blobLabel;
56 CRYPT_DATA_BLOB blobSeed;
57 } RSAENH_TLS1PRF_PARAMS;
59 typedef struct tagCRYPTHASH
61 OBJECTHDR header;
62 ALG_ID aiAlgid;
63 HCRYPTKEY hKey;
64 HCRYPTPROV hProv;
65 DWORD dwHashSize;
66 DWORD dwState;
67 HASH_CONTEXT context;
68 BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
69 PHMAC_INFO pHMACInfo;
70 RSAENH_TLS1PRF_PARAMS tpPRFParams;
71 } CRYPTHASH;
73 /******************************************************************************
74 * CRYPTKEY - key objects
76 #define RSAENH_MAGIC_KEY 0x73620457u
77 #define RSAENH_MAX_KEY_SIZE 64
78 #define RSAENH_MAX_BLOCK_SIZE 24
79 #define RSAENH_KEYSTATE_IDLE 0
80 #define RSAENH_KEYSTATE_ENCRYPTING 1
81 #define RSAENH_KEYSTATE_MASTERKEY 2
82 typedef struct _RSAENH_SCHANNEL_INFO
84 SCHANNEL_ALG saEncAlg;
85 SCHANNEL_ALG saMACAlg;
86 CRYPT_DATA_BLOB blobClientRandom;
87 CRYPT_DATA_BLOB blobServerRandom;
88 } RSAENH_SCHANNEL_INFO;
90 typedef struct tagCRYPTKEY
92 OBJECTHDR header;
93 ALG_ID aiAlgid;
94 HCRYPTPROV hProv;
95 DWORD dwMode;
96 DWORD dwModeBits;
97 DWORD dwPermissions;
98 DWORD dwKeyLen;
99 DWORD dwEffectiveKeyLen;
100 DWORD dwSaltLen;
101 DWORD dwBlockLen;
102 DWORD dwState;
103 KEY_CONTEXT context;
104 BYTE abKeyValue[RSAENH_MAX_KEY_SIZE];
105 BYTE abInitVector[RSAENH_MAX_BLOCK_SIZE];
106 BYTE abChainVector[RSAENH_MAX_BLOCK_SIZE];
107 RSAENH_SCHANNEL_INFO siSChannelInfo;
108 CRYPT_DATA_BLOB blobHmacKey;
109 } CRYPTKEY;
111 /******************************************************************************
112 * KEYCONTAINER - key containers
114 #define RSAENH_PERSONALITY_BASE 0u
115 #define RSAENH_PERSONALITY_STRONG 1u
116 #define RSAENH_PERSONALITY_ENHANCED 2u
117 #define RSAENH_PERSONALITY_SCHANNEL 3u
118 #define RSAENH_PERSONALITY_AES 4u
120 #define RSAENH_MAGIC_CONTAINER 0x26384993u
121 typedef struct tagKEYCONTAINER
123 OBJECTHDR header;
124 DWORD dwFlags;
125 DWORD dwPersonality;
126 DWORD dwEnumAlgsCtr;
127 DWORD dwEnumContainersCtr;
128 CHAR szName[MAX_PATH];
129 CHAR szProvName[MAX_PATH];
130 HCRYPTKEY hKeyExchangeKeyPair;
131 HCRYPTKEY hSignatureKeyPair;
132 } KEYCONTAINER;
134 /******************************************************************************
135 * Some magic constants
137 #define RSAENH_ENCRYPT 1
138 #define RSAENH_DECRYPT 0
139 #define RSAENH_HMAC_DEF_IPAD_CHAR 0x36
140 #define RSAENH_HMAC_DEF_OPAD_CHAR 0x5c
141 #define RSAENH_HMAC_DEF_PAD_LEN 64
142 #define RSAENH_HMAC_BLOCK_LEN 64
143 #define RSAENH_DES_EFFECTIVE_KEYLEN 56
144 #define RSAENH_DES_STORAGE_KEYLEN 64
145 #define RSAENH_3DES112_EFFECTIVE_KEYLEN 112
146 #define RSAENH_3DES112_STORAGE_KEYLEN 128
147 #define RSAENH_3DES_EFFECTIVE_KEYLEN 168
148 #define RSAENH_3DES_STORAGE_KEYLEN 192
149 #define RSAENH_MAGIC_RSA2 0x32415352
150 #define RSAENH_MAGIC_RSA1 0x31415352
151 #define RSAENH_PKC_BLOCKTYPE 0x02
152 #define RSAENH_SSL3_VERSION_MAJOR 3
153 #define RSAENH_SSL3_VERSION_MINOR 0
154 #define RSAENH_TLS1_VERSION_MAJOR 3
155 #define RSAENH_TLS1_VERSION_MINOR 1
156 #define RSAENH_REGKEY "Software\\Wine\\Crypto\\RSA\\%s"
158 #define RSAENH_MIN(a,b) ((a)<(b)?(a):(b))
159 /******************************************************************************
160 * aProvEnumAlgsEx - Defines the capabilities of the CSP personalities.
162 #define RSAENH_MAX_ENUMALGS 24
163 #define RSAENH_PCT1_SSL2_SSL3_TLS1 (CRYPT_FLAG_PCT1|CRYPT_FLAG_SSL2|CRYPT_FLAG_SSL3|CRYPT_FLAG_TLS1)
164 #define S(s) sizeof(s), s
165 static const PROV_ENUMALGS_EX aProvEnumAlgsEx[5][RSAENH_MAX_ENUMALGS+1] =
168 {CALG_RC2, 40, 40, 56, 0, S("RC2"), S("RSA Data Security's RC2")},
169 {CALG_RC4, 40, 40, 56, 0, S("RC4"), S("RSA Data Security's RC4")},
170 {CALG_DES, 56, 56, 56, 0, S("DES"), S("Data Encryption Standard (DES)")},
171 {CALG_SHA, 160, 160, 160, CRYPT_FLAG_SIGNING, S("SHA-1"), S("Secure Hash Algorithm (SHA-1)")},
172 {CALG_MD2, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD2"), S("Message Digest 2 (MD2)")},
173 {CALG_MD4, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD4"), S("Message Digest 4 (MD4)")},
174 {CALG_MD5, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD5"), S("Message Digest 5 (MD5)")},
175 {CALG_SSL3_SHAMD5, 288, 288, 288, 0, S("SSL3 SHAMD5"), S("SSL3 SHAMD5")},
176 {CALG_MAC, 0, 0, 0, 0, S("MAC"), S("Message Authentication Code")},
177 {CALG_RSA_SIGN, 512, 384, 16384, CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC, S("RSA_SIGN"), S("RSA Signature")},
178 {CALG_RSA_KEYX, 512, 384, 1024, CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC, S("RSA_KEYX"), S("RSA Key Exchange")},
179 {CALG_HMAC, 0, 0, 0, 0, S("HMAC"), S("Hugo's MAC (HMAC)")},
180 {0, 0, 0, 0, 0, S(""), S("")}
183 {CALG_RC2, 128, 40, 128, 0, S("RC2"), S("RSA Data Security's RC2")},
184 {CALG_RC4, 128, 40, 128, 0, S("RC4"), S("RSA Data Security's RC4")},
185 {CALG_DES, 56, 56, 56, 0, S("DES"), S("Data Encryption Standard (DES)")},
186 {CALG_3DES_112, 112, 112, 112, 0, S("3DES TWO KEY"), S("Two Key Triple DES")},
187 {CALG_3DES, 168, 168, 168, 0, S("3DES"), S("Three Key Triple DES")},
188 {CALG_SHA, 160, 160, 160, CRYPT_FLAG_SIGNING, S("SHA-1"), S("Secure Hash Algorithm (SHA-1)")},
189 {CALG_MD2, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD2"), S("Message Digest 2 (MD2)")},
190 {CALG_MD4, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD4"), S("Message Digest 4 (MD4)")},
191 {CALG_MD5, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD5"), S("Message Digest 5 (MD5)")},
192 {CALG_SSL3_SHAMD5, 288, 288, 288, 0, S("SSL3 SHAMD5"), S("SSL3 SHAMD5")},
193 {CALG_MAC, 0, 0, 0, 0, S("MAC"), S("Message Authentication Code")},
194 {CALG_RSA_SIGN, 1024, 384, 16384, CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC, S("RSA_SIGN"), S("RSA Signature")},
195 {CALG_RSA_KEYX, 1024, 384, 16384, CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC, S("RSA_KEYX"), S("RSA Key Exchange")},
196 {CALG_HMAC, 0, 0, 0, 0, S("HMAC"), S("Hugo's MAC (HMAC)")},
197 {0, 0, 0, 0, 0, S(""), S("")}
200 {CALG_RC2, 128, 40, 128, 0, S("RC2"), S("RSA Data Security's RC2")},
201 {CALG_RC4, 128, 40, 128, 0, S("RC4"), S("RSA Data Security's RC4")},
202 {CALG_DES, 56, 56, 56, 0, S("DES"), S("Data Encryption Standard (DES)")},
203 {CALG_3DES_112, 112, 112, 112, 0, S("3DES TWO KEY"), S("Two Key Triple DES")},
204 {CALG_3DES, 168, 168, 168, 0, S("3DES"), S("Three Key Triple DES")},
205 {CALG_SHA, 160, 160, 160, CRYPT_FLAG_SIGNING, S("SHA-1"), S("Secure Hash Algorithm (SHA-1)")},
206 {CALG_MD2, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD2"), S("Message Digest 2 (MD2)")},
207 {CALG_MD4, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD4"), S("Message Digest 4 (MD4)")},
208 {CALG_MD5, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD5"), S("Message Digest 5 (MD5)")},
209 {CALG_SSL3_SHAMD5, 288, 288, 288, 0, S("SSL3 SHAMD5"), S("SSL3 SHAMD5")},
210 {CALG_MAC, 0, 0, 0, 0, S("MAC"), S("Message Authentication Code")},
211 {CALG_RSA_SIGN, 1024, 384, 16384, CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC, S("RSA_SIGN"), S("RSA Signature")},
212 {CALG_RSA_KEYX, 1024, 384, 16384, CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC, S("RSA_KEYX"), S("RSA Key Exchange")},
213 {CALG_HMAC, 0, 0, 0, 0, S("HMAC"), S("Hugo's MAC (HMAC)")},
214 {0, 0, 0, 0, 0, S(""), S("")}
217 {CALG_RC2, 128, 40, 128, RSAENH_PCT1_SSL2_SSL3_TLS1, S("RC2"), S("RSA Data Security's RC2")},
218 {CALG_RC4, 128, 40, 128, RSAENH_PCT1_SSL2_SSL3_TLS1, S("RC4"), S("RSA Data Security's RC4")},
219 {CALG_DES, 56, 56, 56, RSAENH_PCT1_SSL2_SSL3_TLS1, S("DES"), S("Data Encryption Standard (DES)")},
220 {CALG_3DES_112, 112, 112, 112, RSAENH_PCT1_SSL2_SSL3_TLS1, S("3DES TWO KEY"), S("Two Key Triple DES")},
221 {CALG_3DES, 168, 168, 168, RSAENH_PCT1_SSL2_SSL3_TLS1, S("3DES"), S("Three Key Triple DES")},
222 {CALG_SHA, 160, 160, 160, CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1, S("SHA-1"), S("Secure Hash Algorithm (SHA-1)")},
223 {CALG_MD5, 128, 128, 128, CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1, S("MD5"), S("Message Digest 5 (MD5)")},
224 {CALG_SSL3_SHAMD5, 288, 288, 288, 0, S("SSL3 SHAMD5"), S("SSL3 SHAMD5")},
225 {CALG_MAC, 0, 0, 0, 0, S("MAC"), S("Message Authentication Code")},
226 {CALG_RSA_SIGN, 1024, 384, 16384, CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1, S("RSA_SIGN"), S("RSA Signature")},
227 {CALG_RSA_KEYX, 1024, 384, 16384, CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1, S("RSA_KEYX"), S("RSA Key Exchange")},
228 {CALG_HMAC, 0, 0, 0, 0, S("HMAC"), S("Hugo's MAC (HMAC)")},
229 {CALG_PCT1_MASTER, 128, 128, 128, CRYPT_FLAG_PCT1, S("PCT1 MASTER"), S("PCT1 Master")},
230 {CALG_SSL2_MASTER, 40, 40, 192, CRYPT_FLAG_SSL2, S("SSL2 MASTER"), S("SSL2 Master")},
231 {CALG_SSL3_MASTER, 384, 384, 384, CRYPT_FLAG_SSL3, S("SSL3 MASTER"), S("SSL3 Master")},
232 {CALG_TLS1_MASTER, 384, 384, 384, CRYPT_FLAG_TLS1, S("TLS1 MASTER"), S("TLS1 Master")},
233 {CALG_SCHANNEL_MASTER_HASH, 0, 0, -1, 0, S("SCH MASTER HASH"), S("SChannel Master Hash")},
234 {CALG_SCHANNEL_MAC_KEY, 0, 0, -1, 0, S("SCH MAC KEY"), S("SChannel MAC Key")},
235 {CALG_SCHANNEL_ENC_KEY, 0, 0, -1, 0, S("SCH ENC KEY"), S("SChannel Encryption Key")},
236 {CALG_TLS1PRF, 0, 0, -1, 0, S("TLS1 PRF"), S("TLS1 Pseudo Random Function")},
237 {0, 0, 0, 0, 0, S(""), S("")}
240 {CALG_RC2, 128, 40, 128, 0, S("RC2"), S("RSA Data Security's RC2")},
241 {CALG_RC4, 128, 40, 128, 0, S("RC4"), S("RSA Data Security's RC4")},
242 {CALG_DES, 56, 56, 56, 0, S("DES"), S("Data Encryption Standard (DES)")},
243 {CALG_3DES_112, 112, 112, 112, 0, S("3DES TWO KEY"), S("Two Key Triple DES")},
244 {CALG_3DES, 168, 168, 168, 0, S("3DES"), S("Three Key Triple DES")},
245 {CALG_AES_128, 128, 128, 128, 0, S("AES-128"), S("Advanced Encryption Standard (AES-128)")},
246 {CALG_AES_192, 192, 192, 192, 0, S("AES-192"), S("Advanced Encryption Standard (AES-192)")},
247 {CALG_AES_256, 256, 256, 256, 0, S("AES-256"), S("Advanced Encryption Standard (AES-256)")},
248 {CALG_SHA, 160, 160, 160, CRYPT_FLAG_SIGNING, S("SHA-1"), S("Secure Hash Algorithm (SHA-1)")},
249 {CALG_SHA_256, 256, 256, 256, CRYPT_FLAG_SIGNING, S("SHA-256"), S("Secure Hash Algorithm (SHA-256)")},
250 {CALG_SHA_384, 384, 384, 384, CRYPT_FLAG_SIGNING, S("SHA-384"), S("Secure Hash Algorithm (SHA-384)")},
251 {CALG_SHA_512, 512, 512, 512, CRYPT_FLAG_SIGNING, S("SHA-512"), S("Secure Hash Algorithm (SHA-512)")},
252 {CALG_MD2, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD2"), S("Message Digest 2 (MD2)")},
253 {CALG_MD4, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD4"), S("Message Digest 4 (MD4)")},
254 {CALG_MD5, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD5"), S("Message Digest 5 (MD5)")},
255 {CALG_SSL3_SHAMD5, 288, 288, 288, 0, S("SSL3 SHAMD5"), S("SSL3 SHAMD5")},
256 {CALG_MAC, 0, 0, 0, 0, S("MAC"), S("Message Authentication Code")},
257 {CALG_RSA_SIGN, 1024, 384, 16384, CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC, S("RSA_SIGN"), S("RSA Signature")},
258 {CALG_RSA_KEYX, 1024, 384, 16384, CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC, S("RSA_KEYX"), S("RSA Key Exchange")},
259 {CALG_HMAC, 0, 0, 0, 0, S("HMAC"), S("Hugo's MAC (HMAC)")},
260 {0, 0, 0, 0, 0, S(""), S("")}
263 #undef S
265 /******************************************************************************
266 * API forward declarations
268 BOOL WINAPI
269 RSAENH_CPGetKeyParam(
270 HCRYPTPROV hProv,
271 HCRYPTKEY hKey,
272 DWORD dwParam,
273 BYTE *pbData,
274 DWORD *pdwDataLen,
275 DWORD dwFlags
278 BOOL WINAPI
279 RSAENH_CPEncrypt(
280 HCRYPTPROV hProv,
281 HCRYPTKEY hKey,
282 HCRYPTHASH hHash,
283 BOOL Final,
284 DWORD dwFlags,
285 BYTE *pbData,
286 DWORD *pdwDataLen,
287 DWORD dwBufLen
290 BOOL WINAPI
291 RSAENH_CPCreateHash(
292 HCRYPTPROV hProv,
293 ALG_ID Algid,
294 HCRYPTKEY hKey,
295 DWORD dwFlags,
296 HCRYPTHASH *phHash
299 BOOL WINAPI
300 RSAENH_CPSetHashParam(
301 HCRYPTPROV hProv,
302 HCRYPTHASH hHash,
303 DWORD dwParam,
304 BYTE *pbData, DWORD dwFlags
307 BOOL WINAPI
308 RSAENH_CPGetHashParam(
309 HCRYPTPROV hProv,
310 HCRYPTHASH hHash,
311 DWORD dwParam,
312 BYTE *pbData,
313 DWORD *pdwDataLen,
314 DWORD dwFlags
317 BOOL WINAPI
318 RSAENH_CPDestroyHash(
319 HCRYPTPROV hProv,
320 HCRYPTHASH hHash
323 static BOOL crypt_export_key(
324 CRYPTKEY *pCryptKey,
325 HCRYPTKEY hPubKey,
326 DWORD dwBlobType,
327 DWORD dwFlags,
328 BOOL force,
329 BYTE *pbData,
330 DWORD *pdwDataLen
333 static BOOL import_key(
334 HCRYPTPROV hProv,
335 const BYTE *pbData,
336 DWORD dwDataLen,
337 HCRYPTKEY hPubKey,
338 DWORD dwFlags,
339 BOOL fStoreKey,
340 HCRYPTKEY *phKey
343 BOOL WINAPI
344 RSAENH_CPHashData(
345 HCRYPTPROV hProv,
346 HCRYPTHASH hHash,
347 const BYTE *pbData,
348 DWORD dwDataLen,
349 DWORD dwFlags
352 /******************************************************************************
353 * CSP's handle table (used by all acquired key containers)
355 static struct handle_table handle_table;
357 /******************************************************************************
358 * DllMain (RSAENH.@)
360 * Initializes and destroys the handle table for the CSP's handles.
362 BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD fdwReason, PVOID reserved)
364 switch (fdwReason)
366 case DLL_PROCESS_ATTACH:
367 instance = hInstance;
368 DisableThreadLibraryCalls(hInstance);
369 init_handle_table(&handle_table);
370 break;
372 case DLL_PROCESS_DETACH:
373 if (reserved) break;
374 destroy_handle_table(&handle_table);
375 break;
377 return TRUE;
380 /******************************************************************************
381 * copy_param [Internal]
383 * Helper function that supports the standard WINAPI protocol for querying data
384 * of dynamic size.
386 * PARAMS
387 * pbBuffer [O] Buffer where the queried parameter is copied to, if it is large enough.
388 * May be NUL if the required buffer size is to be queried only.
389 * pdwBufferSize [I/O] In: Size of the buffer at pbBuffer
390 * Out: Size of parameter pbParam
391 * pbParam [I] Parameter value.
392 * dwParamSize [I] Size of pbParam
394 * RETURN
395 * Success: TRUE (pbParam was copied into pbBuffer or pbBuffer is NULL)
396 * Failure: FALSE (pbBuffer is not large enough to hold pbParam). Last error: ERROR_MORE_DATA
398 static inline BOOL copy_param(BYTE *pbBuffer, DWORD *pdwBufferSize, const BYTE *pbParam,
399 DWORD dwParamSize)
401 if (pbBuffer)
403 if (dwParamSize > *pdwBufferSize)
405 SetLastError(ERROR_MORE_DATA);
406 *pdwBufferSize = dwParamSize;
407 return FALSE;
409 memcpy(pbBuffer, pbParam, dwParamSize);
411 *pdwBufferSize = dwParamSize;
412 return TRUE;
415 static inline KEYCONTAINER* get_key_container(HCRYPTPROV hProv)
417 KEYCONTAINER *pKeyContainer;
419 if (!lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER,
420 (OBJECTHDR**)&pKeyContainer))
422 SetLastError(NTE_BAD_UID);
423 return NULL;
425 return pKeyContainer;
428 /******************************************************************************
429 * get_algid_info [Internal]
431 * Query CSP capabilities for a given crypto algorithm.
433 * PARAMS
434 * hProv [I] Handle to a key container of the CSP whose capabilities are to be queried.
435 * algid [I] Identifier of the crypto algorithm about which information is requested.
437 * RETURNS
438 * Success: Pointer to a PROV_ENUMALGS_EX struct containing information about the crypto algorithm.
439 * Failure: NULL (algid not supported)
441 static inline const PROV_ENUMALGS_EX* get_algid_info(HCRYPTPROV hProv, ALG_ID algid) {
442 const PROV_ENUMALGS_EX *iterator;
443 KEYCONTAINER *pKeyContainer;
445 if (!(pKeyContainer = get_key_container(hProv))) return NULL;
447 for (iterator = aProvEnumAlgsEx[pKeyContainer->dwPersonality]; iterator->aiAlgid; iterator++) {
448 if (iterator->aiAlgid == algid) return iterator;
451 SetLastError(NTE_BAD_ALGID);
452 return NULL;
455 /******************************************************************************
456 * copy_data_blob [Internal]
458 * deeply copies a DATA_BLOB
460 * PARAMS
461 * dst [O] That's where the blob will be copied to
462 * src [I] Source blob
464 * RETURNS
465 * Success: TRUE
466 * Failure: FALSE (GetLastError() == NTE_NO_MEMORY
468 * NOTES
469 * Use free_data_blob to release resources occupied by copy_data_blob.
471 static inline BOOL copy_data_blob(PCRYPT_DATA_BLOB dst, const PCRYPT_DATA_BLOB src)
473 dst->pbData = HeapAlloc(GetProcessHeap(), 0, src->cbData);
474 if (!dst->pbData) {
475 SetLastError(NTE_NO_MEMORY);
476 return FALSE;
478 dst->cbData = src->cbData;
479 memcpy(dst->pbData, src->pbData, src->cbData);
480 return TRUE;
483 /******************************************************************************
484 * concat_data_blobs [Internal]
486 * Concatenates two blobs
488 * PARAMS
489 * dst [O] The new blob will be copied here
490 * src1 [I] Prefix blob
491 * src2 [I] Appendix blob
493 * RETURNS
494 * Success: TRUE
495 * Failure: FALSE (GetLastError() == NTE_NO_MEMORY)
497 * NOTES
498 * Release resources occupied by concat_data_blobs with free_data_blobs
500 static inline BOOL concat_data_blobs(PCRYPT_DATA_BLOB dst, const PCRYPT_DATA_BLOB src1,
501 const PCRYPT_DATA_BLOB src2)
503 dst->cbData = src1->cbData + src2->cbData;
504 dst->pbData = HeapAlloc(GetProcessHeap(), 0, dst->cbData);
505 if (!dst->pbData) {
506 SetLastError(NTE_NO_MEMORY);
507 return FALSE;
509 memcpy(dst->pbData, src1->pbData, src1->cbData);
510 memcpy(dst->pbData + src1->cbData, src2->pbData, src2->cbData);
511 return TRUE;
514 /******************************************************************************
515 * free_data_blob [Internal]
517 * releases resource occupied by a dynamically allocated CRYPT_DATA_BLOB
519 * PARAMS
520 * pBlob [I] Heap space occupied by pBlob->pbData is released
522 static inline void free_data_blob(PCRYPT_DATA_BLOB pBlob) {
523 HeapFree(GetProcessHeap(), 0, pBlob->pbData);
526 /******************************************************************************
527 * init_data_blob [Internal]
529 static inline void init_data_blob(PCRYPT_DATA_BLOB pBlob) {
530 pBlob->pbData = NULL;
531 pBlob->cbData = 0;
534 /******************************************************************************
535 * free_hmac_info [Internal]
537 * Deeply free an HMAC_INFO struct.
539 * PARAMS
540 * hmac_info [I] Pointer to the HMAC_INFO struct to be freed.
542 * NOTES
543 * See Internet RFC 2104 for details on the HMAC algorithm.
545 static inline void free_hmac_info(PHMAC_INFO hmac_info) {
546 if (!hmac_info) return;
547 HeapFree(GetProcessHeap(), 0, hmac_info->pbInnerString);
548 HeapFree(GetProcessHeap(), 0, hmac_info->pbOuterString);
549 HeapFree(GetProcessHeap(), 0, hmac_info);
552 /******************************************************************************
553 * copy_hmac_info [Internal]
555 * Deeply copy an HMAC_INFO struct
557 * PARAMS
558 * dst [O] Pointer to a location where the pointer to the HMAC_INFO copy will be stored.
559 * src [I] Pointer to the HMAC_INFO struct to be copied.
561 * RETURNS
562 * Success: TRUE
563 * Failure: FALSE
565 * NOTES
566 * See Internet RFC 2104 for details on the HMAC algorithm.
568 static BOOL copy_hmac_info(PHMAC_INFO *dst, const HMAC_INFO *src) {
569 if (!src) return FALSE;
570 *dst = HeapAlloc(GetProcessHeap(), 0, sizeof(HMAC_INFO));
571 if (!*dst) return FALSE;
572 **dst = *src;
573 (*dst)->pbInnerString = NULL;
574 (*dst)->pbOuterString = NULL;
575 if ((*dst)->cbInnerString == 0) (*dst)->cbInnerString = RSAENH_HMAC_DEF_PAD_LEN;
576 (*dst)->pbInnerString = HeapAlloc(GetProcessHeap(), 0, (*dst)->cbInnerString);
577 if (!(*dst)->pbInnerString) {
578 free_hmac_info(*dst);
579 return FALSE;
581 if (src->cbInnerString)
582 memcpy((*dst)->pbInnerString, src->pbInnerString, src->cbInnerString);
583 else
584 memset((*dst)->pbInnerString, RSAENH_HMAC_DEF_IPAD_CHAR, RSAENH_HMAC_DEF_PAD_LEN);
585 if ((*dst)->cbOuterString == 0) (*dst)->cbOuterString = RSAENH_HMAC_DEF_PAD_LEN;
586 (*dst)->pbOuterString = HeapAlloc(GetProcessHeap(), 0, (*dst)->cbOuterString);
587 if (!(*dst)->pbOuterString) {
588 free_hmac_info(*dst);
589 return FALSE;
591 if (src->cbOuterString)
592 memcpy((*dst)->pbOuterString, src->pbOuterString, src->cbOuterString);
593 else
594 memset((*dst)->pbOuterString, RSAENH_HMAC_DEF_OPAD_CHAR, RSAENH_HMAC_DEF_PAD_LEN);
595 return TRUE;
598 /******************************************************************************
599 * destroy_hash [Internal]
601 * Destructor for hash objects
603 * PARAMS
604 * pCryptHash [I] Pointer to the hash object to be destroyed.
605 * Will be invalid after function returns!
607 static void destroy_hash(OBJECTHDR *pObject)
609 CRYPTHASH *pCryptHash = (CRYPTHASH*)pObject;
611 free_hmac_info(pCryptHash->pHMACInfo);
612 free_data_blob(&pCryptHash->tpPRFParams.blobLabel);
613 free_data_blob(&pCryptHash->tpPRFParams.blobSeed);
614 HeapFree(GetProcessHeap(), 0, pCryptHash);
617 /******************************************************************************
618 * init_hash [Internal]
620 * Initialize (or reset) a hash object
622 * PARAMS
623 * pCryptHash [I] The hash object to be initialized.
625 static inline BOOL init_hash(CRYPTHASH *pCryptHash) {
626 DWORD dwLen;
628 switch (pCryptHash->aiAlgid)
630 case CALG_HMAC:
631 if (pCryptHash->pHMACInfo) {
632 const PROV_ENUMALGS_EX *pAlgInfo;
634 pAlgInfo = get_algid_info(pCryptHash->hProv, pCryptHash->pHMACInfo->HashAlgid);
635 if (!pAlgInfo) return FALSE;
636 pCryptHash->dwHashSize = pAlgInfo->dwDefaultLen >> 3;
637 init_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context);
638 update_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
639 pCryptHash->pHMACInfo->pbInnerString,
640 pCryptHash->pHMACInfo->cbInnerString);
642 return TRUE;
644 case CALG_MAC:
645 dwLen = sizeof(DWORD);
646 RSAENH_CPGetKeyParam(pCryptHash->hProv, pCryptHash->hKey, KP_BLOCKLEN,
647 (BYTE*)&pCryptHash->dwHashSize, &dwLen, 0);
648 pCryptHash->dwHashSize >>= 3;
649 return TRUE;
651 default:
652 return init_hash_impl(pCryptHash->aiAlgid, &pCryptHash->context);
656 /******************************************************************************
657 * update_hash [Internal]
659 * Hashes the given data and updates the hash object's state accordingly
661 * PARAMS
662 * pCryptHash [I] Hash object to be updated.
663 * pbData [I] Pointer to data stream to be hashed.
664 * dwDataLen [I] Length of data stream.
666 static inline void update_hash(CRYPTHASH *pCryptHash, const BYTE *pbData, DWORD dwDataLen)
668 BYTE *pbTemp;
670 switch (pCryptHash->aiAlgid)
672 case CALG_HMAC:
673 if (pCryptHash->pHMACInfo)
674 update_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
675 pbData, dwDataLen);
676 break;
678 case CALG_MAC:
679 pbTemp = HeapAlloc(GetProcessHeap(), 0, dwDataLen);
680 if (!pbTemp) return;
681 memcpy(pbTemp, pbData, dwDataLen);
682 RSAENH_CPEncrypt(pCryptHash->hProv, pCryptHash->hKey, 0, FALSE, 0,
683 pbTemp, &dwDataLen, dwDataLen);
684 HeapFree(GetProcessHeap(), 0, pbTemp);
685 break;
687 default:
688 update_hash_impl(pCryptHash->aiAlgid, &pCryptHash->context, pbData, dwDataLen);
692 /******************************************************************************
693 * finalize_hash [Internal]
695 * Finalizes the hash, after all data has been hashed with update_hash.
696 * No additional data can be hashed afterwards until the hash gets initialized again.
698 * PARAMS
699 * pCryptHash [I] Hash object to be finalized.
701 static inline void finalize_hash(CRYPTHASH *pCryptHash) {
702 DWORD dwDataLen;
704 switch (pCryptHash->aiAlgid)
706 case CALG_HMAC:
707 if (pCryptHash->pHMACInfo) {
708 BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
710 finalize_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
711 pCryptHash->abHashValue);
712 memcpy(abHashValue, pCryptHash->abHashValue, pCryptHash->dwHashSize);
713 init_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context);
714 update_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
715 pCryptHash->pHMACInfo->pbOuterString,
716 pCryptHash->pHMACInfo->cbOuterString);
717 update_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
718 abHashValue, pCryptHash->dwHashSize);
719 finalize_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
720 pCryptHash->abHashValue);
722 break;
724 case CALG_MAC:
725 dwDataLen = 0;
726 RSAENH_CPEncrypt(pCryptHash->hProv, pCryptHash->hKey, 0, TRUE, 0,
727 pCryptHash->abHashValue, &dwDataLen, pCryptHash->dwHashSize);
728 break;
730 default:
731 finalize_hash_impl(pCryptHash->aiAlgid, &pCryptHash->context, pCryptHash->abHashValue);
735 /******************************************************************************
736 * destroy_key [Internal]
738 * Destructor for key objects
740 * PARAMS
741 * pCryptKey [I] Pointer to the key object to be destroyed.
742 * Will be invalid after function returns!
744 static void destroy_key(OBJECTHDR *pObject)
746 CRYPTKEY *pCryptKey = (CRYPTKEY*)pObject;
748 free_key_impl(pCryptKey->aiAlgid, &pCryptKey->context);
749 free_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom);
750 free_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom);
751 free_data_blob(&pCryptKey->blobHmacKey);
752 HeapFree(GetProcessHeap(), 0, pCryptKey);
755 /******************************************************************************
756 * setup_key [Internal]
758 * Initialize (or reset) a key object
760 * PARAMS
761 * pCryptKey [I] The key object to be initialized.
763 static inline void setup_key(CRYPTKEY *pCryptKey) {
764 pCryptKey->dwState = RSAENH_KEYSTATE_IDLE;
765 memcpy(pCryptKey->abChainVector, pCryptKey->abInitVector, sizeof(pCryptKey->abChainVector));
766 setup_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen,
767 pCryptKey->dwEffectiveKeyLen, pCryptKey->dwSaltLen,
768 pCryptKey->abKeyValue);
771 /******************************************************************************
772 * new_key [Internal]
774 * Creates a new key object without assigning the actual binary key value.
775 * This is done by CPDeriveKey, CPGenKey or CPImportKey, which call this function.
777 * PARAMS
778 * hProv [I] Handle to the provider to which the created key will belong.
779 * aiAlgid [I] The new key shall use the crypto algorithm identified by aiAlgid.
780 * dwFlags [I] Upper 16 bits give the key length.
781 * Lower 16 bits: CRYPT_EXPORTABLE, CRYPT_CREATE_SALT,
782 * CRYPT_NO_SALT
783 * ppCryptKey [O] Pointer to the created key
785 * RETURNS
786 * Success: Handle to the created key.
787 * Failure: INVALID_HANDLE_VALUE
789 static HCRYPTKEY new_key(HCRYPTPROV hProv, ALG_ID aiAlgid, DWORD dwFlags, CRYPTKEY **ppCryptKey)
791 HCRYPTKEY hCryptKey;
792 CRYPTKEY *pCryptKey;
793 DWORD dwKeyLen = HIWORD(dwFlags);
794 const PROV_ENUMALGS_EX *peaAlgidInfo;
796 *ppCryptKey = NULL;
799 * Retrieve the CSP's capabilities for the given ALG_ID value
801 peaAlgidInfo = get_algid_info(hProv, aiAlgid);
802 if (!peaAlgidInfo) return (HCRYPTKEY)INVALID_HANDLE_VALUE;
804 TRACE("alg = %s, dwKeyLen = %d\n", debugstr_a(peaAlgidInfo->szName),
805 dwKeyLen);
807 * Assume the default key length, if none is specified explicitly
809 if (dwKeyLen == 0) dwKeyLen = peaAlgidInfo->dwDefaultLen;
812 * Check if the requested key length is supported by the current CSP.
813 * Adjust key length's for DES algorithms.
815 switch (aiAlgid) {
816 case CALG_DES:
817 if (dwKeyLen == RSAENH_DES_EFFECTIVE_KEYLEN) {
818 dwKeyLen = RSAENH_DES_STORAGE_KEYLEN;
820 if (dwKeyLen != RSAENH_DES_STORAGE_KEYLEN) {
821 SetLastError(NTE_BAD_FLAGS);
822 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
824 break;
826 case CALG_3DES_112:
827 if (dwKeyLen == RSAENH_3DES112_EFFECTIVE_KEYLEN) {
828 dwKeyLen = RSAENH_3DES112_STORAGE_KEYLEN;
830 if (dwKeyLen != RSAENH_3DES112_STORAGE_KEYLEN) {
831 SetLastError(NTE_BAD_FLAGS);
832 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
834 break;
836 case CALG_3DES:
837 if (dwKeyLen == RSAENH_3DES_EFFECTIVE_KEYLEN) {
838 dwKeyLen = RSAENH_3DES_STORAGE_KEYLEN;
840 if (dwKeyLen != RSAENH_3DES_STORAGE_KEYLEN) {
841 SetLastError(NTE_BAD_FLAGS);
842 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
844 break;
846 case CALG_HMAC:
847 /* Avoid the key length check for HMAC keys, which have unlimited
848 * length.
850 break;
852 default:
853 if (dwKeyLen % 8 ||
854 dwKeyLen > peaAlgidInfo->dwMaxLen ||
855 dwKeyLen < peaAlgidInfo->dwMinLen)
857 TRACE("key len %d out of bounds (%d, %d)\n", dwKeyLen,
858 peaAlgidInfo->dwMinLen, peaAlgidInfo->dwMaxLen);
859 SetLastError(NTE_BAD_DATA);
860 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
864 hCryptKey = new_object(&handle_table, sizeof(CRYPTKEY), RSAENH_MAGIC_KEY,
865 destroy_key, (OBJECTHDR**)&pCryptKey);
866 if (hCryptKey != (HCRYPTKEY)INVALID_HANDLE_VALUE)
868 KEYCONTAINER *pKeyContainer = get_key_container(hProv);
869 pCryptKey->aiAlgid = aiAlgid;
870 pCryptKey->hProv = hProv;
871 pCryptKey->dwModeBits = 0;
872 pCryptKey->dwPermissions = CRYPT_ENCRYPT | CRYPT_DECRYPT | CRYPT_READ | CRYPT_WRITE |
873 CRYPT_MAC;
874 if (dwFlags & CRYPT_EXPORTABLE)
875 pCryptKey->dwPermissions |= CRYPT_EXPORT;
876 pCryptKey->dwKeyLen = dwKeyLen >> 3;
877 pCryptKey->dwEffectiveKeyLen = 0;
880 * For compatibility reasons a 40 bit key on the Enhanced
881 * provider will not have salt
883 if (pKeyContainer->dwPersonality == RSAENH_PERSONALITY_ENHANCED
884 && (aiAlgid == CALG_RC2 || aiAlgid == CALG_RC4)
885 && (dwFlags & CRYPT_CREATE_SALT) && dwKeyLen == 40)
886 pCryptKey->dwSaltLen = 0;
887 else if ((dwFlags & CRYPT_CREATE_SALT) || (dwKeyLen == 40 && !(dwFlags & CRYPT_NO_SALT)))
888 pCryptKey->dwSaltLen = 16 /*FIXME*/ - pCryptKey->dwKeyLen;
889 else
890 pCryptKey->dwSaltLen = 0;
891 memset(pCryptKey->abKeyValue, 0, sizeof(pCryptKey->abKeyValue));
892 memset(pCryptKey->abInitVector, 0, sizeof(pCryptKey->abInitVector));
893 memset(&pCryptKey->siSChannelInfo.saEncAlg, 0, sizeof(pCryptKey->siSChannelInfo.saEncAlg));
894 memset(&pCryptKey->siSChannelInfo.saMACAlg, 0, sizeof(pCryptKey->siSChannelInfo.saMACAlg));
895 init_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom);
896 init_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom);
897 init_data_blob(&pCryptKey->blobHmacKey);
899 switch(aiAlgid)
901 case CALG_PCT1_MASTER:
902 case CALG_SSL2_MASTER:
903 case CALG_SSL3_MASTER:
904 case CALG_TLS1_MASTER:
905 case CALG_RC4:
906 pCryptKey->dwBlockLen = 0;
907 pCryptKey->dwMode = 0;
908 break;
910 case CALG_RC2:
911 case CALG_DES:
912 case CALG_3DES_112:
913 case CALG_3DES:
914 pCryptKey->dwBlockLen = 8;
915 pCryptKey->dwMode = CRYPT_MODE_CBC;
916 break;
918 case CALG_AES_128:
919 case CALG_AES_192:
920 case CALG_AES_256:
921 pCryptKey->dwBlockLen = 16;
922 pCryptKey->dwMode = CRYPT_MODE_CBC;
923 break;
925 case CALG_RSA_KEYX:
926 case CALG_RSA_SIGN:
927 pCryptKey->dwBlockLen = dwKeyLen >> 3;
928 pCryptKey->dwMode = 0;
929 break;
931 case CALG_HMAC:
932 pCryptKey->dwBlockLen = 0;
933 pCryptKey->dwMode = 0;
934 break;
937 *ppCryptKey = pCryptKey;
940 return hCryptKey;
943 /******************************************************************************
944 * map_key_spec_to_key_pair_name [Internal]
946 * Returns the name of the registry value associated with a key spec.
948 * PARAMS
949 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
951 * RETURNS
952 * Success: Name of registry value.
953 * Failure: NULL
955 static LPCSTR map_key_spec_to_key_pair_name(DWORD dwKeySpec)
957 LPCSTR szValueName;
959 switch (dwKeySpec)
961 case AT_KEYEXCHANGE:
962 szValueName = "KeyExchangeKeyPair";
963 break;
964 case AT_SIGNATURE:
965 szValueName = "SignatureKeyPair";
966 break;
967 default:
968 WARN("invalid key spec %d\n", dwKeySpec);
969 szValueName = NULL;
971 return szValueName;
974 /******************************************************************************
975 * store_key_pair [Internal]
977 * Stores a key pair to the registry
979 * PARAMS
980 * hCryptKey [I] Handle to the key to be stored
981 * hKey [I] Registry key where the key pair is to be stored
982 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
983 * dwFlags [I] Flags for protecting the key
985 static void store_key_pair(HCRYPTKEY hCryptKey, HKEY hKey, DWORD dwKeySpec, DWORD dwFlags)
987 LPCSTR szValueName;
988 DATA_BLOB blobIn, blobOut;
989 CRYPTKEY *pKey;
990 DWORD dwLen;
991 BYTE *pbKey;
993 if (!(szValueName = map_key_spec_to_key_pair_name(dwKeySpec)))
994 return;
995 if (lookup_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY,
996 (OBJECTHDR**)&pKey))
998 if (crypt_export_key(pKey, 0, PRIVATEKEYBLOB, 0, TRUE, 0, &dwLen))
1000 pbKey = HeapAlloc(GetProcessHeap(), 0, dwLen);
1001 if (pbKey)
1003 if (crypt_export_key(pKey, 0, PRIVATEKEYBLOB, 0, TRUE, pbKey,
1004 &dwLen))
1006 blobIn.pbData = pbKey;
1007 blobIn.cbData = dwLen;
1009 if (CryptProtectData(&blobIn, NULL, NULL, NULL, NULL,
1010 dwFlags, &blobOut))
1012 RegSetValueExA(hKey, szValueName, 0, REG_BINARY,
1013 blobOut.pbData, blobOut.cbData);
1014 LocalFree(blobOut.pbData);
1017 HeapFree(GetProcessHeap(), 0, pbKey);
1023 /******************************************************************************
1024 * map_key_spec_to_permissions_name [Internal]
1026 * Returns the name of the registry value associated with the permissions for
1027 * a key spec.
1029 * PARAMS
1030 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
1032 * RETURNS
1033 * Success: Name of registry value.
1034 * Failure: NULL
1036 static LPCSTR map_key_spec_to_permissions_name(DWORD dwKeySpec)
1038 LPCSTR szValueName;
1040 switch (dwKeySpec)
1042 case AT_KEYEXCHANGE:
1043 szValueName = "KeyExchangePermissions";
1044 break;
1045 case AT_SIGNATURE:
1046 szValueName = "SignaturePermissions";
1047 break;
1048 default:
1049 WARN("invalid key spec %d\n", dwKeySpec);
1050 szValueName = NULL;
1052 return szValueName;
1055 /******************************************************************************
1056 * store_key_permissions [Internal]
1058 * Stores a key's permissions to the registry
1060 * PARAMS
1061 * hCryptKey [I] Handle to the key whose permissions are to be stored
1062 * hKey [I] Registry key where the key permissions are to be stored
1063 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
1065 static void store_key_permissions(HCRYPTKEY hCryptKey, HKEY hKey, DWORD dwKeySpec)
1067 LPCSTR szValueName;
1068 CRYPTKEY *pKey;
1070 if (!(szValueName = map_key_spec_to_permissions_name(dwKeySpec)))
1071 return;
1072 if (lookup_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY,
1073 (OBJECTHDR**)&pKey))
1074 RegSetValueExA(hKey, szValueName, 0, REG_DWORD,
1075 (BYTE *)&pKey->dwPermissions,
1076 sizeof(pKey->dwPermissions));
1079 /******************************************************************************
1080 * create_container_key [Internal]
1082 * Creates the registry key for a key container's persistent storage.
1084 * PARAMS
1085 * pKeyContainer [I] Pointer to the key container
1086 * sam [I] Desired registry access
1087 * phKey [O] Returned key
1089 static BOOL create_container_key(KEYCONTAINER *pKeyContainer, REGSAM sam, HKEY *phKey)
1091 CHAR szRSABase[sizeof(RSAENH_REGKEY) + MAX_PATH];
1092 HKEY hRootKey;
1094 sprintf(szRSABase, RSAENH_REGKEY, pKeyContainer->szName);
1096 if (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET)
1097 hRootKey = HKEY_LOCAL_MACHINE;
1098 else
1099 hRootKey = HKEY_CURRENT_USER;
1101 /* @@ Wine registry key: HKLM\Software\Wine\Crypto\RSA */
1102 /* @@ Wine registry key: HKCU\Software\Wine\Crypto\RSA */
1103 return RegCreateKeyExA(hRootKey, szRSABase, 0, NULL,
1104 REG_OPTION_NON_VOLATILE, sam, NULL, phKey, NULL)
1105 == ERROR_SUCCESS;
1108 /******************************************************************************
1109 * open_container_key [Internal]
1111 * Opens a key container's persistent storage for reading.
1113 * PARAMS
1114 * pszContainerName [I] Name of the container to be opened. May be the empty
1115 * string if the parent key of all containers is to be
1116 * opened.
1117 * dwFlags [I] Flags indicating which keyset to be opened.
1118 * phKey [O] Returned key
1120 static BOOL open_container_key(LPCSTR pszContainerName, DWORD dwFlags, REGSAM access, HKEY *phKey)
1122 CHAR szRSABase[sizeof(RSAENH_REGKEY) + MAX_PATH];
1123 HKEY hRootKey;
1125 sprintf(szRSABase, RSAENH_REGKEY, pszContainerName);
1127 if (dwFlags & CRYPT_MACHINE_KEYSET)
1128 hRootKey = HKEY_LOCAL_MACHINE;
1129 else
1130 hRootKey = HKEY_CURRENT_USER;
1132 /* @@ Wine registry key: HKLM\Software\Wine\Crypto\RSA */
1133 /* @@ Wine registry key: HKCU\Software\Wine\Crypto\RSA */
1134 return RegOpenKeyExA(hRootKey, szRSABase, 0, access, phKey) ==
1135 ERROR_SUCCESS;
1138 /******************************************************************************
1139 * delete_container_key [Internal]
1141 * Deletes a key container's persistent storage.
1143 * PARAMS
1144 * pszContainerName [I] Name of the container to be opened.
1145 * dwFlags [I] Flags indicating which keyset to be opened.
1147 static BOOL delete_container_key(LPCSTR pszContainerName, DWORD dwFlags)
1149 CHAR szRegKey[sizeof(RSAENH_REGKEY) + MAX_PATH];
1150 HKEY hRootKey;
1152 sprintf(szRegKey, RSAENH_REGKEY, pszContainerName);
1154 if (dwFlags & CRYPT_MACHINE_KEYSET)
1155 hRootKey = HKEY_LOCAL_MACHINE;
1156 else
1157 hRootKey = HKEY_CURRENT_USER;
1158 if (!RegDeleteKeyA(hRootKey, szRegKey)) {
1159 SetLastError(ERROR_SUCCESS);
1160 return TRUE;
1161 } else {
1162 SetLastError(NTE_BAD_KEYSET);
1163 return FALSE;
1167 /******************************************************************************
1168 * store_key_container_keys [Internal]
1170 * Stores key container's keys in a persistent location.
1172 * PARAMS
1173 * pKeyContainer [I] Pointer to the key container whose keys are to be saved
1175 static void store_key_container_keys(KEYCONTAINER *pKeyContainer)
1177 HKEY hKey;
1178 DWORD dwFlags;
1180 /* On WinXP, persistent keys are stored in a file located at:
1181 * $AppData$\\Microsoft\\Crypto\\RSA\\$SID$\\some_hex_string
1184 if (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET)
1185 dwFlags = CRYPTPROTECT_LOCAL_MACHINE;
1186 else
1187 dwFlags = 0;
1189 if (create_container_key(pKeyContainer, KEY_WRITE, &hKey))
1191 store_key_pair(pKeyContainer->hKeyExchangeKeyPair, hKey,
1192 AT_KEYEXCHANGE, dwFlags);
1193 store_key_pair(pKeyContainer->hSignatureKeyPair, hKey,
1194 AT_SIGNATURE, dwFlags);
1195 RegCloseKey(hKey);
1199 /******************************************************************************
1200 * store_key_container_permissions [Internal]
1202 * Stores key container's key permissions in a persistent location.
1204 * PARAMS
1205 * pKeyContainer [I] Pointer to the key container whose key permissions are to
1206 * be saved
1208 static void store_key_container_permissions(KEYCONTAINER *pKeyContainer)
1210 HKEY hKey;
1212 if (create_container_key(pKeyContainer, KEY_WRITE, &hKey))
1214 store_key_permissions(pKeyContainer->hKeyExchangeKeyPair, hKey,
1215 AT_KEYEXCHANGE);
1216 store_key_permissions(pKeyContainer->hSignatureKeyPair, hKey,
1217 AT_SIGNATURE);
1218 RegCloseKey(hKey);
1222 /******************************************************************************
1223 * release_key_container_keys [Internal]
1225 * Releases key container's keys.
1227 * PARAMS
1228 * pKeyContainer [I] Pointer to the key container whose keys are to be released.
1230 static void release_key_container_keys(KEYCONTAINER *pKeyContainer)
1232 release_handle(&handle_table, pKeyContainer->hKeyExchangeKeyPair,
1233 RSAENH_MAGIC_KEY);
1234 release_handle(&handle_table, pKeyContainer->hSignatureKeyPair,
1235 RSAENH_MAGIC_KEY);
1238 /******************************************************************************
1239 * destroy_key_container [Internal]
1241 * Destructor for key containers.
1243 * PARAMS
1244 * pObjectHdr [I] Pointer to the key container to be destroyed.
1246 static void destroy_key_container(OBJECTHDR *pObjectHdr)
1248 KEYCONTAINER *pKeyContainer = (KEYCONTAINER*)pObjectHdr;
1250 if (!(pKeyContainer->dwFlags & CRYPT_VERIFYCONTEXT))
1252 store_key_container_keys(pKeyContainer);
1253 store_key_container_permissions(pKeyContainer);
1254 release_key_container_keys(pKeyContainer);
1256 else
1257 release_key_container_keys(pKeyContainer);
1258 HeapFree( GetProcessHeap(), 0, pKeyContainer );
1261 /******************************************************************************
1262 * new_key_container [Internal]
1264 * Create a new key container. The personality (RSA Base, Strong or Enhanced CP)
1265 * of the CSP is determined via the pVTable->pszProvName string.
1267 * PARAMS
1268 * pszContainerName [I] Name of the key container.
1269 * pVTable [I] Callback functions and context info provided by the OS
1271 * RETURNS
1272 * Success: Handle to the new key container.
1273 * Failure: INVALID_HANDLE_VALUE
1275 static HCRYPTPROV new_key_container(PCCH pszContainerName, DWORD dwFlags, const VTableProvStruc *pVTable)
1277 KEYCONTAINER *pKeyContainer;
1278 HCRYPTPROV hKeyContainer;
1280 hKeyContainer = new_object(&handle_table, sizeof(KEYCONTAINER), RSAENH_MAGIC_CONTAINER,
1281 destroy_key_container, (OBJECTHDR**)&pKeyContainer);
1282 if (hKeyContainer != (HCRYPTPROV)INVALID_HANDLE_VALUE)
1284 lstrcpynA(pKeyContainer->szName, pszContainerName, MAX_PATH);
1285 pKeyContainer->dwFlags = dwFlags;
1286 pKeyContainer->dwEnumAlgsCtr = 0;
1287 pKeyContainer->hKeyExchangeKeyPair = (HCRYPTKEY)INVALID_HANDLE_VALUE;
1288 pKeyContainer->hSignatureKeyPair = (HCRYPTKEY)INVALID_HANDLE_VALUE;
1289 if (pVTable && pVTable->pszProvName) {
1290 lstrcpynA(pKeyContainer->szProvName, pVTable->pszProvName, MAX_PATH);
1291 if (!strcmp(pVTable->pszProvName, MS_DEF_PROV_A)) {
1292 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_BASE;
1293 } else if (!strcmp(pVTable->pszProvName, MS_ENHANCED_PROV_A)) {
1294 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_ENHANCED;
1295 } else if (!strcmp(pVTable->pszProvName, MS_DEF_RSA_SCHANNEL_PROV_A)) {
1296 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_SCHANNEL;
1297 } else if (!strcmp(pVTable->pszProvName, MS_ENH_RSA_AES_PROV_A) ||
1298 !strcmp(pVTable->pszProvName, MS_ENH_RSA_AES_PROV_XP_A)) {
1299 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_AES;
1300 } else {
1301 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_STRONG;
1305 /* The new key container has to be inserted into the CSP immediately
1306 * after creation to be available for CPGetProvParam's PP_ENUMCONTAINERS. */
1307 if (!(dwFlags & CRYPT_VERIFYCONTEXT)) {
1308 HKEY hKey;
1310 if (create_container_key(pKeyContainer, KEY_WRITE, &hKey))
1311 RegCloseKey(hKey);
1315 return hKeyContainer;
1318 /******************************************************************************
1319 * read_key_value [Internal]
1321 * Reads a key pair value from the registry
1323 * PARAMS
1324 * hKeyContainer [I] Crypt provider to use to import the key
1325 * hKey [I] Registry key from which to read the key pair
1326 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
1327 * dwFlags [I] Flags for unprotecting the key
1328 * phCryptKey [O] Returned key
1330 static BOOL read_key_value(HCRYPTPROV hKeyContainer, HKEY hKey, DWORD dwKeySpec, DWORD dwFlags, HCRYPTKEY *phCryptKey)
1332 LPCSTR szValueName;
1333 DWORD dwValueType, dwLen;
1334 BYTE *pbKey;
1335 DATA_BLOB blobIn, blobOut;
1336 BOOL ret = FALSE;
1338 if (!(szValueName = map_key_spec_to_key_pair_name(dwKeySpec)))
1339 return FALSE;
1340 if (RegQueryValueExA(hKey, szValueName, 0, &dwValueType, NULL, &dwLen) ==
1341 ERROR_SUCCESS)
1343 pbKey = HeapAlloc(GetProcessHeap(), 0, dwLen);
1344 if (pbKey)
1346 if (RegQueryValueExA(hKey, szValueName, 0, &dwValueType, pbKey, &dwLen) ==
1347 ERROR_SUCCESS)
1349 blobIn.pbData = pbKey;
1350 blobIn.cbData = dwLen;
1352 if (CryptUnprotectData(&blobIn, NULL, NULL, NULL, NULL,
1353 dwFlags, &blobOut))
1355 ret = import_key(hKeyContainer, blobOut.pbData, blobOut.cbData, 0, 0,
1356 FALSE, phCryptKey);
1357 LocalFree(blobOut.pbData);
1360 HeapFree(GetProcessHeap(), 0, pbKey);
1363 if (ret)
1365 CRYPTKEY *pKey;
1367 if (lookup_handle(&handle_table, *phCryptKey, RSAENH_MAGIC_KEY,
1368 (OBJECTHDR**)&pKey))
1370 if ((szValueName = map_key_spec_to_permissions_name(dwKeySpec)))
1372 dwLen = sizeof(pKey->dwPermissions);
1373 RegQueryValueExA(hKey, szValueName, 0, NULL,
1374 (BYTE *)&pKey->dwPermissions, &dwLen);
1378 return ret;
1381 /******************************************************************************
1382 * read_key_container [Internal]
1384 * Tries to read the persistent state of the key container (mainly the signature
1385 * and key exchange private keys) given by pszContainerName.
1387 * PARAMS
1388 * pszContainerName [I] Name of the key container to read from the registry
1389 * pVTable [I] Pointer to context data provided by the operating system
1391 * RETURNS
1392 * Success: Handle to the key container read from the registry
1393 * Failure: INVALID_HANDLE_VALUE
1395 static HCRYPTPROV read_key_container(PCHAR pszContainerName, DWORD dwFlags, const VTableProvStruc *pVTable)
1397 HKEY hKey;
1398 KEYCONTAINER *pKeyContainer;
1399 HCRYPTPROV hKeyContainer;
1400 HCRYPTKEY hCryptKey;
1402 if (!open_container_key(pszContainerName, dwFlags, KEY_READ, &hKey))
1404 SetLastError(NTE_BAD_KEYSET);
1405 return (HCRYPTPROV)INVALID_HANDLE_VALUE;
1408 hKeyContainer = new_key_container(pszContainerName, dwFlags, pVTable);
1409 if (hKeyContainer != (HCRYPTPROV)INVALID_HANDLE_VALUE)
1411 DWORD dwProtectFlags = (dwFlags & CRYPT_MACHINE_KEYSET) ?
1412 CRYPTPROTECT_LOCAL_MACHINE : 0;
1414 if (!lookup_handle(&handle_table, hKeyContainer, RSAENH_MAGIC_CONTAINER,
1415 (OBJECTHDR**)&pKeyContainer))
1416 return (HCRYPTPROV)INVALID_HANDLE_VALUE;
1418 /* read_key_value calls import_key, which calls import_private_key,
1419 * which implicitly installs the key value into the appropriate key
1420 * container key. Thus the ref count is incremented twice, once for
1421 * the output key value, and once for the implicit install, and needs
1422 * to be decremented to balance the two.
1424 if (read_key_value(hKeyContainer, hKey, AT_KEYEXCHANGE,
1425 dwProtectFlags, &hCryptKey))
1426 release_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY);
1427 if (read_key_value(hKeyContainer, hKey, AT_SIGNATURE,
1428 dwProtectFlags, &hCryptKey))
1429 release_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY);
1432 return hKeyContainer;
1435 /******************************************************************************
1436 * build_hash_signature [Internal]
1438 * Builds a padded version of a hash to match the length of the RSA key modulus.
1440 * PARAMS
1441 * pbSignature [O] The padded hash object is stored here.
1442 * dwLen [I] Length of the pbSignature buffer.
1443 * aiAlgid [I] Algorithm identifier of the hash to be padded.
1444 * abHashValue [I] The value of the hash object.
1445 * dwHashLen [I] Length of the hash value.
1446 * dwFlags [I] Selection of padding algorithm.
1448 * RETURNS
1449 * Success: TRUE
1450 * Failure: FALSE (NTE_BAD_ALGID)
1452 static BOOL build_hash_signature(BYTE *pbSignature, DWORD dwLen, ALG_ID aiAlgid,
1453 const BYTE *abHashValue, DWORD dwHashLen, DWORD dwFlags)
1455 /* These prefixes are meant to be concatenated with hash values of the
1456 * respective kind to form a PKCS #7 DigestInfo. */
1457 static const struct tagOIDDescriptor {
1458 ALG_ID aiAlgid;
1459 DWORD dwLen;
1460 const BYTE abOID[19];
1461 } aOIDDescriptor[] = {
1462 { CALG_MD2, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48,
1463 0x86, 0xf7, 0x0d, 0x02, 0x02, 0x05, 0x00, 0x04, 0x10 } },
1464 { CALG_MD4, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48,
1465 0x86, 0xf7, 0x0d, 0x02, 0x04, 0x05, 0x00, 0x04, 0x10 } },
1466 { CALG_MD5, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48,
1467 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10 } },
1468 { CALG_SHA, 15, { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
1469 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 } },
1470 { CALG_SHA_256, 19, { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
1471 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01,
1472 0x05, 0x00, 0x04, 0x20 } },
1473 { CALG_SHA_384, 19, { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
1474 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02,
1475 0x05, 0x00, 0x04, 0x30 } },
1476 { CALG_SHA_512, 19, { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
1477 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03,
1478 0x05, 0x00, 0x04, 0x40 } },
1479 { CALG_SSL3_SHAMD5, 0, { 0 } },
1480 { 0, 0, { 0 } }
1482 DWORD dwIdxOID, i, j;
1484 for (dwIdxOID = 0; aOIDDescriptor[dwIdxOID].aiAlgid; dwIdxOID++) {
1485 if (aOIDDescriptor[dwIdxOID].aiAlgid == aiAlgid) break;
1488 if (!aOIDDescriptor[dwIdxOID].aiAlgid) {
1489 SetLastError(NTE_BAD_ALGID);
1490 return FALSE;
1493 /* Build the padded signature */
1494 if (dwFlags & CRYPT_X931_FORMAT) {
1495 pbSignature[0] = 0x6b;
1496 for (i=1; i < dwLen - dwHashLen - 3; i++) {
1497 pbSignature[i] = 0xbb;
1499 pbSignature[i++] = 0xba;
1500 for (j=0; j < dwHashLen; j++, i++) {
1501 pbSignature[i] = abHashValue[j];
1503 pbSignature[i++] = 0x33;
1504 pbSignature[i++] = 0xcc;
1505 } else {
1506 pbSignature[0] = 0x00;
1507 pbSignature[1] = 0x01;
1508 if (dwFlags & CRYPT_NOHASHOID) {
1509 for (i=2; i < dwLen - 1 - dwHashLen; i++) {
1510 pbSignature[i] = 0xff;
1512 pbSignature[i++] = 0x00;
1513 } else {
1514 for (i=2; i < dwLen - 1 - aOIDDescriptor[dwIdxOID].dwLen - dwHashLen; i++) {
1515 pbSignature[i] = 0xff;
1517 pbSignature[i++] = 0x00;
1518 for (j=0; j < aOIDDescriptor[dwIdxOID].dwLen; j++) {
1519 pbSignature[i++] = aOIDDescriptor[dwIdxOID].abOID[j];
1522 for (j=0; j < dwHashLen; j++) {
1523 pbSignature[i++] = abHashValue[j];
1527 return TRUE;
1530 /******************************************************************************
1531 * tls1_p [Internal]
1533 * This is an implementation of the 'P_hash' helper function for TLS1's PRF.
1534 * It is used exclusively by tls1_prf. For details see RFC 2246, chapter 5.
1535 * The pseudo random stream generated by this function is exclusive or'ed with
1536 * the data in pbBuffer.
1538 * PARAMS
1539 * hHMAC [I] HMAC object, which will be used in pseudo random generation
1540 * pblobSeed [I] Seed value
1541 * pbBuffer [I/O] Pseudo random stream will be xor'ed to the provided data
1542 * dwBufferLen [I] Number of pseudo random bytes desired
1544 * RETURNS
1545 * Success: TRUE
1546 * Failure: FALSE
1548 static BOOL tls1_p(HCRYPTHASH hHMAC, const PCRYPT_DATA_BLOB pblobSeed, BYTE *pbBuffer,
1549 DWORD dwBufferLen)
1551 CRYPTHASH *pHMAC;
1552 BYTE abAi[RSAENH_MAX_HASH_SIZE];
1553 DWORD i = 0;
1555 if (!lookup_handle(&handle_table, hHMAC, RSAENH_MAGIC_HASH, (OBJECTHDR**)&pHMAC)) {
1556 SetLastError(NTE_BAD_HASH);
1557 return FALSE;
1560 /* compute A_1 = HMAC(seed) */
1561 init_hash(pHMAC);
1562 update_hash(pHMAC, pblobSeed->pbData, pblobSeed->cbData);
1563 finalize_hash(pHMAC);
1564 memcpy(abAi, pHMAC->abHashValue, pHMAC->dwHashSize);
1566 do {
1567 /* compute HMAC(A_i + seed) */
1568 init_hash(pHMAC);
1569 update_hash(pHMAC, abAi, pHMAC->dwHashSize);
1570 update_hash(pHMAC, pblobSeed->pbData, pblobSeed->cbData);
1571 finalize_hash(pHMAC);
1573 /* pseudo random stream := CONCAT_{i=1..n} ( HMAC(A_i + seed) ) */
1574 do {
1575 if (i >= dwBufferLen) break;
1576 pbBuffer[i] ^= pHMAC->abHashValue[i % pHMAC->dwHashSize];
1577 i++;
1578 } while (i % pHMAC->dwHashSize);
1580 /* compute A_{i+1} = HMAC(A_i) */
1581 init_hash(pHMAC);
1582 update_hash(pHMAC, abAi, pHMAC->dwHashSize);
1583 finalize_hash(pHMAC);
1584 memcpy(abAi, pHMAC->abHashValue, pHMAC->dwHashSize);
1585 } while (i < dwBufferLen);
1587 return TRUE;
1590 /******************************************************************************
1591 * tls1_prf [Internal]
1593 * TLS1 pseudo random function as specified in RFC 2246, chapter 5
1595 * PARAMS
1596 * hProv [I] Key container used to compute the pseudo random stream
1597 * hSecret [I] Key that holds the (pre-)master secret
1598 * pblobLabel [I] Descriptive label
1599 * pblobSeed [I] Seed value
1600 * pbBuffer [O] Pseudo random numbers will be stored here
1601 * dwBufferLen [I] Number of pseudo random bytes desired
1603 * RETURNS
1604 * Success: TRUE
1605 * Failure: FALSE
1607 static BOOL tls1_prf(HCRYPTPROV hProv, HCRYPTPROV hSecret, const PCRYPT_DATA_BLOB pblobLabel,
1608 const PCRYPT_DATA_BLOB pblobSeed, BYTE *pbBuffer, DWORD dwBufferLen)
1610 HMAC_INFO hmacInfo = { 0, NULL, 0, NULL, 0 };
1611 HCRYPTHASH hHMAC = (HCRYPTHASH)INVALID_HANDLE_VALUE;
1612 HCRYPTKEY hHalfSecret = (HCRYPTKEY)INVALID_HANDLE_VALUE;
1613 CRYPTKEY *pHalfSecret, *pSecret;
1614 DWORD dwHalfSecretLen;
1615 BOOL result = FALSE;
1616 CRYPT_DATA_BLOB blobLabelSeed;
1618 TRACE("(hProv=%08lx, hSecret=%08lx, pblobLabel=%p, pblobSeed=%p, pbBuffer=%p, dwBufferLen=%d)\n",
1619 hProv, hSecret, pblobLabel, pblobSeed, pbBuffer, dwBufferLen);
1621 if (!lookup_handle(&handle_table, hSecret, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pSecret)) {
1622 SetLastError(NTE_FAIL);
1623 return FALSE;
1626 dwHalfSecretLen = (pSecret->dwKeyLen+1)/2;
1628 /* concatenation of the label and the seed */
1629 if (!concat_data_blobs(&blobLabelSeed, pblobLabel, pblobSeed)) goto exit;
1631 /* zero out the buffer, since two random streams will be xor'ed into it. */
1632 memset(pbBuffer, 0, dwBufferLen);
1634 /* build a 'fake' key, to hold the secret. CALG_SSL2_MASTER is used since it provides
1635 * the biggest range of valid key lengths. */
1636 hHalfSecret = new_key(hProv, CALG_SSL2_MASTER, MAKELONG(0,dwHalfSecretLen*8), &pHalfSecret);
1637 if (hHalfSecret == (HCRYPTKEY)INVALID_HANDLE_VALUE) goto exit;
1639 /* Derive an HMAC_MD5 hash and call the helper function. */
1640 memcpy(pHalfSecret->abKeyValue, pSecret->abKeyValue, dwHalfSecretLen);
1641 if (!RSAENH_CPCreateHash(hProv, CALG_HMAC, hHalfSecret, 0, &hHMAC)) goto exit;
1642 hmacInfo.HashAlgid = CALG_MD5;
1643 if (!RSAENH_CPSetHashParam(hProv, hHMAC, HP_HMAC_INFO, (BYTE*)&hmacInfo, 0)) goto exit;
1644 if (!tls1_p(hHMAC, &blobLabelSeed, pbBuffer, dwBufferLen)) goto exit;
1646 /* Reconfigure to HMAC_SHA hash and call helper function again. */
1647 memcpy(pHalfSecret->abKeyValue, pSecret->abKeyValue + (pSecret->dwKeyLen/2), dwHalfSecretLen);
1648 hmacInfo.HashAlgid = CALG_SHA;
1649 if (!RSAENH_CPSetHashParam(hProv, hHMAC, HP_HMAC_INFO, (BYTE*)&hmacInfo, 0)) goto exit;
1650 if (!tls1_p(hHMAC, &blobLabelSeed, pbBuffer, dwBufferLen)) goto exit;
1652 result = TRUE;
1653 exit:
1654 release_handle(&handle_table, hHalfSecret, RSAENH_MAGIC_KEY);
1655 if (hHMAC != (HCRYPTHASH)INVALID_HANDLE_VALUE) RSAENH_CPDestroyHash(hProv, hHMAC);
1656 free_data_blob(&blobLabelSeed);
1657 return result;
1660 /******************************************************************************
1661 * pad_data [Internal]
1663 * Helper function for data padding according to PKCS1 #2
1665 * PARAMS
1666 * abData [I] The data to be padded
1667 * dwDataLen [I] Length of the data
1668 * abBuffer [O] Padded data will be stored here
1669 * dwBufferLen [I] Length of the buffer (also length of padded data)
1670 * dwFlags [I] Padding format (CRYPT_SSL2_FALLBACK)
1672 * RETURN
1673 * Success: TRUE
1674 * Failure: FALSE (NTE_BAD_LEN, too much data to pad)
1676 static BOOL pad_data(const BYTE *abData, DWORD dwDataLen, BYTE *abBuffer, DWORD dwBufferLen,
1677 DWORD dwFlags)
1679 DWORD i;
1681 /* Ensure there is enough space for PKCS1 #2 padding */
1682 if (dwDataLen > dwBufferLen-11) {
1683 SetLastError(NTE_BAD_LEN);
1684 return FALSE;
1687 memmove(abBuffer + dwBufferLen - dwDataLen, abData, dwDataLen);
1689 abBuffer[0] = 0x00;
1690 abBuffer[1] = RSAENH_PKC_BLOCKTYPE;
1691 for (i=2; i < dwBufferLen - dwDataLen - 1; i++)
1692 do gen_rand_impl(&abBuffer[i], 1); while (!abBuffer[i]);
1693 if (dwFlags & CRYPT_SSL2_FALLBACK)
1694 for (i-=8; i < dwBufferLen - dwDataLen - 1; i++)
1695 abBuffer[i] = 0x03;
1696 abBuffer[i] = 0x00;
1698 return TRUE;
1701 /******************************************************************************
1702 * unpad_data [Internal]
1704 * Remove the PKCS1 padding from RSA decrypted data
1706 * PARAMS
1707 * abData [I] The padded data
1708 * dwDataLen [I] Length of the padded data
1709 * abBuffer [O] Data without padding will be stored here
1710 * dwBufferLen [I/O] I: Length of the buffer, O: Length of unpadded data
1711 * dwFlags [I] Currently none defined
1713 * RETURNS
1714 * Success: TRUE
1715 * Failure: FALSE, (NTE_BAD_DATA, no valid PKCS1 padding or buffer too small)
1717 static BOOL unpad_data(const BYTE *abData, DWORD dwDataLen, BYTE *abBuffer, DWORD *dwBufferLen,
1718 DWORD dwFlags)
1720 DWORD i;
1722 if (dwDataLen < 3)
1724 SetLastError(NTE_BAD_DATA);
1725 return FALSE;
1727 for (i=2; i<dwDataLen; i++)
1728 if (!abData[i])
1729 break;
1731 if ((i == dwDataLen) || (*dwBufferLen < dwDataLen - i - 1) ||
1732 (abData[0] != 0x00) || (abData[1] != RSAENH_PKC_BLOCKTYPE))
1734 SetLastError(NTE_BAD_DATA);
1735 return FALSE;
1738 *dwBufferLen = dwDataLen - i - 1;
1739 memmove(abBuffer, abData + i + 1, *dwBufferLen);
1740 return TRUE;
1743 /******************************************************************************
1744 * CPAcquireContext (RSAENH.@)
1746 * Acquire a handle to the key container specified by pszContainer
1748 * PARAMS
1749 * phProv [O] Pointer to the location the acquired handle will be written to.
1750 * pszContainer [I] Name of the desired key container. See Notes
1751 * dwFlags [I] Flags. See Notes.
1752 * pVTable [I] Pointer to a PVTableProvStruct containing callbacks.
1754 * RETURNS
1755 * Success: TRUE
1756 * Failure: FALSE
1758 * NOTES
1759 * If pszContainer is NULL or points to a zero length string the user's login
1760 * name will be used as the key container name.
1762 * If the CRYPT_NEW_KEYSET flag is set in dwFlags a new keyset will be created.
1763 * If a keyset with the given name already exists, the function fails and sets
1764 * last error to NTE_EXISTS. If CRYPT_NEW_KEYSET is not set and the specified
1765 * key container does not exist, function fails and sets last error to
1766 * NTE_BAD_KEYSET.
1768 BOOL WINAPI RSAENH_CPAcquireContext(HCRYPTPROV *phProv, LPSTR pszContainer,
1769 DWORD dwFlags, PVTableProvStruc pVTable)
1771 CHAR szKeyContainerName[MAX_PATH];
1773 TRACE("(phProv=%p, pszContainer=%s, dwFlags=%08x, pVTable=%p)\n", phProv,
1774 debugstr_a(pszContainer), dwFlags, pVTable);
1776 if (pszContainer && *pszContainer)
1778 lstrcpynA(szKeyContainerName, pszContainer, MAX_PATH);
1780 else
1782 DWORD dwLen = sizeof(szKeyContainerName);
1783 if (!GetUserNameA(szKeyContainerName, &dwLen)) return FALSE;
1786 switch (dwFlags & (CRYPT_NEWKEYSET|CRYPT_VERIFYCONTEXT|CRYPT_DELETEKEYSET))
1788 case 0:
1789 *phProv = read_key_container(szKeyContainerName, dwFlags, pVTable);
1790 break;
1792 case CRYPT_DELETEKEYSET:
1793 return delete_container_key(szKeyContainerName, dwFlags);
1795 case CRYPT_NEWKEYSET:
1796 *phProv = read_key_container(szKeyContainerName, dwFlags, pVTable);
1797 if (*phProv != (HCRYPTPROV)INVALID_HANDLE_VALUE)
1799 release_handle(&handle_table, *phProv, RSAENH_MAGIC_CONTAINER);
1800 TRACE("Can't create new keyset, already exists\n");
1801 SetLastError(NTE_EXISTS);
1802 return FALSE;
1804 *phProv = new_key_container(szKeyContainerName, dwFlags, pVTable);
1805 break;
1807 case CRYPT_VERIFYCONTEXT|CRYPT_NEWKEYSET:
1808 case CRYPT_VERIFYCONTEXT:
1809 if (pszContainer && *pszContainer) {
1810 TRACE("pszContainer should be empty\n");
1811 SetLastError(NTE_BAD_FLAGS);
1812 return FALSE;
1814 *phProv = new_key_container("", dwFlags, pVTable);
1815 break;
1817 default:
1818 *phProv = (HCRYPTPROV)INVALID_HANDLE_VALUE;
1819 SetLastError(NTE_BAD_FLAGS);
1820 return FALSE;
1823 if (*phProv != (HCRYPTPROV)INVALID_HANDLE_VALUE) {
1824 SetLastError(ERROR_SUCCESS);
1825 return TRUE;
1826 } else {
1827 return FALSE;
1831 /******************************************************************************
1832 * CPCreateHash (RSAENH.@)
1834 * CPCreateHash creates and initializes a new hash object.
1836 * PARAMS
1837 * hProv [I] Handle to the key container to which the new hash will belong.
1838 * Algid [I] Identifies the hash algorithm, which will be used for the hash.
1839 * hKey [I] Handle to a session key applied for keyed hashes.
1840 * dwFlags [I] Currently no flags defined. Must be zero.
1841 * phHash [O] Points to the location where a handle to the new hash will be stored.
1843 * RETURNS
1844 * Success: TRUE
1845 * Failure: FALSE
1847 * NOTES
1848 * hKey is a handle to a session key applied in keyed hashes like MAC and HMAC.
1849 * If a normal hash object is to be created (like e.g. MD2 or SHA1) hKey must be zero.
1851 BOOL WINAPI RSAENH_CPCreateHash(HCRYPTPROV hProv, ALG_ID Algid, HCRYPTKEY hKey, DWORD dwFlags,
1852 HCRYPTHASH *phHash)
1854 CRYPTKEY *pCryptKey;
1855 CRYPTHASH *pCryptHash;
1856 const PROV_ENUMALGS_EX *peaAlgidInfo;
1858 TRACE("(hProv=%08lx, Algid=%08x, hKey=%08lx, dwFlags=%08x, phHash=%p)\n", hProv, Algid, hKey,
1859 dwFlags, phHash);
1861 peaAlgidInfo = get_algid_info(hProv, Algid);
1862 if (!peaAlgidInfo) return FALSE;
1864 if (dwFlags)
1866 SetLastError(NTE_BAD_FLAGS);
1867 return FALSE;
1870 if (Algid == CALG_MAC || Algid == CALG_HMAC || Algid == CALG_SCHANNEL_MASTER_HASH ||
1871 Algid == CALG_TLS1PRF)
1873 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey)) {
1874 SetLastError(NTE_BAD_KEY);
1875 return FALSE;
1878 if ((Algid == CALG_MAC) && (GET_ALG_TYPE(pCryptKey->aiAlgid) != ALG_TYPE_BLOCK)) {
1879 SetLastError(NTE_BAD_KEY);
1880 return FALSE;
1883 if ((Algid == CALG_SCHANNEL_MASTER_HASH || Algid == CALG_TLS1PRF) &&
1884 (pCryptKey->aiAlgid != CALG_TLS1_MASTER))
1886 SetLastError(NTE_BAD_KEY);
1887 return FALSE;
1889 if (Algid == CALG_SCHANNEL_MASTER_HASH &&
1890 ((!pCryptKey->siSChannelInfo.blobClientRandom.cbData) ||
1891 (!pCryptKey->siSChannelInfo.blobServerRandom.cbData)))
1893 SetLastError(ERROR_INVALID_PARAMETER);
1894 return FALSE;
1897 if ((Algid == CALG_TLS1PRF) && (pCryptKey->dwState != RSAENH_KEYSTATE_MASTERKEY)) {
1898 SetLastError(NTE_BAD_KEY_STATE);
1899 return FALSE;
1903 *phHash = new_object(&handle_table, sizeof(CRYPTHASH), RSAENH_MAGIC_HASH,
1904 destroy_hash, (OBJECTHDR**)&pCryptHash);
1905 if (!pCryptHash) return FALSE;
1907 pCryptHash->aiAlgid = Algid;
1908 pCryptHash->hKey = hKey;
1909 pCryptHash->hProv = hProv;
1910 pCryptHash->dwState = RSAENH_HASHSTATE_HASHING;
1911 pCryptHash->pHMACInfo = NULL;
1912 pCryptHash->dwHashSize = peaAlgidInfo->dwDefaultLen >> 3;
1913 init_data_blob(&pCryptHash->tpPRFParams.blobLabel);
1914 init_data_blob(&pCryptHash->tpPRFParams.blobSeed);
1916 if (Algid == CALG_SCHANNEL_MASTER_HASH) {
1917 static const char keyex[] = "key expansion";
1918 BYTE key_expansion[sizeof keyex];
1919 CRYPT_DATA_BLOB blobRandom, blobKeyExpansion = { 13, key_expansion };
1921 memcpy( key_expansion, keyex, sizeof keyex );
1923 if (pCryptKey->dwState != RSAENH_KEYSTATE_MASTERKEY) {
1924 static const char msec[] = "master secret";
1925 BYTE master_secret[sizeof msec];
1926 CRYPT_DATA_BLOB blobLabel = { 13, master_secret };
1927 BYTE abKeyValue[48];
1929 memcpy( master_secret, msec, sizeof msec );
1931 /* See RFC 2246, chapter 8.1 */
1932 if (!concat_data_blobs(&blobRandom,
1933 &pCryptKey->siSChannelInfo.blobClientRandom,
1934 &pCryptKey->siSChannelInfo.blobServerRandom))
1936 return FALSE;
1938 tls1_prf(hProv, hKey, &blobLabel, &blobRandom, abKeyValue, 48);
1939 pCryptKey->dwState = RSAENH_KEYSTATE_MASTERKEY;
1940 memcpy(pCryptKey->abKeyValue, abKeyValue, 48);
1941 free_data_blob(&blobRandom);
1944 /* See RFC 2246, chapter 6.3 */
1945 if (!concat_data_blobs(&blobRandom,
1946 &pCryptKey->siSChannelInfo.blobServerRandom,
1947 &pCryptKey->siSChannelInfo.blobClientRandom))
1949 return FALSE;
1951 tls1_prf(hProv, hKey, &blobKeyExpansion, &blobRandom, pCryptHash->abHashValue,
1952 RSAENH_MAX_HASH_SIZE);
1953 free_data_blob(&blobRandom);
1956 return init_hash(pCryptHash);
1959 /******************************************************************************
1960 * CPDestroyHash (RSAENH.@)
1962 * Releases the handle to a hash object. The object is destroyed if its reference
1963 * count reaches zero.
1965 * PARAMS
1966 * hProv [I] Handle to the key container to which the hash object belongs.
1967 * hHash [I] Handle to the hash object to be released.
1969 * RETURNS
1970 * Success: TRUE
1971 * Failure: FALSE
1973 BOOL WINAPI RSAENH_CPDestroyHash(HCRYPTPROV hProv, HCRYPTHASH hHash)
1975 TRACE("(hProv=%08lx, hHash=%08lx)\n", hProv, hHash);
1977 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
1979 SetLastError(NTE_BAD_UID);
1980 return FALSE;
1983 if (!release_handle(&handle_table, hHash, RSAENH_MAGIC_HASH))
1985 SetLastError(NTE_BAD_HASH);
1986 return FALSE;
1989 return TRUE;
1992 /******************************************************************************
1993 * CPDestroyKey (RSAENH.@)
1995 * Releases the handle to a key object. The object is destroyed if its reference
1996 * count reaches zero.
1998 * PARAMS
1999 * hProv [I] Handle to the key container to which the key object belongs.
2000 * hKey [I] Handle to the key object to be released.
2002 * RETURNS
2003 * Success: TRUE
2004 * Failure: FALSE
2006 BOOL WINAPI RSAENH_CPDestroyKey(HCRYPTPROV hProv, HCRYPTKEY hKey)
2008 TRACE("(hProv=%08lx, hKey=%08lx)\n", hProv, hKey);
2010 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2012 SetLastError(NTE_BAD_UID);
2013 return FALSE;
2016 if (!release_handle(&handle_table, hKey, RSAENH_MAGIC_KEY))
2018 SetLastError(NTE_BAD_KEY);
2019 return FALSE;
2022 return TRUE;
2025 /******************************************************************************
2026 * CPDuplicateHash (RSAENH.@)
2028 * Clones a hash object including its current state.
2030 * PARAMS
2031 * hUID [I] Handle to the key container the hash belongs to.
2032 * hHash [I] Handle to the hash object to be cloned.
2033 * pdwReserved [I] Reserved. Must be NULL.
2034 * dwFlags [I] No flags are currently defined. Must be 0.
2035 * phHash [O] Handle to the cloned hash object.
2037 * RETURNS
2038 * Success: TRUE.
2039 * Failure: FALSE.
2041 BOOL WINAPI RSAENH_CPDuplicateHash(HCRYPTPROV hUID, HCRYPTHASH hHash, DWORD *pdwReserved,
2042 DWORD dwFlags, HCRYPTHASH *phHash)
2044 CRYPTHASH *pSrcHash, *pDestHash;
2046 TRACE("(hUID=%08lx, hHash=%08lx, pdwReserved=%p, dwFlags=%08x, phHash=%p)\n", hUID, hHash,
2047 pdwReserved, dwFlags, phHash);
2049 if (!is_valid_handle(&handle_table, hUID, RSAENH_MAGIC_CONTAINER))
2051 SetLastError(NTE_BAD_UID);
2052 return FALSE;
2055 if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH, (OBJECTHDR**)&pSrcHash))
2057 SetLastError(NTE_BAD_HASH);
2058 return FALSE;
2061 if (!phHash || pdwReserved || dwFlags)
2063 SetLastError(ERROR_INVALID_PARAMETER);
2064 return FALSE;
2067 *phHash = new_object(&handle_table, sizeof(CRYPTHASH), RSAENH_MAGIC_HASH,
2068 destroy_hash, (OBJECTHDR**)&pDestHash);
2069 if (*phHash != (HCRYPTHASH)INVALID_HANDLE_VALUE)
2071 *pDestHash = *pSrcHash;
2072 duplicate_hash_impl(pSrcHash->aiAlgid, &pSrcHash->context, &pDestHash->context);
2073 copy_hmac_info(&pDestHash->pHMACInfo, pSrcHash->pHMACInfo);
2074 copy_data_blob(&pDestHash->tpPRFParams.blobLabel, &pSrcHash->tpPRFParams.blobLabel);
2075 copy_data_blob(&pDestHash->tpPRFParams.blobSeed, &pSrcHash->tpPRFParams.blobSeed);
2078 return *phHash != (HCRYPTHASH)INVALID_HANDLE_VALUE;
2081 /******************************************************************************
2082 * CPDuplicateKey (RSAENH.@)
2084 * Clones a key object including its current state.
2086 * PARAMS
2087 * hUID [I] Handle to the key container the hash belongs to.
2088 * hKey [I] Handle to the key object to be cloned.
2089 * pdwReserved [I] Reserved. Must be NULL.
2090 * dwFlags [I] No flags are currently defined. Must be 0.
2091 * phHash [O] Handle to the cloned key object.
2093 * RETURNS
2094 * Success: TRUE.
2095 * Failure: FALSE.
2097 BOOL WINAPI RSAENH_CPDuplicateKey(HCRYPTPROV hUID, HCRYPTKEY hKey, DWORD *pdwReserved,
2098 DWORD dwFlags, HCRYPTKEY *phKey)
2100 CRYPTKEY *pSrcKey, *pDestKey;
2102 TRACE("(hUID=%08lx, hKey=%08lx, pdwReserved=%p, dwFlags=%08x, phKey=%p)\n", hUID, hKey,
2103 pdwReserved, dwFlags, phKey);
2105 if (!is_valid_handle(&handle_table, hUID, RSAENH_MAGIC_CONTAINER))
2107 SetLastError(NTE_BAD_UID);
2108 return FALSE;
2111 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pSrcKey))
2113 SetLastError(NTE_BAD_KEY);
2114 return FALSE;
2117 if (!phKey || pdwReserved || dwFlags)
2119 SetLastError(ERROR_INVALID_PARAMETER);
2120 return FALSE;
2123 *phKey = new_object(&handle_table, sizeof(CRYPTKEY), RSAENH_MAGIC_KEY, destroy_key,
2124 (OBJECTHDR**)&pDestKey);
2125 if (*phKey != (HCRYPTKEY)INVALID_HANDLE_VALUE)
2127 *pDestKey = *pSrcKey;
2128 copy_data_blob(&pDestKey->siSChannelInfo.blobServerRandom,
2129 &pSrcKey->siSChannelInfo.blobServerRandom);
2130 copy_data_blob(&pDestKey->siSChannelInfo.blobClientRandom,
2131 &pSrcKey->siSChannelInfo.blobClientRandom);
2132 duplicate_key_impl(pSrcKey->aiAlgid, &pSrcKey->context, &pDestKey->context);
2133 return TRUE;
2135 else
2137 return FALSE;
2141 /******************************************************************************
2142 * CPEncrypt (RSAENH.@)
2144 * Encrypt data.
2146 * PARAMS
2147 * hProv [I] The key container hKey and hHash belong to.
2148 * hKey [I] The key used to encrypt the data.
2149 * hHash [I] An optional hash object for parallel hashing. See notes.
2150 * Final [I] Indicates if this is the last block of data to encrypt.
2151 * dwFlags [I] Currently no flags defined. Must be zero.
2152 * pbData [I/O] Pointer to the data to encrypt. Encrypted data will also be stored there.
2153 * pdwDataLen [I/O] I: Length of data to encrypt, O: Length of encrypted data.
2154 * dwBufLen [I] Size of the buffer at pbData.
2156 * RETURNS
2157 * Success: TRUE.
2158 * Failure: FALSE.
2160 * NOTES
2161 * If a hash object handle is provided in hHash, it will be updated with the plaintext.
2162 * This is useful for message signatures.
2164 * This function uses the standard WINAPI protocol for querying data of dynamic length.
2166 BOOL WINAPI RSAENH_CPEncrypt(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final,
2167 DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen, DWORD dwBufLen)
2169 CRYPTKEY *pCryptKey;
2170 BYTE *in, out[RSAENH_MAX_BLOCK_SIZE], o[RSAENH_MAX_BLOCK_SIZE];
2171 DWORD dwEncryptedLen, i, j, k;
2173 TRACE("(hProv=%08lx, hKey=%08lx, hHash=%08lx, Final=%d, dwFlags=%08x, pbData=%p, "
2174 "pdwDataLen=%p, dwBufLen=%d)\n", hProv, hKey, hHash, Final, dwFlags, pbData, pdwDataLen,
2175 dwBufLen);
2177 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2179 SetLastError(NTE_BAD_UID);
2180 return FALSE;
2183 if (dwFlags)
2185 SetLastError(NTE_BAD_FLAGS);
2186 return FALSE;
2189 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2191 SetLastError(NTE_BAD_KEY);
2192 return FALSE;
2195 if (pCryptKey->dwState == RSAENH_KEYSTATE_IDLE)
2196 pCryptKey->dwState = RSAENH_KEYSTATE_ENCRYPTING;
2198 if (pCryptKey->dwState != RSAENH_KEYSTATE_ENCRYPTING)
2200 SetLastError(NTE_BAD_DATA);
2201 return FALSE;
2204 if (is_valid_handle(&handle_table, hHash, RSAENH_MAGIC_HASH)) {
2205 if (!RSAENH_CPHashData(hProv, hHash, pbData, *pdwDataLen, 0)) return FALSE;
2208 if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_BLOCK) {
2209 if (!Final && (*pdwDataLen % pCryptKey->dwBlockLen)) {
2210 SetLastError(NTE_BAD_DATA);
2211 return FALSE;
2214 dwEncryptedLen = (*pdwDataLen/pCryptKey->dwBlockLen+(Final?1:0))*pCryptKey->dwBlockLen;
2216 if (pbData == NULL) {
2217 *pdwDataLen = dwEncryptedLen;
2218 return TRUE;
2220 else if (dwEncryptedLen > dwBufLen) {
2221 *pdwDataLen = dwEncryptedLen;
2222 SetLastError(ERROR_MORE_DATA);
2223 return FALSE;
2226 /* Pad final block with length bytes */
2227 for (i=*pdwDataLen; i<dwEncryptedLen; i++) pbData[i] = dwEncryptedLen - *pdwDataLen;
2228 *pdwDataLen = dwEncryptedLen;
2230 for (i=0, in=pbData; i<*pdwDataLen; i+=pCryptKey->dwBlockLen, in+=pCryptKey->dwBlockLen) {
2231 switch (pCryptKey->dwMode) {
2232 case CRYPT_MODE_ECB:
2233 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out,
2234 RSAENH_ENCRYPT);
2235 break;
2237 case CRYPT_MODE_CBC:
2238 for (j=0; j<pCryptKey->dwBlockLen; j++) in[j] ^= pCryptKey->abChainVector[j];
2239 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out,
2240 RSAENH_ENCRYPT);
2241 memcpy(pCryptKey->abChainVector, out, pCryptKey->dwBlockLen);
2242 break;
2244 case CRYPT_MODE_CFB:
2245 for (j=0; j<pCryptKey->dwBlockLen; j++) {
2246 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context,
2247 pCryptKey->abChainVector, o, RSAENH_ENCRYPT);
2248 out[j] = in[j] ^ o[0];
2249 for (k=0; k<pCryptKey->dwBlockLen-1; k++)
2250 pCryptKey->abChainVector[k] = pCryptKey->abChainVector[k+1];
2251 pCryptKey->abChainVector[k] = out[j];
2253 break;
2255 default:
2256 SetLastError(NTE_BAD_ALGID);
2257 return FALSE;
2259 memcpy(in, out, pCryptKey->dwBlockLen);
2261 } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_STREAM) {
2262 if (pbData == NULL) {
2263 *pdwDataLen = dwBufLen;
2264 return TRUE;
2266 encrypt_stream_impl(pCryptKey->aiAlgid, &pCryptKey->context, pbData, *pdwDataLen);
2267 } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_RSA) {
2268 if (pCryptKey->aiAlgid == CALG_RSA_SIGN) {
2269 SetLastError(NTE_BAD_KEY);
2270 return FALSE;
2272 if (!pbData) {
2273 *pdwDataLen = pCryptKey->dwBlockLen;
2274 return TRUE;
2276 if (dwBufLen < pCryptKey->dwBlockLen) {
2277 SetLastError(ERROR_MORE_DATA);
2278 return FALSE;
2280 if (!pad_data(pbData, *pdwDataLen, pbData, pCryptKey->dwBlockLen, dwFlags)) return FALSE;
2281 encrypt_block_impl(pCryptKey->aiAlgid, PK_PUBLIC, &pCryptKey->context, pbData, pbData, RSAENH_ENCRYPT);
2282 *pdwDataLen = pCryptKey->dwBlockLen;
2283 Final = TRUE;
2284 } else {
2285 SetLastError(NTE_BAD_TYPE);
2286 return FALSE;
2289 if (Final) setup_key(pCryptKey);
2291 return TRUE;
2294 /******************************************************************************
2295 * CPDecrypt (RSAENH.@)
2297 * Decrypt data.
2299 * PARAMS
2300 * hProv [I] The key container hKey and hHash belong to.
2301 * hKey [I] The key used to decrypt the data.
2302 * hHash [I] An optional hash object for parallel hashing. See notes.
2303 * Final [I] Indicates if this is the last block of data to decrypt.
2304 * dwFlags [I] Currently no flags defined. Must be zero.
2305 * pbData [I/O] Pointer to the data to decrypt. Plaintext will also be stored there.
2306 * pdwDataLen [I/O] I: Length of ciphertext, O: Length of plaintext.
2308 * RETURNS
2309 * Success: TRUE.
2310 * Failure: FALSE.
2312 * NOTES
2313 * If a hash object handle is provided in hHash, it will be updated with the plaintext.
2314 * This is useful for message signatures.
2316 * This function uses the standard WINAPI protocol for querying data of dynamic length.
2318 BOOL WINAPI RSAENH_CPDecrypt(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final,
2319 DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2321 CRYPTKEY *pCryptKey;
2322 BYTE *in, out[RSAENH_MAX_BLOCK_SIZE], o[RSAENH_MAX_BLOCK_SIZE];
2323 DWORD i, j, k;
2324 DWORD dwMax;
2326 TRACE("(hProv=%08lx, hKey=%08lx, hHash=%08lx, Final=%d, dwFlags=%08x, pbData=%p, "
2327 "pdwDataLen=%p)\n", hProv, hKey, hHash, Final, dwFlags, pbData, pdwDataLen);
2329 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2331 SetLastError(NTE_BAD_UID);
2332 return FALSE;
2335 if (dwFlags)
2337 SetLastError(NTE_BAD_FLAGS);
2338 return FALSE;
2341 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2343 SetLastError(NTE_BAD_KEY);
2344 return FALSE;
2347 if (pCryptKey->dwState == RSAENH_KEYSTATE_IDLE)
2348 pCryptKey->dwState = RSAENH_KEYSTATE_ENCRYPTING;
2350 if (pCryptKey->dwState != RSAENH_KEYSTATE_ENCRYPTING)
2352 SetLastError(NTE_BAD_DATA);
2353 return FALSE;
2356 dwMax=*pdwDataLen;
2358 if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_BLOCK) {
2359 for (i=0, in=pbData; i<*pdwDataLen; i+=pCryptKey->dwBlockLen, in+=pCryptKey->dwBlockLen) {
2360 switch (pCryptKey->dwMode) {
2361 case CRYPT_MODE_ECB:
2362 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out,
2363 RSAENH_DECRYPT);
2364 break;
2366 case CRYPT_MODE_CBC:
2367 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out,
2368 RSAENH_DECRYPT);
2369 for (j=0; j<pCryptKey->dwBlockLen; j++) out[j] ^= pCryptKey->abChainVector[j];
2370 memcpy(pCryptKey->abChainVector, in, pCryptKey->dwBlockLen);
2371 break;
2373 case CRYPT_MODE_CFB:
2374 for (j=0; j<pCryptKey->dwBlockLen; j++) {
2375 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context,
2376 pCryptKey->abChainVector, o, RSAENH_ENCRYPT);
2377 out[j] = in[j] ^ o[0];
2378 for (k=0; k<pCryptKey->dwBlockLen-1; k++)
2379 pCryptKey->abChainVector[k] = pCryptKey->abChainVector[k+1];
2380 pCryptKey->abChainVector[k] = in[j];
2382 break;
2384 default:
2385 SetLastError(NTE_BAD_ALGID);
2386 return FALSE;
2388 memcpy(in, out, pCryptKey->dwBlockLen);
2390 if (Final) {
2391 if (pbData[*pdwDataLen-1] &&
2392 pbData[*pdwDataLen-1] <= pCryptKey->dwBlockLen &&
2393 pbData[*pdwDataLen-1] <= *pdwDataLen) {
2394 BOOL padOkay = TRUE;
2396 /* check that every bad byte has the same value */
2397 for (i = 1; padOkay && i < pbData[*pdwDataLen-1]; i++)
2398 if (pbData[*pdwDataLen - i - 1] != pbData[*pdwDataLen - 1])
2399 padOkay = FALSE;
2400 if (padOkay)
2401 *pdwDataLen -= pbData[*pdwDataLen-1];
2402 else {
2403 SetLastError(NTE_BAD_DATA);
2404 setup_key(pCryptKey);
2405 return FALSE;
2408 else {
2409 SetLastError(NTE_BAD_DATA);
2410 setup_key(pCryptKey);
2411 return FALSE;
2415 } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_STREAM) {
2416 encrypt_stream_impl(pCryptKey->aiAlgid, &pCryptKey->context, pbData, *pdwDataLen);
2417 } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_RSA) {
2418 if (pCryptKey->aiAlgid == CALG_RSA_SIGN) {
2419 SetLastError(NTE_BAD_KEY);
2420 return FALSE;
2422 encrypt_block_impl(pCryptKey->aiAlgid, PK_PRIVATE, &pCryptKey->context, pbData, pbData, RSAENH_DECRYPT);
2423 if (!unpad_data(pbData, pCryptKey->dwBlockLen, pbData, pdwDataLen, dwFlags)) return FALSE;
2424 Final = TRUE;
2425 } else {
2426 SetLastError(NTE_BAD_TYPE);
2427 return FALSE;
2430 if (Final) setup_key(pCryptKey);
2432 if (is_valid_handle(&handle_table, hHash, RSAENH_MAGIC_HASH)) {
2433 if (*pdwDataLen>dwMax ||
2434 !RSAENH_CPHashData(hProv, hHash, pbData, *pdwDataLen, 0)) return FALSE;
2437 return TRUE;
2440 static BOOL crypt_export_simple(CRYPTKEY *pCryptKey, CRYPTKEY *pPubKey,
2441 DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2443 BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2444 ALG_ID *pAlgid = (ALG_ID*)(pBlobHeader+1);
2445 DWORD dwDataLen;
2447 if (!(GET_ALG_CLASS(pCryptKey->aiAlgid)&(ALG_CLASS_DATA_ENCRYPT|ALG_CLASS_MSG_ENCRYPT))) {
2448 SetLastError(NTE_BAD_KEY); /* FIXME: error code? */
2449 return FALSE;
2452 dwDataLen = sizeof(BLOBHEADER) + sizeof(ALG_ID) + pPubKey->dwBlockLen;
2453 if (pbData) {
2454 if (*pdwDataLen < dwDataLen) {
2455 SetLastError(ERROR_MORE_DATA);
2456 *pdwDataLen = dwDataLen;
2457 return FALSE;
2460 pBlobHeader->bType = SIMPLEBLOB;
2461 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2462 pBlobHeader->reserved = 0;
2463 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2465 *pAlgid = pPubKey->aiAlgid;
2467 if (!pad_data(pCryptKey->abKeyValue, pCryptKey->dwKeyLen, (BYTE*)(pAlgid+1),
2468 pPubKey->dwBlockLen, dwFlags))
2470 return FALSE;
2473 encrypt_block_impl(pPubKey->aiAlgid, PK_PUBLIC, &pPubKey->context, (BYTE*)(pAlgid+1),
2474 (BYTE*)(pAlgid+1), RSAENH_ENCRYPT);
2476 *pdwDataLen = dwDataLen;
2477 return TRUE;
2480 static BOOL crypt_export_public_key(CRYPTKEY *pCryptKey, BYTE *pbData,
2481 DWORD *pdwDataLen)
2483 BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2484 RSAPUBKEY *pRSAPubKey = (RSAPUBKEY*)(pBlobHeader+1);
2485 DWORD dwDataLen;
2487 if ((pCryptKey->aiAlgid != CALG_RSA_KEYX) && (pCryptKey->aiAlgid != CALG_RSA_SIGN)) {
2488 SetLastError(NTE_BAD_KEY);
2489 return FALSE;
2492 dwDataLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) + pCryptKey->dwKeyLen;
2493 if (pbData) {
2494 if (*pdwDataLen < dwDataLen) {
2495 SetLastError(ERROR_MORE_DATA);
2496 *pdwDataLen = dwDataLen;
2497 return FALSE;
2500 pBlobHeader->bType = PUBLICKEYBLOB;
2501 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2502 pBlobHeader->reserved = 0;
2503 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2505 pRSAPubKey->magic = RSAENH_MAGIC_RSA1;
2506 pRSAPubKey->bitlen = pCryptKey->dwKeyLen << 3;
2508 export_public_key_impl((BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2509 pCryptKey->dwKeyLen, &pRSAPubKey->pubexp);
2511 *pdwDataLen = dwDataLen;
2512 return TRUE;
2515 static BOOL crypt_export_private_key(CRYPTKEY *pCryptKey, BOOL force,
2516 BYTE *pbData, DWORD *pdwDataLen)
2518 BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2519 RSAPUBKEY *pRSAPubKey = (RSAPUBKEY*)(pBlobHeader+1);
2520 DWORD dwDataLen;
2522 if ((pCryptKey->aiAlgid != CALG_RSA_KEYX) && (pCryptKey->aiAlgid != CALG_RSA_SIGN)) {
2523 SetLastError(NTE_BAD_KEY);
2524 return FALSE;
2526 if (!force && !(pCryptKey->dwPermissions & CRYPT_EXPORT))
2528 SetLastError(NTE_BAD_KEY_STATE);
2529 return FALSE;
2532 dwDataLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) +
2533 2 * pCryptKey->dwKeyLen + 5 * ((pCryptKey->dwKeyLen + 1) >> 1);
2534 if (pbData) {
2535 if (*pdwDataLen < dwDataLen) {
2536 SetLastError(ERROR_MORE_DATA);
2537 *pdwDataLen = dwDataLen;
2538 return FALSE;
2541 pBlobHeader->bType = PRIVATEKEYBLOB;
2542 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2543 pBlobHeader->reserved = 0;
2544 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2546 pRSAPubKey->magic = RSAENH_MAGIC_RSA2;
2547 pRSAPubKey->bitlen = pCryptKey->dwKeyLen << 3;
2549 export_private_key_impl((BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2550 pCryptKey->dwKeyLen, &pRSAPubKey->pubexp);
2552 *pdwDataLen = dwDataLen;
2553 return TRUE;
2556 static BOOL crypt_export_plaintext_key(CRYPTKEY *pCryptKey, BYTE *pbData,
2557 DWORD *pdwDataLen)
2559 BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2560 DWORD *pKeyLen = (DWORD*)(pBlobHeader+1);
2561 BYTE *pbKey = (BYTE*)(pKeyLen+1);
2562 DWORD dwDataLen;
2564 dwDataLen = sizeof(BLOBHEADER) + sizeof(DWORD) + pCryptKey->dwKeyLen;
2565 if (pbData) {
2566 if (*pdwDataLen < dwDataLen) {
2567 SetLastError(ERROR_MORE_DATA);
2568 *pdwDataLen = dwDataLen;
2569 return FALSE;
2572 pBlobHeader->bType = PLAINTEXTKEYBLOB;
2573 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2574 pBlobHeader->reserved = 0;
2575 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2577 *pKeyLen = pCryptKey->dwKeyLen;
2578 memcpy(pbKey, pCryptKey->abKeyValue, pCryptKey->dwKeyLen);
2580 *pdwDataLen = dwDataLen;
2581 return TRUE;
2583 /******************************************************************************
2584 * crypt_export_key [Internal]
2586 * Export a key into a binary large object (BLOB). Called by CPExportKey and
2587 * by store_key_pair.
2589 * PARAMS
2590 * pCryptKey [I] Key to be exported.
2591 * hPubKey [I] Key used to encrypt sensitive BLOB data.
2592 * dwBlobType [I] SIMPLEBLOB, PUBLICKEYBLOB or PRIVATEKEYBLOB.
2593 * dwFlags [I] Currently none defined.
2594 * force [I] If TRUE, the key is written no matter what the key's
2595 * permissions are. Otherwise the key's permissions are
2596 * checked before exporting.
2597 * pbData [O] Pointer to a buffer where the BLOB will be written to.
2598 * pdwDataLen [I/O] I: Size of buffer at pbData, O: Size of BLOB
2600 * RETURNS
2601 * Success: TRUE.
2602 * Failure: FALSE.
2604 static BOOL crypt_export_key(CRYPTKEY *pCryptKey, HCRYPTKEY hPubKey,
2605 DWORD dwBlobType, DWORD dwFlags, BOOL force,
2606 BYTE *pbData, DWORD *pdwDataLen)
2608 CRYPTKEY *pPubKey;
2610 if (dwFlags & CRYPT_SSL2_FALLBACK) {
2611 if (pCryptKey->aiAlgid != CALG_SSL2_MASTER) {
2612 SetLastError(NTE_BAD_KEY);
2613 return FALSE;
2617 switch ((BYTE)dwBlobType)
2619 case SIMPLEBLOB:
2620 if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pPubKey)){
2621 SetLastError(NTE_BAD_PUBLIC_KEY); /* FIXME: error_code? */
2622 return FALSE;
2624 return crypt_export_simple(pCryptKey, pPubKey, dwFlags, pbData,
2625 pdwDataLen);
2627 case PUBLICKEYBLOB:
2628 if (is_valid_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY)) {
2629 SetLastError(NTE_BAD_KEY); /* FIXME: error code? */
2630 return FALSE;
2633 return crypt_export_public_key(pCryptKey, pbData, pdwDataLen);
2635 case PRIVATEKEYBLOB:
2636 return crypt_export_private_key(pCryptKey, force, pbData, pdwDataLen);
2638 case PLAINTEXTKEYBLOB:
2639 return crypt_export_plaintext_key(pCryptKey, pbData, pdwDataLen);
2641 default:
2642 SetLastError(NTE_BAD_TYPE); /* FIXME: error code? */
2643 return FALSE;
2647 /******************************************************************************
2648 * CPExportKey (RSAENH.@)
2650 * Export a key into a binary large object (BLOB).
2652 * PARAMS
2653 * hProv [I] Key container from which a key is to be exported.
2654 * hKey [I] Key to be exported.
2655 * hPubKey [I] Key used to encrypt sensitive BLOB data.
2656 * dwBlobType [I] SIMPLEBLOB, PUBLICKEYBLOB or PRIVATEKEYBLOB.
2657 * dwFlags [I] Currently none defined.
2658 * pbData [O] Pointer to a buffer where the BLOB will be written to.
2659 * pdwDataLen [I/O] I: Size of buffer at pbData, O: Size of BLOB
2661 * RETURNS
2662 * Success: TRUE.
2663 * Failure: FALSE.
2665 BOOL WINAPI RSAENH_CPExportKey(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTKEY hPubKey,
2666 DWORD dwBlobType, DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2668 CRYPTKEY *pCryptKey;
2670 TRACE("(hProv=%08lx, hKey=%08lx, hPubKey=%08lx, dwBlobType=%08x, dwFlags=%08x, pbData=%p,"
2671 "pdwDataLen=%p)\n", hProv, hKey, hPubKey, dwBlobType, dwFlags, pbData, pdwDataLen);
2673 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2675 SetLastError(NTE_BAD_UID);
2676 return FALSE;
2679 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2681 SetLastError(NTE_BAD_KEY);
2682 return FALSE;
2685 return crypt_export_key(pCryptKey, hPubKey, dwBlobType, dwFlags, FALSE,
2686 pbData, pdwDataLen);
2689 /******************************************************************************
2690 * release_and_install_key [Internal]
2692 * Release an existing key, if present, and replaces it with a new one.
2694 * PARAMS
2695 * hProv [I] Key container into which the key is to be imported.
2696 * src [I] Key which will replace *dest
2697 * dest [I] Points to key to be released and replaced with src
2698 * fStoreKey [I] If TRUE, the newly installed key is stored to the registry.
2700 static void release_and_install_key(HCRYPTPROV hProv, HCRYPTKEY src,
2701 HCRYPTKEY *dest, DWORD fStoreKey)
2703 RSAENH_CPDestroyKey(hProv, *dest);
2704 copy_handle(&handle_table, src, RSAENH_MAGIC_KEY, dest);
2705 if (fStoreKey)
2707 KEYCONTAINER *pKeyContainer;
2709 if ((pKeyContainer = get_key_container(hProv)))
2711 store_key_container_keys(pKeyContainer);
2712 store_key_container_permissions(pKeyContainer);
2717 /******************************************************************************
2718 * import_private_key [Internal]
2720 * Import a BLOB'ed private key into a key container.
2722 * PARAMS
2723 * hProv [I] Key container into which the private key is to be imported.
2724 * pbData [I] Pointer to a buffer which holds the private key BLOB.
2725 * dwDataLen [I] Length of data in buffer at pbData.
2726 * dwFlags [I] One of:
2727 * CRYPT_EXPORTABLE: the imported key is marked exportable
2728 * fStoreKey [I] If TRUE, the imported key is stored to the registry.
2729 * phKey [O] Handle to the imported key.
2732 * NOTES
2733 * Assumes the caller has already checked the BLOBHEADER at pbData to ensure
2734 * it's a PRIVATEKEYBLOB.
2736 * RETURNS
2737 * Success: TRUE.
2738 * Failure: FALSE.
2740 static BOOL import_private_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
2741 DWORD dwFlags, BOOL fStoreKey, HCRYPTKEY *phKey)
2743 KEYCONTAINER *pKeyContainer;
2744 CRYPTKEY *pCryptKey;
2745 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
2746 const RSAPUBKEY *pRSAPubKey = (const RSAPUBKEY*)(pBlobHeader+1);
2747 BOOL ret;
2749 if (dwFlags & CRYPT_IPSEC_HMAC_KEY)
2751 FIXME("unimplemented for CRYPT_IPSEC_HMAC_KEY\n");
2752 SetLastError(NTE_BAD_FLAGS);
2753 return FALSE;
2755 if (!(pKeyContainer = get_key_container(hProv)))
2756 return FALSE;
2758 if ((dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY)))
2760 ERR("datalen %d not long enough for a BLOBHEADER + RSAPUBKEY\n",
2761 dwDataLen);
2762 SetLastError(NTE_BAD_DATA);
2763 return FALSE;
2765 if (pRSAPubKey->magic != RSAENH_MAGIC_RSA2)
2767 ERR("unexpected magic %08x\n", pRSAPubKey->magic);
2768 SetLastError(NTE_BAD_DATA);
2769 return FALSE;
2771 if ((dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) +
2772 (pRSAPubKey->bitlen >> 3) + (5 * ((pRSAPubKey->bitlen+8)>>4))))
2774 DWORD expectedLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) +
2775 (pRSAPubKey->bitlen >> 3) + (5 * ((pRSAPubKey->bitlen+8)>>4));
2777 ERR("blob too short for pub key: expect %d, got %d\n",
2778 expectedLen, dwDataLen);
2779 SetLastError(NTE_BAD_DATA);
2780 return FALSE;
2783 *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, MAKELONG(0,pRSAPubKey->bitlen), &pCryptKey);
2784 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
2785 setup_key(pCryptKey);
2786 ret = import_private_key_impl((const BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2787 pRSAPubKey->bitlen/8, dwDataLen, pRSAPubKey->pubexp);
2788 if (ret) {
2789 if (dwFlags & CRYPT_EXPORTABLE)
2790 pCryptKey->dwPermissions |= CRYPT_EXPORT;
2791 switch (pBlobHeader->aiKeyAlg)
2793 case AT_SIGNATURE:
2794 case CALG_RSA_SIGN:
2795 TRACE("installing signing key\n");
2796 release_and_install_key(hProv, *phKey, &pKeyContainer->hSignatureKeyPair,
2797 fStoreKey);
2798 break;
2799 case AT_KEYEXCHANGE:
2800 case CALG_RSA_KEYX:
2801 TRACE("installing key exchange key\n");
2802 release_and_install_key(hProv, *phKey, &pKeyContainer->hKeyExchangeKeyPair,
2803 fStoreKey);
2804 break;
2807 return ret;
2810 /******************************************************************************
2811 * import_public_key [Internal]
2813 * Import a BLOB'ed public key.
2815 * PARAMS
2816 * hProv [I] A CSP.
2817 * pbData [I] Pointer to a buffer which holds the public key BLOB.
2818 * dwDataLen [I] Length of data in buffer at pbData.
2819 * dwFlags [I] One of:
2820 * CRYPT_EXPORTABLE: the imported key is marked exportable
2821 * phKey [O] Handle to the imported key.
2824 * NOTES
2825 * Assumes the caller has already checked the BLOBHEADER at pbData to ensure
2826 * it's a PUBLICKEYBLOB.
2828 * RETURNS
2829 * Success: TRUE.
2830 * Failure: FALSE.
2832 static BOOL import_public_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
2833 DWORD dwFlags, HCRYPTKEY *phKey)
2835 CRYPTKEY *pCryptKey;
2836 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
2837 const RSAPUBKEY *pRSAPubKey = (const RSAPUBKEY*)(pBlobHeader+1);
2838 ALG_ID algID;
2839 BOOL ret;
2841 if (dwFlags & CRYPT_IPSEC_HMAC_KEY)
2843 FIXME("unimplemented for CRYPT_IPSEC_HMAC_KEY\n");
2844 SetLastError(NTE_BAD_FLAGS);
2845 return FALSE;
2848 if ((dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY)) ||
2849 (pRSAPubKey->magic != RSAENH_MAGIC_RSA1) ||
2850 (dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) + (pRSAPubKey->bitlen >> 3)))
2852 SetLastError(NTE_BAD_DATA);
2853 return FALSE;
2856 /* Since this is a public key blob, only the public key is
2857 * available, so only signature verification is possible.
2859 algID = pBlobHeader->aiKeyAlg;
2860 *phKey = new_key(hProv, algID, MAKELONG(0,pRSAPubKey->bitlen), &pCryptKey);
2861 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
2862 setup_key(pCryptKey);
2863 ret = import_public_key_impl((const BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2864 pRSAPubKey->bitlen >> 3, pRSAPubKey->pubexp);
2865 if (ret) {
2866 if (dwFlags & CRYPT_EXPORTABLE)
2867 pCryptKey->dwPermissions |= CRYPT_EXPORT;
2869 return ret;
2872 /******************************************************************************
2873 * import_symmetric_key [Internal]
2875 * Import a BLOB'ed symmetric key into a key container.
2877 * PARAMS
2878 * hProv [I] Key container into which the symmetric key is to be imported.
2879 * pbData [I] Pointer to a buffer which holds the symmetric key BLOB.
2880 * dwDataLen [I] Length of data in buffer at pbData.
2881 * hPubKey [I] Key used to decrypt sensitive BLOB data.
2882 * dwFlags [I] One of:
2883 * CRYPT_EXPORTABLE: the imported key is marked exportable
2884 * phKey [O] Handle to the imported key.
2887 * NOTES
2888 * Assumes the caller has already checked the BLOBHEADER at pbData to ensure
2889 * it's a SIMPLEBLOB.
2891 * RETURNS
2892 * Success: TRUE.
2893 * Failure: FALSE.
2895 static BOOL import_symmetric_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
2896 HCRYPTKEY hPubKey, DWORD dwFlags, HCRYPTKEY *phKey)
2898 CRYPTKEY *pCryptKey, *pPubKey;
2899 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
2900 const ALG_ID *pAlgid = (const ALG_ID*)(pBlobHeader+1);
2901 const BYTE *pbKeyStream = (const BYTE*)(pAlgid + 1);
2902 BYTE *pbDecrypted;
2903 DWORD dwKeyLen;
2905 if (dwFlags & CRYPT_IPSEC_HMAC_KEY)
2907 FIXME("unimplemented for CRYPT_IPSEC_HMAC_KEY\n");
2908 SetLastError(NTE_BAD_FLAGS);
2909 return FALSE;
2911 if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pPubKey) ||
2912 pPubKey->aiAlgid != CALG_RSA_KEYX)
2914 SetLastError(NTE_BAD_PUBLIC_KEY); /* FIXME: error code? */
2915 return FALSE;
2918 if (dwDataLen < sizeof(BLOBHEADER)+sizeof(ALG_ID)+pPubKey->dwBlockLen)
2920 SetLastError(NTE_BAD_DATA); /* FIXME: error code */
2921 return FALSE;
2924 pbDecrypted = HeapAlloc(GetProcessHeap(), 0, pPubKey->dwBlockLen);
2925 if (!pbDecrypted) return FALSE;
2926 encrypt_block_impl(pPubKey->aiAlgid, PK_PRIVATE, &pPubKey->context, pbKeyStream, pbDecrypted,
2927 RSAENH_DECRYPT);
2929 dwKeyLen = RSAENH_MAX_KEY_SIZE;
2930 if (!unpad_data(pbDecrypted, pPubKey->dwBlockLen, pbDecrypted, &dwKeyLen, dwFlags)) {
2931 HeapFree(GetProcessHeap(), 0, pbDecrypted);
2932 return FALSE;
2935 *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, dwKeyLen<<19, &pCryptKey);
2936 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
2938 HeapFree(GetProcessHeap(), 0, pbDecrypted);
2939 return FALSE;
2941 memcpy(pCryptKey->abKeyValue, pbDecrypted, dwKeyLen);
2942 HeapFree(GetProcessHeap(), 0, pbDecrypted);
2943 setup_key(pCryptKey);
2944 if (dwFlags & CRYPT_EXPORTABLE)
2945 pCryptKey->dwPermissions |= CRYPT_EXPORT;
2946 return TRUE;
2949 /******************************************************************************
2950 * import_plaintext_key [Internal]
2952 * Import a plaintext key into a key container.
2954 * PARAMS
2955 * hProv [I] Key container into which the symmetric key is to be imported.
2956 * pbData [I] Pointer to a buffer which holds the plaintext key BLOB.
2957 * dwDataLen [I] Length of data in buffer at pbData.
2958 * dwFlags [I] One of:
2959 * CRYPT_EXPORTABLE: the imported key is marked exportable
2960 * phKey [O] Handle to the imported key.
2963 * NOTES
2964 * Assumes the caller has already checked the BLOBHEADER at pbData to ensure
2965 * it's a PLAINTEXTKEYBLOB.
2967 * RETURNS
2968 * Success: TRUE.
2969 * Failure: FALSE.
2971 static BOOL import_plaintext_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
2972 DWORD dwFlags, HCRYPTKEY *phKey)
2974 CRYPTKEY *pCryptKey;
2975 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
2976 const DWORD *pKeyLen = (const DWORD *)(pBlobHeader + 1);
2977 const BYTE *pbKeyStream = (const BYTE*)(pKeyLen + 1);
2979 if (dwDataLen < sizeof(BLOBHEADER)+sizeof(DWORD)+*pKeyLen)
2981 SetLastError(NTE_BAD_DATA); /* FIXME: error code */
2982 return FALSE;
2985 if (dwFlags & CRYPT_IPSEC_HMAC_KEY)
2987 *phKey = new_key(hProv, CALG_HMAC, 0, &pCryptKey);
2988 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
2989 return FALSE;
2990 if (*pKeyLen <= RSAENH_MIN(sizeof(pCryptKey->abKeyValue), RSAENH_HMAC_BLOCK_LEN))
2992 memcpy(pCryptKey->abKeyValue, pbKeyStream, *pKeyLen);
2993 pCryptKey->dwKeyLen = *pKeyLen;
2995 else
2997 CRYPT_DATA_BLOB blobHmacKey = { *pKeyLen, (BYTE *)pbKeyStream };
2999 /* In order to initialize an HMAC key, the key material is hashed,
3000 * and the output of the hash function is used as the key material.
3001 * Unfortunately, the way the Crypto API is designed, we don't know
3002 * the hash algorithm yet, so we have to copy the entire key
3003 * material.
3005 if (!copy_data_blob(&pCryptKey->blobHmacKey, &blobHmacKey))
3007 release_handle(&handle_table, *phKey, RSAENH_MAGIC_KEY);
3008 *phKey = (HCRYPTKEY)INVALID_HANDLE_VALUE;
3009 return FALSE;
3012 setup_key(pCryptKey);
3013 if (dwFlags & CRYPT_EXPORTABLE)
3014 pCryptKey->dwPermissions |= CRYPT_EXPORT;
3016 else
3018 *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, *pKeyLen<<19, &pCryptKey);
3019 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
3020 return FALSE;
3021 memcpy(pCryptKey->abKeyValue, pbKeyStream, *pKeyLen);
3022 setup_key(pCryptKey);
3023 if (dwFlags & CRYPT_EXPORTABLE)
3024 pCryptKey->dwPermissions |= CRYPT_EXPORT;
3026 return TRUE;
3029 /******************************************************************************
3030 * import_key [Internal]
3032 * Import a BLOB'ed key into a key container, optionally storing the key's
3033 * value to the registry.
3035 * PARAMS
3036 * hProv [I] Key container into which the key is to be imported.
3037 * pbData [I] Pointer to a buffer which holds the BLOB.
3038 * dwDataLen [I] Length of data in buffer at pbData.
3039 * hPubKey [I] Key used to decrypt sensitive BLOB data.
3040 * dwFlags [I] One of:
3041 * CRYPT_EXPORTABLE: the imported key is marked exportable
3042 * fStoreKey [I] If TRUE, the imported key is stored to the registry.
3043 * phKey [O] Handle to the imported key.
3045 * RETURNS
3046 * Success: TRUE.
3047 * Failure: FALSE.
3049 static BOOL import_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen, HCRYPTKEY hPubKey,
3050 DWORD dwFlags, BOOL fStoreKey, HCRYPTKEY *phKey)
3052 KEYCONTAINER *pKeyContainer;
3053 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
3055 if (!(pKeyContainer = get_key_container(hProv)))
3056 return FALSE;
3058 if (dwDataLen < sizeof(BLOBHEADER) ||
3059 pBlobHeader->bVersion != CUR_BLOB_VERSION ||
3060 pBlobHeader->reserved != 0)
3062 TRACE("bVersion = %d, reserved = %d\n", pBlobHeader->bVersion,
3063 pBlobHeader->reserved);
3064 SetLastError(NTE_BAD_DATA);
3065 return FALSE;
3068 /* If this is a verify-only context, the key is not persisted regardless of
3069 * fStoreKey's original value.
3071 fStoreKey = fStoreKey && !(dwFlags & CRYPT_VERIFYCONTEXT);
3072 TRACE("blob type: %x\n", pBlobHeader->bType);
3073 switch (pBlobHeader->bType)
3075 case PRIVATEKEYBLOB:
3076 return import_private_key(hProv, pbData, dwDataLen, dwFlags,
3077 fStoreKey, phKey);
3079 case PUBLICKEYBLOB:
3080 return import_public_key(hProv, pbData, dwDataLen, dwFlags,
3081 phKey);
3083 case SIMPLEBLOB:
3084 return import_symmetric_key(hProv, pbData, dwDataLen, hPubKey,
3085 dwFlags, phKey);
3087 case PLAINTEXTKEYBLOB:
3088 return import_plaintext_key(hProv, pbData, dwDataLen, dwFlags,
3089 phKey);
3091 default:
3092 SetLastError(NTE_BAD_TYPE); /* FIXME: error code? */
3093 return FALSE;
3097 /******************************************************************************
3098 * CPImportKey (RSAENH.@)
3100 * Import a BLOB'ed key into a key container.
3102 * PARAMS
3103 * hProv [I] Key container into which the key is to be imported.
3104 * pbData [I] Pointer to a buffer which holds the BLOB.
3105 * dwDataLen [I] Length of data in buffer at pbData.
3106 * hPubKey [I] Key used to decrypt sensitive BLOB data.
3107 * dwFlags [I] One of:
3108 * CRYPT_EXPORTABLE: the imported key is marked exportable
3109 * phKey [O] Handle to the imported key.
3111 * RETURNS
3112 * Success: TRUE.
3113 * Failure: FALSE.
3115 BOOL WINAPI RSAENH_CPImportKey(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
3116 HCRYPTKEY hPubKey, DWORD dwFlags, HCRYPTKEY *phKey)
3118 TRACE("(hProv=%08lx, pbData=%p, dwDataLen=%d, hPubKey=%08lx, dwFlags=%08x, phKey=%p)\n",
3119 hProv, pbData, dwDataLen, hPubKey, dwFlags, phKey);
3121 return import_key(hProv, pbData, dwDataLen, hPubKey, dwFlags, TRUE, phKey);
3124 /******************************************************************************
3125 * CPGenKey (RSAENH.@)
3127 * Generate a key in the key container
3129 * PARAMS
3130 * hProv [I] Key container for which a key is to be generated.
3131 * Algid [I] Crypto algorithm identifier for the key to be generated.
3132 * dwFlags [I] Upper 16 bits: Binary length of key. Lower 16 bits: Flags. See Notes
3133 * phKey [O] Handle to the generated key.
3135 * RETURNS
3136 * Success: TRUE.
3137 * Failure: FALSE.
3139 * FIXME
3140 * Flags currently not considered.
3142 * NOTES
3143 * Private key-exchange- and signature-keys can be generated with Algid AT_KEYEXCHANGE
3144 * and AT_SIGNATURE values.
3146 BOOL WINAPI RSAENH_CPGenKey(HCRYPTPROV hProv, ALG_ID Algid, DWORD dwFlags, HCRYPTKEY *phKey)
3148 KEYCONTAINER *pKeyContainer;
3149 CRYPTKEY *pCryptKey;
3151 TRACE("(hProv=%08lx, aiAlgid=%d, dwFlags=%08x, phKey=%p)\n", hProv, Algid, dwFlags, phKey);
3153 if (!(pKeyContainer = get_key_container(hProv)))
3155 /* MSDN: hProv not containing valid context handle */
3156 return FALSE;
3159 switch (Algid)
3161 case AT_SIGNATURE:
3162 case CALG_RSA_SIGN:
3163 *phKey = new_key(hProv, CALG_RSA_SIGN, dwFlags, &pCryptKey);
3164 if (pCryptKey) {
3165 new_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen);
3166 setup_key(pCryptKey);
3167 release_and_install_key(hProv, *phKey,
3168 &pKeyContainer->hSignatureKeyPair,
3169 FALSE);
3171 break;
3173 case AT_KEYEXCHANGE:
3174 case CALG_RSA_KEYX:
3175 *phKey = new_key(hProv, CALG_RSA_KEYX, dwFlags, &pCryptKey);
3176 if (pCryptKey) {
3177 new_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen);
3178 setup_key(pCryptKey);
3179 release_and_install_key(hProv, *phKey,
3180 &pKeyContainer->hKeyExchangeKeyPair,
3181 FALSE);
3183 break;
3185 case CALG_RC2:
3186 case CALG_RC4:
3187 case CALG_DES:
3188 case CALG_3DES_112:
3189 case CALG_3DES:
3190 case CALG_AES_128:
3191 case CALG_AES_192:
3192 case CALG_AES_256:
3193 case CALG_PCT1_MASTER:
3194 case CALG_SSL2_MASTER:
3195 case CALG_SSL3_MASTER:
3196 case CALG_TLS1_MASTER:
3197 *phKey = new_key(hProv, Algid, dwFlags, &pCryptKey);
3198 if (pCryptKey) {
3199 gen_rand_impl(pCryptKey->abKeyValue, RSAENH_MAX_KEY_SIZE);
3200 switch (Algid) {
3201 case CALG_SSL3_MASTER:
3202 pCryptKey->abKeyValue[0] = RSAENH_SSL3_VERSION_MAJOR;
3203 pCryptKey->abKeyValue[1] = RSAENH_SSL3_VERSION_MINOR;
3204 break;
3206 case CALG_TLS1_MASTER:
3207 pCryptKey->abKeyValue[0] = RSAENH_TLS1_VERSION_MAJOR;
3208 pCryptKey->abKeyValue[1] = RSAENH_TLS1_VERSION_MINOR;
3209 break;
3211 setup_key(pCryptKey);
3213 break;
3215 default:
3216 /* MSDN: Algorithm not supported specified by Algid */
3217 SetLastError(NTE_BAD_ALGID);
3218 return FALSE;
3221 return *phKey != (HCRYPTKEY)INVALID_HANDLE_VALUE;
3224 /******************************************************************************
3225 * CPGenRandom (RSAENH.@)
3227 * Generate a random byte stream.
3229 * PARAMS
3230 * hProv [I] Key container that is used to generate random bytes.
3231 * dwLen [I] Specifies the number of requested random data bytes.
3232 * pbBuffer [O] Random bytes will be stored here.
3234 * RETURNS
3235 * Success: TRUE
3236 * Failure: FALSE
3238 BOOL WINAPI RSAENH_CPGenRandom(HCRYPTPROV hProv, DWORD dwLen, BYTE *pbBuffer)
3240 TRACE("(hProv=%08lx, dwLen=%d, pbBuffer=%p)\n", hProv, dwLen, pbBuffer);
3242 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3244 /* MSDN: hProv not containing valid context handle */
3245 SetLastError(NTE_BAD_UID);
3246 return FALSE;
3249 return gen_rand_impl(pbBuffer, dwLen);
3252 /******************************************************************************
3253 * CPGetHashParam (RSAENH.@)
3255 * Query parameters of an hash object.
3257 * PARAMS
3258 * hProv [I] The kea container, which the hash belongs to.
3259 * hHash [I] The hash object that is to be queried.
3260 * dwParam [I] Specifies the parameter that is to be queried.
3261 * pbData [I] Pointer to the buffer where the parameter value will be stored.
3262 * pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
3263 * dwFlags [I] None currently defined.
3265 * RETURNS
3266 * Success: TRUE
3267 * Failure: FALSE
3269 * NOTES
3270 * Valid dwParams are: HP_ALGID, HP_HASHSIZE, HP_HASHVALUE. The hash will be
3271 * finalized if HP_HASHVALUE is queried.
3273 BOOL WINAPI RSAENH_CPGetHashParam(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwParam, BYTE *pbData,
3274 DWORD *pdwDataLen, DWORD dwFlags)
3276 CRYPTHASH *pCryptHash;
3278 TRACE("(hProv=%08lx, hHash=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p, dwFlags=%08x)\n",
3279 hProv, hHash, dwParam, pbData, pdwDataLen, dwFlags);
3281 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3283 SetLastError(NTE_BAD_UID);
3284 return FALSE;
3287 if (dwFlags)
3289 SetLastError(NTE_BAD_FLAGS);
3290 return FALSE;
3293 if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH,
3294 (OBJECTHDR**)&pCryptHash))
3296 SetLastError(NTE_BAD_HASH);
3297 return FALSE;
3300 if (!pdwDataLen)
3302 SetLastError(ERROR_INVALID_PARAMETER);
3303 return FALSE;
3306 switch (dwParam)
3308 case HP_ALGID:
3309 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptHash->aiAlgid,
3310 sizeof(ALG_ID));
3312 case HP_HASHSIZE:
3313 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptHash->dwHashSize,
3314 sizeof(DWORD));
3316 case HP_HASHVAL:
3317 if (pCryptHash->aiAlgid == CALG_TLS1PRF) {
3318 return tls1_prf(hProv, pCryptHash->hKey, &pCryptHash->tpPRFParams.blobLabel,
3319 &pCryptHash->tpPRFParams.blobSeed, pbData, *pdwDataLen);
3322 if ( pbData == NULL ) {
3323 *pdwDataLen = pCryptHash->dwHashSize;
3324 return TRUE;
3327 if (pbData && (pCryptHash->dwState != RSAENH_HASHSTATE_FINISHED))
3329 finalize_hash(pCryptHash);
3330 pCryptHash->dwState = RSAENH_HASHSTATE_FINISHED;
3333 return copy_param(pbData, pdwDataLen, pCryptHash->abHashValue,
3334 pCryptHash->dwHashSize);
3336 default:
3337 SetLastError(NTE_BAD_TYPE);
3338 return FALSE;
3342 /******************************************************************************
3343 * CPSetKeyParam (RSAENH.@)
3345 * Set a parameter of a key object
3347 * PARAMS
3348 * hProv [I] The key container to which the key belongs.
3349 * hKey [I] The key for which a parameter is to be set.
3350 * dwParam [I] Parameter type. See Notes.
3351 * pbData [I] Pointer to the parameter value.
3352 * dwFlags [I] Currently none defined.
3354 * RETURNS
3355 * Success: TRUE.
3356 * Failure: FALSE.
3358 * NOTES:
3359 * Defined dwParam types are:
3360 * - KP_MODE: Values MODE_CBC, MODE_ECB, MODE_CFB.
3361 * - KP_MODE_BITS: Shift width for cipher feedback mode. (Currently ignored by MS CSP's)
3362 * - KP_PERMISSIONS: Or'ed combination of CRYPT_ENCRYPT, CRYPT_DECRYPT,
3363 * CRYPT_EXPORT, CRYPT_READ, CRYPT_WRITE, CRYPT_MAC
3364 * - KP_IV: Initialization vector
3366 BOOL WINAPI RSAENH_CPSetKeyParam(HCRYPTPROV hProv, HCRYPTKEY hKey, DWORD dwParam, BYTE *pbData,
3367 DWORD dwFlags)
3369 CRYPTKEY *pCryptKey;
3371 TRACE("(hProv=%08lx, hKey=%08lx, dwParam=%08x, pbData=%p, dwFlags=%08x)\n", hProv, hKey,
3372 dwParam, pbData, dwFlags);
3374 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3376 SetLastError(NTE_BAD_UID);
3377 return FALSE;
3380 if (dwFlags) {
3381 SetLastError(NTE_BAD_FLAGS);
3382 return FALSE;
3385 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
3387 SetLastError(NTE_BAD_KEY);
3388 return FALSE;
3391 switch (dwParam) {
3392 case KP_PADDING:
3393 /* The MS providers only support PKCS5_PADDING */
3394 if (*(DWORD *)pbData != PKCS5_PADDING) {
3395 SetLastError(NTE_BAD_DATA);
3396 return FALSE;
3398 return TRUE;
3400 case KP_MODE:
3401 pCryptKey->dwMode = *(DWORD*)pbData;
3402 return TRUE;
3404 case KP_MODE_BITS:
3405 pCryptKey->dwModeBits = *(DWORD*)pbData;
3406 return TRUE;
3408 case KP_PERMISSIONS:
3410 DWORD perms = *(DWORD *)pbData;
3412 if ((perms & CRYPT_EXPORT) &&
3413 !(pCryptKey->dwPermissions & CRYPT_EXPORT))
3415 SetLastError(NTE_BAD_DATA);
3416 return FALSE;
3418 else if (!(perms & CRYPT_EXPORT) &&
3419 (pCryptKey->dwPermissions & CRYPT_EXPORT))
3421 /* Clearing the export permission appears to be ignored,
3422 * see tests.
3424 perms |= CRYPT_EXPORT;
3426 pCryptKey->dwPermissions = perms;
3427 return TRUE;
3430 case KP_IV:
3431 memcpy(pCryptKey->abInitVector, pbData, pCryptKey->dwBlockLen);
3432 setup_key(pCryptKey);
3433 return TRUE;
3435 case KP_SALT:
3436 switch (pCryptKey->aiAlgid) {
3437 case CALG_RC2:
3438 case CALG_RC4:
3440 KEYCONTAINER *pKeyContainer = get_key_container(pCryptKey->hProv);
3441 if (!pbData)
3443 SetLastError(ERROR_INVALID_PARAMETER);
3444 return FALSE;
3446 /* MSDN: the base provider always sets eleven bytes of
3447 * salt value.
3449 memcpy(pCryptKey->abKeyValue + pCryptKey->dwKeyLen,
3450 pbData, 11);
3451 pCryptKey->dwSaltLen = 11;
3452 setup_key(pCryptKey);
3453 /* After setting the salt value if the provider is not base or
3454 * strong the salt length will be reset. */
3455 if (pKeyContainer->dwPersonality != RSAENH_PERSONALITY_BASE &&
3456 pKeyContainer->dwPersonality != RSAENH_PERSONALITY_STRONG)
3457 pCryptKey->dwSaltLen = 0;
3458 break;
3460 default:
3461 SetLastError(NTE_BAD_KEY);
3462 return FALSE;
3464 return TRUE;
3466 case KP_SALT_EX:
3468 CRYPT_INTEGER_BLOB *blob = (CRYPT_INTEGER_BLOB *)pbData;
3470 /* salt length can't be greater than 184 bits = 24 bytes */
3471 if (blob->cbData > 24)
3473 SetLastError(NTE_BAD_DATA);
3474 return FALSE;
3476 memcpy(pCryptKey->abKeyValue + pCryptKey->dwKeyLen, blob->pbData,
3477 blob->cbData);
3478 pCryptKey->dwSaltLen = blob->cbData;
3479 setup_key(pCryptKey);
3480 return TRUE;
3483 case KP_EFFECTIVE_KEYLEN:
3484 switch (pCryptKey->aiAlgid) {
3485 case CALG_RC2:
3487 DWORD keylen, deflen;
3488 BOOL ret = TRUE;
3489 KEYCONTAINER *pKeyContainer = get_key_container(pCryptKey->hProv);
3491 if (!pbData)
3493 SetLastError(ERROR_INVALID_PARAMETER);
3494 return FALSE;
3496 keylen = *(DWORD *)pbData;
3497 if (!keylen || keylen > 1024)
3499 SetLastError(NTE_BAD_DATA);
3500 return FALSE;
3504 * The Base provider will force the key length to default
3505 * and set an error state if a key length different from
3506 * the default is tried.
3508 deflen = aProvEnumAlgsEx[pKeyContainer->dwPersonality]->dwDefaultLen;
3509 if (pKeyContainer->dwPersonality == RSAENH_PERSONALITY_BASE
3510 && keylen != deflen)
3512 keylen = deflen;
3513 SetLastError(NTE_BAD_DATA);
3514 ret = FALSE;
3516 pCryptKey->dwEffectiveKeyLen = keylen;
3517 setup_key(pCryptKey);
3518 return ret;
3520 default:
3521 SetLastError(NTE_BAD_TYPE);
3522 return FALSE;
3524 return TRUE;
3526 case KP_SCHANNEL_ALG:
3527 switch (((PSCHANNEL_ALG)pbData)->dwUse) {
3528 case SCHANNEL_ENC_KEY:
3529 memcpy(&pCryptKey->siSChannelInfo.saEncAlg, pbData, sizeof(SCHANNEL_ALG));
3530 break;
3532 case SCHANNEL_MAC_KEY:
3533 memcpy(&pCryptKey->siSChannelInfo.saMACAlg, pbData, sizeof(SCHANNEL_ALG));
3534 break;
3536 default:
3537 SetLastError(NTE_FAIL); /* FIXME: error code */
3538 return FALSE;
3540 return TRUE;
3542 case KP_CLIENT_RANDOM:
3543 return copy_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom, (PCRYPT_DATA_BLOB)pbData);
3545 case KP_SERVER_RANDOM:
3546 return copy_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom, (PCRYPT_DATA_BLOB)pbData);
3548 default:
3549 SetLastError(NTE_BAD_TYPE);
3550 return FALSE;
3554 /******************************************************************************
3555 * CPGetKeyParam (RSAENH.@)
3557 * Query a key parameter.
3559 * PARAMS
3560 * hProv [I] The key container, which the key belongs to.
3561 * hHash [I] The key object that is to be queried.
3562 * dwParam [I] Specifies the parameter that is to be queried.
3563 * pbData [I] Pointer to the buffer where the parameter value will be stored.
3564 * pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
3565 * dwFlags [I] None currently defined.
3567 * RETURNS
3568 * Success: TRUE
3569 * Failure: FALSE
3571 * NOTES
3572 * Defined dwParam types are:
3573 * - KP_MODE: Values MODE_CBC, MODE_ECB, MODE_CFB.
3574 * - KP_MODE_BITS: Shift width for cipher feedback mode.
3575 * (Currently ignored by MS CSP's - always eight)
3576 * - KP_PERMISSIONS: Or'ed combination of CRYPT_ENCRYPT, CRYPT_DECRYPT,
3577 * CRYPT_EXPORT, CRYPT_READ, CRYPT_WRITE, CRYPT_MAC
3578 * - KP_IV: Initialization vector.
3579 * - KP_KEYLEN: Bitwidth of the key.
3580 * - KP_BLOCKLEN: Size of a block cipher block.
3581 * - KP_SALT: Salt value.
3583 BOOL WINAPI RSAENH_CPGetKeyParam(HCRYPTPROV hProv, HCRYPTKEY hKey, DWORD dwParam, BYTE *pbData,
3584 DWORD *pdwDataLen, DWORD dwFlags)
3586 CRYPTKEY *pCryptKey;
3587 DWORD dwValue;
3589 TRACE("(hProv=%08lx, hKey=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p dwFlags=%08x)\n",
3590 hProv, hKey, dwParam, pbData, pdwDataLen, dwFlags);
3592 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3594 SetLastError(NTE_BAD_UID);
3595 return FALSE;
3598 if (dwFlags) {
3599 SetLastError(NTE_BAD_FLAGS);
3600 return FALSE;
3603 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
3605 SetLastError(NTE_BAD_KEY);
3606 return FALSE;
3609 switch (dwParam)
3611 case KP_IV:
3612 return copy_param(pbData, pdwDataLen, pCryptKey->abInitVector,
3613 pCryptKey->dwBlockLen);
3615 case KP_SALT:
3616 switch (pCryptKey->aiAlgid) {
3617 case CALG_RC2:
3618 case CALG_RC4:
3619 return copy_param(pbData, pdwDataLen,
3620 &pCryptKey->abKeyValue[pCryptKey->dwKeyLen],
3621 pCryptKey->dwSaltLen);
3622 default:
3623 SetLastError(NTE_BAD_KEY);
3624 return FALSE;
3627 case KP_PADDING:
3628 dwValue = PKCS5_PADDING;
3629 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwValue, sizeof(DWORD));
3631 case KP_KEYLEN:
3632 dwValue = pCryptKey->dwKeyLen << 3;
3633 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwValue, sizeof(DWORD));
3635 case KP_EFFECTIVE_KEYLEN:
3636 if (pCryptKey->dwEffectiveKeyLen)
3637 dwValue = pCryptKey->dwEffectiveKeyLen;
3638 else
3639 dwValue = pCryptKey->dwKeyLen << 3;
3640 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwValue, sizeof(DWORD));
3642 case KP_BLOCKLEN:
3643 dwValue = pCryptKey->dwBlockLen << 3;
3644 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwValue, sizeof(DWORD));
3646 case KP_MODE:
3647 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptKey->dwMode, sizeof(DWORD));
3649 case KP_MODE_BITS:
3650 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptKey->dwModeBits,
3651 sizeof(DWORD));
3653 case KP_PERMISSIONS:
3654 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptKey->dwPermissions,
3655 sizeof(DWORD));
3657 case KP_ALGID:
3658 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptKey->aiAlgid, sizeof(DWORD));
3660 default:
3661 SetLastError(NTE_BAD_TYPE);
3662 return FALSE;
3666 /******************************************************************************
3667 * CPGetProvParam (RSAENH.@)
3669 * Query a CSP parameter.
3671 * PARAMS
3672 * hProv [I] The key container that is to be queried.
3673 * dwParam [I] Specifies the parameter that is to be queried.
3674 * pbData [I] Pointer to the buffer where the parameter value will be stored.
3675 * pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
3676 * dwFlags [I] CRYPT_FIRST: Start enumeration (for PP_ENUMALGS{_EX}).
3678 * RETURNS
3679 * Success: TRUE
3680 * Failure: FALSE
3681 * NOTES:
3682 * Defined dwParam types:
3683 * - PP_CONTAINER: Name of the key container.
3684 * - PP_NAME: Name of the cryptographic service provider.
3685 * - PP_SIG_KEYSIZE_INC: RSA signature keywidth granularity in bits.
3686 * - PP_KEYX_KEYSIZE_INC: RSA key-exchange keywidth granularity in bits.
3687 * - PP_ENUMALGS{_EX}: Query provider capabilities.
3688 * - PP_KEYSET_SEC_DESCR: Retrieve security descriptor on container.
3690 BOOL WINAPI RSAENH_CPGetProvParam(HCRYPTPROV hProv, DWORD dwParam, BYTE *pbData,
3691 DWORD *pdwDataLen, DWORD dwFlags)
3693 KEYCONTAINER *pKeyContainer;
3694 PROV_ENUMALGS provEnumalgs;
3695 DWORD dwTemp;
3696 HKEY hKey;
3698 /* This is for dwParam PP_CRYPT_COUNT_KEY_USE.
3699 * IE6 SP1 asks for it in the 'About' dialog.
3700 * Returning this BLOB seems to satisfy IE. The marked 0x00 seem
3701 * to be 'don't care's. If you know anything more specific about
3702 * this provider parameter, please report to wine-devel@winehq.org */
3703 static const BYTE abWTF[96] = {
3704 0xb0, 0x25, 0x63, 0x86, 0x9c, 0xab, 0xb6, 0x37,
3705 0xe8, 0x82, /**/0x00,/**/ 0x72, 0x06, 0xb2, /**/0x00,/**/ 0x3b,
3706 0x60, 0x35, /**/0x00,/**/ 0x3b, 0x88, 0xce, /**/0x00,/**/ 0x82,
3707 0xbc, 0x7a, /**/0x00,/**/ 0xb7, 0x4f, 0x7e, /**/0x00,/**/ 0xde,
3708 0x92, 0xf1, /**/0x00,/**/ 0x83, 0xea, 0x5e, /**/0x00,/**/ 0xc8,
3709 0x12, 0x1e, 0xd4, 0x06, 0xf7, 0x66, /**/0x00,/**/ 0x01,
3710 0x29, 0xa4, /**/0x00,/**/ 0xf8, 0x24, 0x0c, /**/0x00,/**/ 0x33,
3711 0x06, 0x80, /**/0x00,/**/ 0x02, 0x46, 0x0b, /**/0x00,/**/ 0x6d,
3712 0x5b, 0xca, /**/0x00,/**/ 0x9a, 0x10, 0xf0, /**/0x00,/**/ 0x05,
3713 0x19, 0xd0, /**/0x00,/**/ 0x2c, 0xf6, 0x27, /**/0x00,/**/ 0xaa,
3714 0x7c, 0x6f, /**/0x00,/**/ 0xb9, 0xd8, 0x72, /**/0x00,/**/ 0x03,
3715 0xf3, 0x81, /**/0x00,/**/ 0xfa, 0xe8, 0x26, /**/0x00,/**/ 0xca
3718 TRACE("(hProv=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p, dwFlags=%08x)\n",
3719 hProv, dwParam, pbData, pdwDataLen, dwFlags);
3721 if (!pdwDataLen) {
3722 SetLastError(ERROR_INVALID_PARAMETER);
3723 return FALSE;
3726 if (!(pKeyContainer = get_key_container(hProv)))
3728 /* MSDN: hProv not containing valid context handle */
3729 return FALSE;
3732 switch (dwParam)
3734 case PP_CONTAINER:
3735 case PP_UNIQUE_CONTAINER:/* MSDN says we can return the same value as PP_CONTAINER */
3736 return copy_param(pbData, pdwDataLen, (const BYTE*)pKeyContainer->szName,
3737 strlen(pKeyContainer->szName)+1);
3739 case PP_NAME:
3740 return copy_param(pbData, pdwDataLen, (const BYTE*)pKeyContainer->szProvName,
3741 strlen(pKeyContainer->szProvName)+1);
3743 case PP_PROVTYPE:
3744 dwTemp = PROV_RSA_FULL;
3745 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
3747 case PP_KEYSPEC:
3748 dwTemp = AT_SIGNATURE | AT_KEYEXCHANGE;
3749 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
3751 case PP_KEYSET_TYPE:
3752 dwTemp = pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET;
3753 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
3755 case PP_KEYSTORAGE:
3756 dwTemp = CRYPT_SEC_DESCR;
3757 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
3759 case PP_SIG_KEYSIZE_INC:
3760 case PP_KEYX_KEYSIZE_INC:
3761 dwTemp = 8;
3762 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
3764 case PP_IMPTYPE:
3765 dwTemp = CRYPT_IMPL_SOFTWARE;
3766 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
3768 case PP_VERSION:
3769 dwTemp = 0x00000200;
3770 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
3772 case PP_ENUMCONTAINERS:
3773 if ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) pKeyContainer->dwEnumContainersCtr = 0;
3775 if (!pbData) {
3776 *pdwDataLen = (DWORD)MAX_PATH + 1;
3777 return TRUE;
3780 if (!open_container_key("", dwFlags, KEY_READ, &hKey))
3782 SetLastError(ERROR_NO_MORE_ITEMS);
3783 return FALSE;
3786 dwTemp = *pdwDataLen;
3787 switch (RegEnumKeyExA(hKey, pKeyContainer->dwEnumContainersCtr, (LPSTR)pbData, &dwTemp,
3788 NULL, NULL, NULL, NULL))
3790 case ERROR_MORE_DATA:
3791 *pdwDataLen = (DWORD)MAX_PATH + 1;
3793 case ERROR_SUCCESS:
3794 pKeyContainer->dwEnumContainersCtr++;
3795 RegCloseKey(hKey);
3796 return TRUE;
3798 case ERROR_NO_MORE_ITEMS:
3799 default:
3800 SetLastError(ERROR_NO_MORE_ITEMS);
3801 RegCloseKey(hKey);
3802 return FALSE;
3805 case PP_ENUMALGS:
3806 case PP_ENUMALGS_EX:
3807 if (((pKeyContainer->dwEnumAlgsCtr >= RSAENH_MAX_ENUMALGS-1) ||
3808 (!aProvEnumAlgsEx[pKeyContainer->dwPersonality]
3809 [pKeyContainer->dwEnumAlgsCtr+1].aiAlgid)) &&
3810 ((dwFlags & CRYPT_FIRST) != CRYPT_FIRST))
3812 SetLastError(ERROR_NO_MORE_ITEMS);
3813 return FALSE;
3816 if (dwParam == PP_ENUMALGS) {
3817 if (pbData && (*pdwDataLen >= sizeof(PROV_ENUMALGS)))
3818 pKeyContainer->dwEnumAlgsCtr = ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) ?
3819 0 : pKeyContainer->dwEnumAlgsCtr+1;
3821 provEnumalgs.aiAlgid = aProvEnumAlgsEx
3822 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].aiAlgid;
3823 provEnumalgs.dwBitLen = aProvEnumAlgsEx
3824 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].dwDefaultLen;
3825 provEnumalgs.dwNameLen = aProvEnumAlgsEx
3826 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].dwNameLen;
3827 memcpy(provEnumalgs.szName, aProvEnumAlgsEx
3828 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].szName,
3829 20*sizeof(CHAR));
3831 return copy_param(pbData, pdwDataLen, (const BYTE*)&provEnumalgs,
3832 sizeof(PROV_ENUMALGS));
3833 } else {
3834 if (pbData && (*pdwDataLen >= sizeof(PROV_ENUMALGS_EX)))
3835 pKeyContainer->dwEnumAlgsCtr = ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) ?
3836 0 : pKeyContainer->dwEnumAlgsCtr+1;
3838 return copy_param(pbData, pdwDataLen,
3839 (const BYTE*)&aProvEnumAlgsEx
3840 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr],
3841 sizeof(PROV_ENUMALGS_EX));
3844 case PP_CRYPT_COUNT_KEY_USE: /* Asked for by IE About dialog */
3845 return copy_param(pbData, pdwDataLen, abWTF, sizeof(abWTF));
3847 case PP_KEYSET_SEC_DESCR:
3849 SECURITY_DESCRIPTOR *sd;
3850 DWORD err, len, flags = (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET);
3852 if (!open_container_key(pKeyContainer->szName, flags, KEY_READ, &hKey))
3854 SetLastError(NTE_BAD_KEYSET);
3855 return FALSE;
3858 err = GetSecurityInfo(hKey, SE_REGISTRY_KEY, dwFlags, NULL, NULL, NULL, NULL, (void **)&sd);
3859 RegCloseKey(hKey);
3860 if (err)
3862 SetLastError(err);
3863 return FALSE;
3866 len = GetSecurityDescriptorLength(sd);
3867 if (*pdwDataLen >= len) memcpy(pbData, sd, len);
3868 else SetLastError(ERROR_INSUFFICIENT_BUFFER);
3869 *pdwDataLen = len;
3871 LocalFree(sd);
3872 return TRUE;
3875 default:
3876 /* MSDN: Unknown parameter number in dwParam */
3877 SetLastError(NTE_BAD_TYPE);
3878 return FALSE;
3882 /******************************************************************************
3883 * CPDeriveKey (RSAENH.@)
3885 * Derives a key from a hash value.
3887 * PARAMS
3888 * hProv [I] Key container for which a key is to be generated.
3889 * Algid [I] Crypto algorithm identifier for the key to be generated.
3890 * hBaseData [I] Hash from whose value the key will be derived.
3891 * dwFlags [I] See Notes.
3892 * phKey [O] The generated key.
3894 * RETURNS
3895 * Success: TRUE
3896 * Failure: FALSE
3898 * NOTES
3899 * Defined flags:
3900 * - CRYPT_EXPORTABLE: Key can be exported.
3901 * - CRYPT_NO_SALT: No salt is used for 40 bit keys.
3902 * - CRYPT_CREATE_SALT: Use remaining bits as salt value.
3904 BOOL WINAPI RSAENH_CPDeriveKey(HCRYPTPROV hProv, ALG_ID Algid, HCRYPTHASH hBaseData,
3905 DWORD dwFlags, HCRYPTKEY *phKey)
3907 CRYPTKEY *pCryptKey, *pMasterKey;
3908 CRYPTHASH *pCryptHash;
3909 BYTE abHashValue[RSAENH_MAX_HASH_SIZE*2];
3910 DWORD dwLen;
3912 TRACE("(hProv=%08lx, Algid=%d, hBaseData=%08lx, dwFlags=%08x phKey=%p)\n", hProv, Algid,
3913 hBaseData, dwFlags, phKey);
3915 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3917 SetLastError(NTE_BAD_UID);
3918 return FALSE;
3921 if (!lookup_handle(&handle_table, hBaseData, RSAENH_MAGIC_HASH,
3922 (OBJECTHDR**)&pCryptHash))
3924 SetLastError(NTE_BAD_HASH);
3925 return FALSE;
3928 if (!phKey)
3930 SetLastError(ERROR_INVALID_PARAMETER);
3931 return FALSE;
3934 switch (GET_ALG_CLASS(Algid))
3936 case ALG_CLASS_DATA_ENCRYPT:
3938 int need_padding, copy_len;
3939 *phKey = new_key(hProv, Algid, dwFlags, &pCryptKey);
3940 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
3943 * We derive the key material from the hash.
3944 * If the hash value is not large enough for the claimed key, we have to construct
3945 * a larger binary value based on the hash. This is documented in MSDN: CryptDeriveKey.
3947 dwLen = RSAENH_MAX_HASH_SIZE;
3948 RSAENH_CPGetHashParam(pCryptHash->hProv, hBaseData, HP_HASHVAL, abHashValue, &dwLen, 0);
3951 * The usage of padding seems to vary from algorithm to algorithm.
3952 * For now the only different case found was for AES with 128 bit key.
3954 switch(Algid)
3956 case CALG_AES_128:
3957 /* To reduce the chance of regressions we will only deviate
3958 * from the old behavior for the tested hash lengths */
3959 if (dwLen == 16 || dwLen == 20)
3961 need_padding = 1;
3962 break;
3964 default:
3965 need_padding = dwLen < pCryptKey->dwKeyLen;
3968 copy_len = pCryptKey->dwKeyLen;
3969 if (need_padding)
3971 BYTE pad1[RSAENH_HMAC_DEF_PAD_LEN], pad2[RSAENH_HMAC_DEF_PAD_LEN];
3972 BYTE old_hashval[RSAENH_MAX_HASH_SIZE];
3973 DWORD i;
3975 memcpy(old_hashval, pCryptHash->abHashValue, RSAENH_MAX_HASH_SIZE);
3977 for (i=0; i<RSAENH_HMAC_DEF_PAD_LEN; i++) {
3978 pad1[i] = RSAENH_HMAC_DEF_IPAD_CHAR ^ (i<dwLen ? abHashValue[i] : 0);
3979 pad2[i] = RSAENH_HMAC_DEF_OPAD_CHAR ^ (i<dwLen ? abHashValue[i] : 0);
3982 init_hash(pCryptHash);
3983 update_hash(pCryptHash, pad1, RSAENH_HMAC_DEF_PAD_LEN);
3984 finalize_hash(pCryptHash);
3985 memcpy(abHashValue, pCryptHash->abHashValue, pCryptHash->dwHashSize);
3987 init_hash(pCryptHash);
3988 update_hash(pCryptHash, pad2, RSAENH_HMAC_DEF_PAD_LEN);
3989 finalize_hash(pCryptHash);
3990 memcpy(abHashValue+pCryptHash->dwHashSize, pCryptHash->abHashValue,
3991 pCryptHash->dwHashSize);
3993 memcpy(pCryptHash->abHashValue, old_hashval, RSAENH_MAX_HASH_SIZE);
3996 * Padding was not required, we have more hash than needed.
3997 * Do we need to use the remaining hash as salt?
3999 else if((dwFlags & CRYPT_CREATE_SALT) &&
4000 (Algid == CALG_RC2 || Algid == CALG_RC4))
4002 copy_len += pCryptKey->dwSaltLen;
4005 memcpy(pCryptKey->abKeyValue, abHashValue,
4006 RSAENH_MIN(copy_len, sizeof(pCryptKey->abKeyValue)));
4007 break;
4009 case ALG_CLASS_MSG_ENCRYPT:
4010 if (!lookup_handle(&handle_table, pCryptHash->hKey, RSAENH_MAGIC_KEY,
4011 (OBJECTHDR**)&pMasterKey))
4013 SetLastError(NTE_FAIL); /* FIXME error code */
4014 return FALSE;
4017 switch (Algid)
4019 /* See RFC 2246, chapter 6.3 Key calculation */
4020 case CALG_SCHANNEL_ENC_KEY:
4021 if (!pMasterKey->siSChannelInfo.saEncAlg.Algid ||
4022 !pMasterKey->siSChannelInfo.saEncAlg.cBits)
4024 SetLastError(NTE_BAD_FLAGS);
4025 return FALSE;
4027 *phKey = new_key(hProv, pMasterKey->siSChannelInfo.saEncAlg.Algid,
4028 MAKELONG(LOWORD(dwFlags),pMasterKey->siSChannelInfo.saEncAlg.cBits),
4029 &pCryptKey);
4030 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
4031 memcpy(pCryptKey->abKeyValue,
4032 pCryptHash->abHashValue + (
4033 2 * (pMasterKey->siSChannelInfo.saMACAlg.cBits / 8) +
4034 ((dwFlags & CRYPT_SERVER) ?
4035 (pMasterKey->siSChannelInfo.saEncAlg.cBits / 8) : 0)),
4036 pMasterKey->siSChannelInfo.saEncAlg.cBits / 8);
4037 memcpy(pCryptKey->abInitVector,
4038 pCryptHash->abHashValue + (
4039 2 * (pMasterKey->siSChannelInfo.saMACAlg.cBits / 8) +
4040 2 * (pMasterKey->siSChannelInfo.saEncAlg.cBits / 8) +
4041 ((dwFlags & CRYPT_SERVER) ? pCryptKey->dwBlockLen : 0)),
4042 pCryptKey->dwBlockLen);
4043 break;
4045 case CALG_SCHANNEL_MAC_KEY:
4046 *phKey = new_key(hProv, Algid,
4047 MAKELONG(LOWORD(dwFlags),pMasterKey->siSChannelInfo.saMACAlg.cBits),
4048 &pCryptKey);
4049 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
4050 memcpy(pCryptKey->abKeyValue,
4051 pCryptHash->abHashValue + ((dwFlags & CRYPT_SERVER) ?
4052 pMasterKey->siSChannelInfo.saMACAlg.cBits / 8 : 0),
4053 pMasterKey->siSChannelInfo.saMACAlg.cBits / 8);
4054 break;
4056 default:
4057 SetLastError(NTE_BAD_ALGID);
4058 return FALSE;
4060 break;
4062 default:
4063 SetLastError(NTE_BAD_ALGID);
4064 return FALSE;
4067 setup_key(pCryptKey);
4068 return TRUE;
4071 /******************************************************************************
4072 * CPGetUserKey (RSAENH.@)
4074 * Returns a handle to the user's private key-exchange- or signature-key.
4076 * PARAMS
4077 * hProv [I] The key container from which a user key is requested.
4078 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
4079 * phUserKey [O] Handle to the requested key or INVALID_HANDLE_VALUE in case of failure.
4081 * RETURNS
4082 * Success: TRUE.
4083 * Failure: FALSE.
4085 * NOTE
4086 * A newly created key container does not contain private user key. Create them with CPGenKey.
4088 BOOL WINAPI RSAENH_CPGetUserKey(HCRYPTPROV hProv, DWORD dwKeySpec, HCRYPTKEY *phUserKey)
4090 KEYCONTAINER *pKeyContainer;
4092 TRACE("(hProv=%08lx, dwKeySpec=%08x, phUserKey=%p)\n", hProv, dwKeySpec, phUserKey);
4094 if (!(pKeyContainer = get_key_container(hProv)))
4096 /* MSDN: hProv not containing valid context handle */
4097 return FALSE;
4100 switch (dwKeySpec)
4102 case AT_KEYEXCHANGE:
4103 copy_handle(&handle_table, pKeyContainer->hKeyExchangeKeyPair, RSAENH_MAGIC_KEY,
4104 phUserKey);
4105 break;
4107 case AT_SIGNATURE:
4108 copy_handle(&handle_table, pKeyContainer->hSignatureKeyPair, RSAENH_MAGIC_KEY,
4109 phUserKey);
4110 break;
4112 default:
4113 *phUserKey = (HCRYPTKEY)INVALID_HANDLE_VALUE;
4116 if (*phUserKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
4118 /* MSDN: dwKeySpec parameter specifies nonexistent key */
4119 SetLastError(NTE_NO_KEY);
4120 return FALSE;
4123 return TRUE;
4126 /******************************************************************************
4127 * CPHashData (RSAENH.@)
4129 * Updates a hash object with the given data.
4131 * PARAMS
4132 * hProv [I] Key container to which the hash object belongs.
4133 * hHash [I] Hash object which is to be updated.
4134 * pbData [I] Pointer to data with which the hash object is to be updated.
4135 * dwDataLen [I] Length of the data.
4136 * dwFlags [I] Currently none defined.
4138 * RETURNS
4139 * Success: TRUE.
4140 * Failure: FALSE.
4142 * NOTES
4143 * The actual hash value is queried with CPGetHashParam, which will finalize
4144 * the hash. Updating a finalized hash will fail with a last error NTE_BAD_HASH_STATE.
4146 BOOL WINAPI RSAENH_CPHashData(HCRYPTPROV hProv, HCRYPTHASH hHash, const BYTE *pbData,
4147 DWORD dwDataLen, DWORD dwFlags)
4149 CRYPTHASH *pCryptHash;
4151 TRACE("(hProv=%08lx, hHash=%08lx, pbData=%p, dwDataLen=%d, dwFlags=%08x)\n",
4152 hProv, hHash, pbData, dwDataLen, dwFlags);
4154 if (dwFlags & ~CRYPT_USERDATA)
4156 SetLastError(NTE_BAD_FLAGS);
4157 return FALSE;
4160 if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH,
4161 (OBJECTHDR**)&pCryptHash))
4163 SetLastError(NTE_BAD_HASH);
4164 return FALSE;
4167 if (!get_algid_info(hProv, pCryptHash->aiAlgid) || pCryptHash->aiAlgid == CALG_SSL3_SHAMD5)
4169 SetLastError(NTE_BAD_ALGID);
4170 return FALSE;
4173 if (pCryptHash->dwState != RSAENH_HASHSTATE_HASHING)
4175 SetLastError(NTE_BAD_HASH_STATE);
4176 return FALSE;
4179 update_hash(pCryptHash, pbData, dwDataLen);
4180 return TRUE;
4183 /******************************************************************************
4184 * CPHashSessionKey (RSAENH.@)
4186 * Updates a hash object with the binary representation of a symmetric key.
4188 * PARAMS
4189 * hProv [I] Key container to which the hash object belongs.
4190 * hHash [I] Hash object which is to be updated.
4191 * hKey [I] The symmetric key, whose binary value will be added to the hash.
4192 * dwFlags [I] CRYPT_LITTLE_ENDIAN, if the binary key value shall be interpreted as little endian.
4194 * RETURNS
4195 * Success: TRUE.
4196 * Failure: FALSE.
4198 BOOL WINAPI RSAENH_CPHashSessionKey(HCRYPTPROV hProv, HCRYPTHASH hHash, HCRYPTKEY hKey,
4199 DWORD dwFlags)
4201 BYTE abKeyValue[RSAENH_MAX_KEY_SIZE], bTemp;
4202 CRYPTKEY *pKey;
4203 DWORD i;
4205 TRACE("(hProv=%08lx, hHash=%08lx, hKey=%08lx, dwFlags=%08x)\n", hProv, hHash, hKey, dwFlags);
4207 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pKey) ||
4208 (GET_ALG_CLASS(pKey->aiAlgid) != ALG_CLASS_DATA_ENCRYPT))
4210 SetLastError(NTE_BAD_KEY);
4211 return FALSE;
4214 if (dwFlags & ~CRYPT_LITTLE_ENDIAN) {
4215 SetLastError(NTE_BAD_FLAGS);
4216 return FALSE;
4219 memcpy(abKeyValue, pKey->abKeyValue, pKey->dwKeyLen);
4220 if (!(dwFlags & CRYPT_LITTLE_ENDIAN)) {
4221 for (i=0; i<pKey->dwKeyLen/2; i++) {
4222 bTemp = abKeyValue[i];
4223 abKeyValue[i] = abKeyValue[pKey->dwKeyLen-i-1];
4224 abKeyValue[pKey->dwKeyLen-i-1] = bTemp;
4228 return RSAENH_CPHashData(hProv, hHash, abKeyValue, pKey->dwKeyLen, 0);
4231 /******************************************************************************
4232 * CPReleaseContext (RSAENH.@)
4234 * Release a key container.
4236 * PARAMS
4237 * hProv [I] Key container to be released.
4238 * dwFlags [I] Currently none defined.
4240 * RETURNS
4241 * Success: TRUE
4242 * Failure: FALSE
4244 BOOL WINAPI RSAENH_CPReleaseContext(HCRYPTPROV hProv, DWORD dwFlags)
4246 TRACE("(hProv=%08lx, dwFlags=%08x)\n", hProv, dwFlags);
4248 if (!release_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
4250 /* MSDN: hProv not containing valid context handle */
4251 SetLastError(NTE_BAD_UID);
4252 return FALSE;
4255 if (dwFlags) {
4256 SetLastError(NTE_BAD_FLAGS);
4257 return FALSE;
4260 return TRUE;
4263 /******************************************************************************
4264 * CPSetHashParam (RSAENH.@)
4266 * Set a parameter of a hash object
4268 * PARAMS
4269 * hProv [I] The key container to which the key belongs.
4270 * hHash [I] The hash object for which a parameter is to be set.
4271 * dwParam [I] Parameter type. See Notes.
4272 * pbData [I] Pointer to the parameter value.
4273 * dwFlags [I] Currently none defined.
4275 * RETURNS
4276 * Success: TRUE.
4277 * Failure: FALSE.
4279 * NOTES
4280 * Currently only the HP_HMAC_INFO dwParam type is defined.
4281 * The HMAC_INFO struct will be deep copied into the hash object.
4282 * See Internet RFC 2104 for details on the HMAC algorithm.
4284 BOOL WINAPI RSAENH_CPSetHashParam(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwParam,
4285 BYTE *pbData, DWORD dwFlags)
4287 CRYPTHASH *pCryptHash;
4288 CRYPTKEY *pCryptKey;
4289 DWORD i;
4291 TRACE("(hProv=%08lx, hHash=%08lx, dwParam=%08x, pbData=%p, dwFlags=%08x)\n",
4292 hProv, hHash, dwParam, pbData, dwFlags);
4294 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
4296 SetLastError(NTE_BAD_UID);
4297 return FALSE;
4300 if (dwFlags) {
4301 SetLastError(NTE_BAD_FLAGS);
4302 return FALSE;
4305 if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH,
4306 (OBJECTHDR**)&pCryptHash))
4308 SetLastError(NTE_BAD_HASH);
4309 return FALSE;
4312 switch (dwParam) {
4313 case HP_HMAC_INFO:
4314 free_hmac_info(pCryptHash->pHMACInfo);
4315 if (!copy_hmac_info(&pCryptHash->pHMACInfo, (PHMAC_INFO)pbData)) return FALSE;
4317 if (!lookup_handle(&handle_table, pCryptHash->hKey, RSAENH_MAGIC_KEY,
4318 (OBJECTHDR**)&pCryptKey))
4320 SetLastError(NTE_FAIL); /* FIXME: correct error code? */
4321 return FALSE;
4324 if (pCryptKey->aiAlgid == CALG_HMAC && !pCryptKey->dwKeyLen) {
4325 HCRYPTHASH hKeyHash;
4326 DWORD keyLen;
4328 if (!RSAENH_CPCreateHash(hProv, ((PHMAC_INFO)pbData)->HashAlgid, 0, 0,
4329 &hKeyHash))
4330 return FALSE;
4331 if (!RSAENH_CPHashData(hProv, hKeyHash, pCryptKey->blobHmacKey.pbData,
4332 pCryptKey->blobHmacKey.cbData, 0))
4334 RSAENH_CPDestroyHash(hProv, hKeyHash);
4335 return FALSE;
4337 keyLen = sizeof(pCryptKey->abKeyValue);
4338 if (!RSAENH_CPGetHashParam(hProv, hKeyHash, HP_HASHVAL, pCryptKey->abKeyValue,
4339 &keyLen, 0))
4341 RSAENH_CPDestroyHash(hProv, hKeyHash);
4342 return FALSE;
4344 pCryptKey->dwKeyLen = keyLen;
4345 RSAENH_CPDestroyHash(hProv, hKeyHash);
4347 for (i=0; i<RSAENH_MIN(pCryptKey->dwKeyLen,pCryptHash->pHMACInfo->cbInnerString); i++) {
4348 pCryptHash->pHMACInfo->pbInnerString[i] ^= pCryptKey->abKeyValue[i];
4350 for (i=0; i<RSAENH_MIN(pCryptKey->dwKeyLen,pCryptHash->pHMACInfo->cbOuterString); i++) {
4351 pCryptHash->pHMACInfo->pbOuterString[i] ^= pCryptKey->abKeyValue[i];
4354 init_hash(pCryptHash);
4355 return TRUE;
4357 case HP_HASHVAL:
4358 memcpy(pCryptHash->abHashValue, pbData, pCryptHash->dwHashSize);
4359 pCryptHash->dwState = RSAENH_HASHSTATE_FINISHED;
4360 return TRUE;
4362 case HP_TLS1PRF_SEED:
4363 return copy_data_blob(&pCryptHash->tpPRFParams.blobSeed, (PCRYPT_DATA_BLOB)pbData);
4365 case HP_TLS1PRF_LABEL:
4366 return copy_data_blob(&pCryptHash->tpPRFParams.blobLabel, (PCRYPT_DATA_BLOB)pbData);
4368 default:
4369 SetLastError(NTE_BAD_TYPE);
4370 return FALSE;
4374 /******************************************************************************
4375 * CPSetProvParam (RSAENH.@)
4377 BOOL WINAPI RSAENH_CPSetProvParam(HCRYPTPROV hProv, DWORD dwParam, BYTE *pbData, DWORD dwFlags)
4379 KEYCONTAINER *pKeyContainer;
4380 HKEY hKey;
4382 TRACE("(hProv=%08lx, dwParam=%08x, pbData=%p, dwFlags=%08x)\n", hProv, dwParam, pbData, dwFlags);
4384 if (!(pKeyContainer = get_key_container(hProv)))
4385 return FALSE;
4387 switch (dwParam)
4389 case PP_KEYSET_SEC_DESCR:
4391 SECURITY_DESCRIPTOR *sd = (SECURITY_DESCRIPTOR *)pbData;
4392 DWORD err, flags = (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET);
4393 BOOL def, present;
4394 REGSAM access = WRITE_DAC | WRITE_OWNER | ACCESS_SYSTEM_SECURITY;
4395 PSID owner = NULL, group = NULL;
4396 PACL dacl = NULL, sacl = NULL;
4398 if (!open_container_key(pKeyContainer->szName, flags, access, &hKey))
4400 SetLastError(NTE_BAD_KEYSET);
4401 return FALSE;
4404 if ((dwFlags & OWNER_SECURITY_INFORMATION && !GetSecurityDescriptorOwner(sd, &owner, &def)) ||
4405 (dwFlags & GROUP_SECURITY_INFORMATION && !GetSecurityDescriptorGroup(sd, &group, &def)) ||
4406 (dwFlags & DACL_SECURITY_INFORMATION && !GetSecurityDescriptorDacl(sd, &present, &dacl, &def)) ||
4407 (dwFlags & SACL_SECURITY_INFORMATION && !GetSecurityDescriptorSacl(sd, &present, &sacl, &def)))
4409 RegCloseKey(hKey);
4410 return FALSE;
4413 err = SetSecurityInfo(hKey, SE_REGISTRY_KEY, dwFlags, owner, group, dacl, sacl);
4414 RegCloseKey(hKey);
4415 if (err)
4417 SetLastError(err);
4418 return FALSE;
4420 return TRUE;
4422 default:
4423 FIXME("unimplemented parameter %08x\n", dwParam);
4424 return FALSE;
4428 /******************************************************************************
4429 * CPSignHash (RSAENH.@)
4431 * Sign a hash object
4433 * PARAMS
4434 * hProv [I] The key container, to which the hash object belongs.
4435 * hHash [I] The hash object to be signed.
4436 * dwKeySpec [I] AT_SIGNATURE or AT_KEYEXCHANGE: Key used to generate the signature.
4437 * sDescription [I] Should be NULL for security reasons.
4438 * dwFlags [I] 0, CRYPT_NOHASHOID or CRYPT_X931_FORMAT: Format of the signature.
4439 * pbSignature [O] Buffer, to which the signature will be stored. May be NULL to query SigLen.
4440 * pdwSigLen [I/O] Size of the buffer (in), Length of the signature (out)
4442 * RETURNS
4443 * Success: TRUE
4444 * Failure: FALSE
4446 BOOL WINAPI RSAENH_CPSignHash(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwKeySpec,
4447 LPCWSTR sDescription, DWORD dwFlags, BYTE *pbSignature,
4448 DWORD *pdwSigLen)
4450 HCRYPTKEY hCryptKey = (HCRYPTKEY)INVALID_HANDLE_VALUE;
4451 CRYPTKEY *pCryptKey;
4452 DWORD dwHashLen;
4453 BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
4454 ALG_ID aiAlgid;
4455 BOOL ret = FALSE;
4457 TRACE("(hProv=%08lx, hHash=%08lx, dwKeySpec=%08x, sDescription=%s, dwFlags=%08x, "
4458 "pbSignature=%p, pdwSigLen=%p)\n", hProv, hHash, dwKeySpec, debugstr_w(sDescription),
4459 dwFlags, pbSignature, pdwSigLen);
4461 if (dwFlags & ~(CRYPT_NOHASHOID|CRYPT_X931_FORMAT)) {
4462 SetLastError(NTE_BAD_FLAGS);
4463 return FALSE;
4466 if (!RSAENH_CPGetUserKey(hProv, dwKeySpec, &hCryptKey)) return FALSE;
4468 if (!lookup_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY,
4469 (OBJECTHDR**)&pCryptKey))
4471 SetLastError(NTE_NO_KEY);
4472 goto out;
4475 if (!pbSignature) {
4476 *pdwSigLen = pCryptKey->dwKeyLen;
4477 ret = TRUE;
4478 goto out;
4480 if (pCryptKey->dwKeyLen > *pdwSigLen)
4482 SetLastError(ERROR_MORE_DATA);
4483 *pdwSigLen = pCryptKey->dwKeyLen;
4484 goto out;
4486 *pdwSigLen = pCryptKey->dwKeyLen;
4488 if (sDescription) {
4489 if (!RSAENH_CPHashData(hProv, hHash, (const BYTE*)sDescription,
4490 (DWORD)lstrlenW(sDescription)*sizeof(WCHAR), 0))
4492 goto out;
4496 dwHashLen = sizeof(DWORD);
4497 if (!RSAENH_CPGetHashParam(hProv, hHash, HP_ALGID, (BYTE*)&aiAlgid, &dwHashLen, 0)) goto out;
4499 dwHashLen = RSAENH_MAX_HASH_SIZE;
4500 if (!RSAENH_CPGetHashParam(hProv, hHash, HP_HASHVAL, abHashValue, &dwHashLen, 0)) goto out;
4503 if (!build_hash_signature(pbSignature, *pdwSigLen, aiAlgid, abHashValue, dwHashLen, dwFlags)) {
4504 goto out;
4507 ret = encrypt_block_impl(pCryptKey->aiAlgid, PK_PRIVATE, &pCryptKey->context, pbSignature, pbSignature, RSAENH_ENCRYPT);
4508 out:
4509 RSAENH_CPDestroyKey(hProv, hCryptKey);
4510 return ret;
4513 /******************************************************************************
4514 * CPVerifySignature (RSAENH.@)
4516 * Verify the signature of a hash object.
4518 * PARAMS
4519 * hProv [I] The key container, to which the hash belongs.
4520 * hHash [I] The hash for which the signature is verified.
4521 * pbSignature [I] The binary signature.
4522 * dwSigLen [I] Length of the signature BLOB.
4523 * hPubKey [I] Public key used to verify the signature.
4524 * sDescription [I] Should be NULL for security reasons.
4525 * dwFlags [I] 0, CRYPT_NOHASHOID or CRYPT_X931_FORMAT: Format of the signature.
4527 * RETURNS
4528 * Success: TRUE (Signature is valid)
4529 * Failure: FALSE (GetLastError() == NTE_BAD_SIGNATURE, if signature is invalid)
4531 BOOL WINAPI RSAENH_CPVerifySignature(HCRYPTPROV hProv, HCRYPTHASH hHash, const BYTE *pbSignature,
4532 DWORD dwSigLen, HCRYPTKEY hPubKey, LPCWSTR sDescription,
4533 DWORD dwFlags)
4535 BYTE *pbConstructed = NULL, *pbDecrypted = NULL;
4536 CRYPTKEY *pCryptKey;
4537 DWORD dwHashLen;
4538 ALG_ID aiAlgid;
4539 BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
4540 BOOL res = FALSE;
4542 TRACE("(hProv=%08lx, hHash=%08lx, pbSignature=%p, dwSigLen=%d, hPubKey=%08lx, sDescription=%s, "
4543 "dwFlags=%08x)\n", hProv, hHash, pbSignature, dwSigLen, hPubKey, debugstr_w(sDescription),
4544 dwFlags);
4546 if (dwFlags & ~(CRYPT_NOHASHOID|CRYPT_X931_FORMAT)) {
4547 SetLastError(NTE_BAD_FLAGS);
4548 return FALSE;
4551 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
4553 SetLastError(NTE_BAD_UID);
4554 return FALSE;
4557 if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY,
4558 (OBJECTHDR**)&pCryptKey))
4560 SetLastError(NTE_BAD_KEY);
4561 return FALSE;
4564 /* in Microsoft implementation, the signature length is checked before
4565 * the signature pointer.
4567 if (dwSigLen != pCryptKey->dwKeyLen)
4569 SetLastError(NTE_BAD_SIGNATURE);
4570 return FALSE;
4573 if (!hHash || !pbSignature)
4575 SetLastError(ERROR_INVALID_PARAMETER);
4576 return FALSE;
4579 if (sDescription) {
4580 if (!RSAENH_CPHashData(hProv, hHash, (const BYTE*)sDescription,
4581 (DWORD)lstrlenW(sDescription)*sizeof(WCHAR), 0))
4583 return FALSE;
4587 dwHashLen = sizeof(DWORD);
4588 if (!RSAENH_CPGetHashParam(hProv, hHash, HP_ALGID, (BYTE*)&aiAlgid, &dwHashLen, 0)) return FALSE;
4590 dwHashLen = RSAENH_MAX_HASH_SIZE;
4591 if (!RSAENH_CPGetHashParam(hProv, hHash, HP_HASHVAL, abHashValue, &dwHashLen, 0)) return FALSE;
4593 pbConstructed = HeapAlloc(GetProcessHeap(), 0, dwSigLen);
4594 if (!pbConstructed) {
4595 SetLastError(NTE_NO_MEMORY);
4596 goto cleanup;
4599 pbDecrypted = HeapAlloc(GetProcessHeap(), 0, dwSigLen);
4600 if (!pbDecrypted) {
4601 SetLastError(NTE_NO_MEMORY);
4602 goto cleanup;
4605 if (!encrypt_block_impl(pCryptKey->aiAlgid, PK_PUBLIC, &pCryptKey->context, pbSignature, pbDecrypted,
4606 RSAENH_DECRYPT))
4608 goto cleanup;
4611 if (build_hash_signature(pbConstructed, dwSigLen, aiAlgid, abHashValue, dwHashLen, dwFlags) &&
4612 !memcmp(pbDecrypted, pbConstructed, dwSigLen)) {
4613 res = TRUE;
4614 goto cleanup;
4617 if (!(dwFlags & CRYPT_NOHASHOID) &&
4618 build_hash_signature(pbConstructed, dwSigLen, aiAlgid, abHashValue, dwHashLen, dwFlags|CRYPT_NOHASHOID) &&
4619 !memcmp(pbDecrypted, pbConstructed, dwSigLen)) {
4620 res = TRUE;
4621 goto cleanup;
4624 SetLastError(NTE_BAD_SIGNATURE);
4626 cleanup:
4627 HeapFree(GetProcessHeap(), 0, pbConstructed);
4628 HeapFree(GetProcessHeap(), 0, pbDecrypted);
4629 return res;
4632 /******************************************************************************
4633 * DllRegisterServer (RSAENH.@)
4635 HRESULT WINAPI DllRegisterServer(void)
4637 return __wine_register_resources( instance );
4640 /******************************************************************************
4641 * DllUnregisterServer (RSAENH.@)
4643 HRESULT WINAPI DllUnregisterServer(void)
4645 return __wine_unregister_resources( instance );