user32/listbox: Resize the entire item array at once in SetCount.
[wine.git] / dlls / rsaenh / rsaenh.c
blobc22b3dcaf1e93068a55d130997bda590139e39a5
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->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->context, pbData, dwDataLen);
675 break;
677 case CALG_MAC:
678 pbTemp = HeapAlloc(GetProcessHeap(), 0, dwDataLen);
679 if (!pbTemp) return;
680 memcpy(pbTemp, pbData, dwDataLen);
681 RSAENH_CPEncrypt(pCryptHash->hProv, pCryptHash->hKey, 0, FALSE, 0,
682 pbTemp, &dwDataLen, dwDataLen);
683 HeapFree(GetProcessHeap(), 0, pbTemp);
684 break;
686 default:
687 update_hash_impl(&pCryptHash->context, pbData, dwDataLen);
691 /******************************************************************************
692 * finalize_hash [Internal]
694 * Finalizes the hash, after all data has been hashed with update_hash.
695 * No additional data can be hashed afterwards until the hash gets initialized again.
697 * PARAMS
698 * pCryptHash [I] Hash object to be finalized.
700 static inline void finalize_hash(CRYPTHASH *pCryptHash) {
701 DWORD dwDataLen;
703 switch (pCryptHash->aiAlgid)
705 case CALG_HMAC:
706 if (pCryptHash->pHMACInfo) {
707 BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
709 finalize_hash_impl(&pCryptHash->context, pCryptHash->abHashValue);
710 memcpy(abHashValue, pCryptHash->abHashValue, pCryptHash->dwHashSize);
711 init_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context);
712 update_hash_impl(&pCryptHash->context,
713 pCryptHash->pHMACInfo->pbOuterString,
714 pCryptHash->pHMACInfo->cbOuterString);
715 update_hash_impl(&pCryptHash->context,
716 abHashValue, pCryptHash->dwHashSize);
717 finalize_hash_impl(&pCryptHash->context, pCryptHash->abHashValue);
719 break;
721 case CALG_MAC:
722 dwDataLen = 0;
723 RSAENH_CPEncrypt(pCryptHash->hProv, pCryptHash->hKey, 0, TRUE, 0,
724 pCryptHash->abHashValue, &dwDataLen, pCryptHash->dwHashSize);
725 break;
727 default:
728 finalize_hash_impl(&pCryptHash->context, pCryptHash->abHashValue);
732 /******************************************************************************
733 * destroy_key [Internal]
735 * Destructor for key objects
737 * PARAMS
738 * pCryptKey [I] Pointer to the key object to be destroyed.
739 * Will be invalid after function returns!
741 static void destroy_key(OBJECTHDR *pObject)
743 CRYPTKEY *pCryptKey = (CRYPTKEY*)pObject;
745 free_key_impl(pCryptKey->aiAlgid, &pCryptKey->context);
746 free_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom);
747 free_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom);
748 free_data_blob(&pCryptKey->blobHmacKey);
749 HeapFree(GetProcessHeap(), 0, pCryptKey);
752 /******************************************************************************
753 * setup_key [Internal]
755 * Initialize (or reset) a key object
757 * PARAMS
758 * pCryptKey [I] The key object to be initialized.
760 static inline void setup_key(CRYPTKEY *pCryptKey) {
761 pCryptKey->dwState = RSAENH_KEYSTATE_IDLE;
762 memcpy(pCryptKey->abChainVector, pCryptKey->abInitVector, sizeof(pCryptKey->abChainVector));
763 setup_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen,
764 pCryptKey->dwEffectiveKeyLen, pCryptKey->dwSaltLen,
765 pCryptKey->abKeyValue);
768 /******************************************************************************
769 * new_key [Internal]
771 * Creates a new key object without assigning the actual binary key value.
772 * This is done by CPDeriveKey, CPGenKey or CPImportKey, which call this function.
774 * PARAMS
775 * hProv [I] Handle to the provider to which the created key will belong.
776 * aiAlgid [I] The new key shall use the crypto algorithm identified by aiAlgid.
777 * dwFlags [I] Upper 16 bits give the key length.
778 * Lower 16 bits: CRYPT_EXPORTABLE, CRYPT_CREATE_SALT,
779 * CRYPT_NO_SALT
780 * ppCryptKey [O] Pointer to the created key
782 * RETURNS
783 * Success: Handle to the created key.
784 * Failure: INVALID_HANDLE_VALUE
786 static HCRYPTKEY new_key(HCRYPTPROV hProv, ALG_ID aiAlgid, DWORD dwFlags, CRYPTKEY **ppCryptKey)
788 HCRYPTKEY hCryptKey;
789 CRYPTKEY *pCryptKey;
790 DWORD dwKeyLen = HIWORD(dwFlags);
791 const PROV_ENUMALGS_EX *peaAlgidInfo;
793 *ppCryptKey = NULL;
796 * Retrieve the CSP's capabilities for the given ALG_ID value
798 peaAlgidInfo = get_algid_info(hProv, aiAlgid);
799 if (!peaAlgidInfo) return (HCRYPTKEY)INVALID_HANDLE_VALUE;
801 TRACE("alg = %s, dwKeyLen = %d\n", debugstr_a(peaAlgidInfo->szName),
802 dwKeyLen);
804 * Assume the default key length, if none is specified explicitly
806 if (dwKeyLen == 0) dwKeyLen = peaAlgidInfo->dwDefaultLen;
809 * Check if the requested key length is supported by the current CSP.
810 * Adjust key length's for DES algorithms.
812 switch (aiAlgid) {
813 case CALG_DES:
814 if (dwKeyLen == RSAENH_DES_EFFECTIVE_KEYLEN) {
815 dwKeyLen = RSAENH_DES_STORAGE_KEYLEN;
817 if (dwKeyLen != RSAENH_DES_STORAGE_KEYLEN) {
818 SetLastError(NTE_BAD_FLAGS);
819 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
821 break;
823 case CALG_3DES_112:
824 if (dwKeyLen == RSAENH_3DES112_EFFECTIVE_KEYLEN) {
825 dwKeyLen = RSAENH_3DES112_STORAGE_KEYLEN;
827 if (dwKeyLen != RSAENH_3DES112_STORAGE_KEYLEN) {
828 SetLastError(NTE_BAD_FLAGS);
829 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
831 break;
833 case CALG_3DES:
834 if (dwKeyLen == RSAENH_3DES_EFFECTIVE_KEYLEN) {
835 dwKeyLen = RSAENH_3DES_STORAGE_KEYLEN;
837 if (dwKeyLen != RSAENH_3DES_STORAGE_KEYLEN) {
838 SetLastError(NTE_BAD_FLAGS);
839 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
841 break;
843 case CALG_HMAC:
844 /* Avoid the key length check for HMAC keys, which have unlimited
845 * length.
847 break;
849 default:
850 if (dwKeyLen % 8 ||
851 dwKeyLen > peaAlgidInfo->dwMaxLen ||
852 dwKeyLen < peaAlgidInfo->dwMinLen)
854 TRACE("key len %d out of bounds (%d, %d)\n", dwKeyLen,
855 peaAlgidInfo->dwMinLen, peaAlgidInfo->dwMaxLen);
856 SetLastError(NTE_BAD_DATA);
857 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
861 hCryptKey = new_object(&handle_table, sizeof(CRYPTKEY), RSAENH_MAGIC_KEY,
862 destroy_key, (OBJECTHDR**)&pCryptKey);
863 if (hCryptKey != (HCRYPTKEY)INVALID_HANDLE_VALUE)
865 KEYCONTAINER *pKeyContainer = get_key_container(hProv);
866 pCryptKey->aiAlgid = aiAlgid;
867 pCryptKey->hProv = hProv;
868 pCryptKey->dwModeBits = 0;
869 pCryptKey->dwPermissions = CRYPT_ENCRYPT | CRYPT_DECRYPT | CRYPT_READ | CRYPT_WRITE |
870 CRYPT_MAC;
871 if (dwFlags & CRYPT_EXPORTABLE)
872 pCryptKey->dwPermissions |= CRYPT_EXPORT;
873 pCryptKey->dwKeyLen = dwKeyLen >> 3;
874 pCryptKey->dwEffectiveKeyLen = 0;
877 * For compatibility reasons a 40 bit key on the Enhanced
878 * provider will not have salt
880 if (pKeyContainer->dwPersonality == RSAENH_PERSONALITY_ENHANCED
881 && (aiAlgid == CALG_RC2 || aiAlgid == CALG_RC4)
882 && (dwFlags & CRYPT_CREATE_SALT) && dwKeyLen == 40)
883 pCryptKey->dwSaltLen = 0;
884 else if ((dwFlags & CRYPT_CREATE_SALT) || (dwKeyLen == 40 && !(dwFlags & CRYPT_NO_SALT)))
885 pCryptKey->dwSaltLen = 16 /*FIXME*/ - pCryptKey->dwKeyLen;
886 else
887 pCryptKey->dwSaltLen = 0;
888 memset(pCryptKey->abKeyValue, 0, sizeof(pCryptKey->abKeyValue));
889 memset(pCryptKey->abInitVector, 0, sizeof(pCryptKey->abInitVector));
890 memset(&pCryptKey->siSChannelInfo.saEncAlg, 0, sizeof(pCryptKey->siSChannelInfo.saEncAlg));
891 memset(&pCryptKey->siSChannelInfo.saMACAlg, 0, sizeof(pCryptKey->siSChannelInfo.saMACAlg));
892 init_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom);
893 init_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom);
894 init_data_blob(&pCryptKey->blobHmacKey);
896 switch(aiAlgid)
898 case CALG_PCT1_MASTER:
899 case CALG_SSL2_MASTER:
900 case CALG_SSL3_MASTER:
901 case CALG_TLS1_MASTER:
902 case CALG_RC4:
903 pCryptKey->dwBlockLen = 0;
904 pCryptKey->dwMode = 0;
905 break;
907 case CALG_RC2:
908 case CALG_DES:
909 case CALG_3DES_112:
910 case CALG_3DES:
911 pCryptKey->dwBlockLen = 8;
912 pCryptKey->dwMode = CRYPT_MODE_CBC;
913 break;
915 case CALG_AES_128:
916 case CALG_AES_192:
917 case CALG_AES_256:
918 pCryptKey->dwBlockLen = 16;
919 pCryptKey->dwMode = CRYPT_MODE_CBC;
920 break;
922 case CALG_RSA_KEYX:
923 case CALG_RSA_SIGN:
924 pCryptKey->dwBlockLen = dwKeyLen >> 3;
925 pCryptKey->dwMode = 0;
926 break;
928 case CALG_HMAC:
929 pCryptKey->dwBlockLen = 0;
930 pCryptKey->dwMode = 0;
931 break;
934 *ppCryptKey = pCryptKey;
937 return hCryptKey;
940 /******************************************************************************
941 * map_key_spec_to_key_pair_name [Internal]
943 * Returns the name of the registry value associated with a key spec.
945 * PARAMS
946 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
948 * RETURNS
949 * Success: Name of registry value.
950 * Failure: NULL
952 static LPCSTR map_key_spec_to_key_pair_name(DWORD dwKeySpec)
954 LPCSTR szValueName;
956 switch (dwKeySpec)
958 case AT_KEYEXCHANGE:
959 szValueName = "KeyExchangeKeyPair";
960 break;
961 case AT_SIGNATURE:
962 szValueName = "SignatureKeyPair";
963 break;
964 default:
965 WARN("invalid key spec %d\n", dwKeySpec);
966 szValueName = NULL;
968 return szValueName;
971 /******************************************************************************
972 * store_key_pair [Internal]
974 * Stores a key pair to the registry
976 * PARAMS
977 * hCryptKey [I] Handle to the key to be stored
978 * hKey [I] Registry key where the key pair is to be stored
979 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
980 * dwFlags [I] Flags for protecting the key
982 static void store_key_pair(HCRYPTKEY hCryptKey, HKEY hKey, DWORD dwKeySpec, DWORD dwFlags)
984 LPCSTR szValueName;
985 DATA_BLOB blobIn, blobOut;
986 CRYPTKEY *pKey;
987 DWORD dwLen;
988 BYTE *pbKey;
990 if (!(szValueName = map_key_spec_to_key_pair_name(dwKeySpec)))
991 return;
992 if (lookup_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY,
993 (OBJECTHDR**)&pKey))
995 if (crypt_export_key(pKey, 0, PRIVATEKEYBLOB, 0, TRUE, 0, &dwLen))
997 pbKey = HeapAlloc(GetProcessHeap(), 0, dwLen);
998 if (pbKey)
1000 if (crypt_export_key(pKey, 0, PRIVATEKEYBLOB, 0, TRUE, pbKey,
1001 &dwLen))
1003 blobIn.pbData = pbKey;
1004 blobIn.cbData = dwLen;
1006 if (CryptProtectData(&blobIn, NULL, NULL, NULL, NULL,
1007 dwFlags, &blobOut))
1009 RegSetValueExA(hKey, szValueName, 0, REG_BINARY,
1010 blobOut.pbData, blobOut.cbData);
1011 LocalFree(blobOut.pbData);
1014 HeapFree(GetProcessHeap(), 0, pbKey);
1020 /******************************************************************************
1021 * map_key_spec_to_permissions_name [Internal]
1023 * Returns the name of the registry value associated with the permissions for
1024 * a key spec.
1026 * PARAMS
1027 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
1029 * RETURNS
1030 * Success: Name of registry value.
1031 * Failure: NULL
1033 static LPCSTR map_key_spec_to_permissions_name(DWORD dwKeySpec)
1035 LPCSTR szValueName;
1037 switch (dwKeySpec)
1039 case AT_KEYEXCHANGE:
1040 szValueName = "KeyExchangePermissions";
1041 break;
1042 case AT_SIGNATURE:
1043 szValueName = "SignaturePermissions";
1044 break;
1045 default:
1046 WARN("invalid key spec %d\n", dwKeySpec);
1047 szValueName = NULL;
1049 return szValueName;
1052 /******************************************************************************
1053 * store_key_permissions [Internal]
1055 * Stores a key's permissions to the registry
1057 * PARAMS
1058 * hCryptKey [I] Handle to the key whose permissions are to be stored
1059 * hKey [I] Registry key where the key permissions are to be stored
1060 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
1062 static void store_key_permissions(HCRYPTKEY hCryptKey, HKEY hKey, DWORD dwKeySpec)
1064 LPCSTR szValueName;
1065 CRYPTKEY *pKey;
1067 if (!(szValueName = map_key_spec_to_permissions_name(dwKeySpec)))
1068 return;
1069 if (lookup_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY,
1070 (OBJECTHDR**)&pKey))
1071 RegSetValueExA(hKey, szValueName, 0, REG_DWORD,
1072 (BYTE *)&pKey->dwPermissions,
1073 sizeof(pKey->dwPermissions));
1076 /******************************************************************************
1077 * create_container_key [Internal]
1079 * Creates the registry key for a key container's persistent storage.
1081 * PARAMS
1082 * pKeyContainer [I] Pointer to the key container
1083 * sam [I] Desired registry access
1084 * phKey [O] Returned key
1086 static BOOL create_container_key(KEYCONTAINER *pKeyContainer, REGSAM sam, HKEY *phKey)
1088 CHAR szRSABase[sizeof(RSAENH_REGKEY) + MAX_PATH];
1089 HKEY hRootKey;
1091 sprintf(szRSABase, RSAENH_REGKEY, pKeyContainer->szName);
1093 if (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET)
1094 hRootKey = HKEY_LOCAL_MACHINE;
1095 else
1096 hRootKey = HKEY_CURRENT_USER;
1098 /* @@ Wine registry key: HKLM\Software\Wine\Crypto\RSA */
1099 /* @@ Wine registry key: HKCU\Software\Wine\Crypto\RSA */
1100 return RegCreateKeyExA(hRootKey, szRSABase, 0, NULL,
1101 REG_OPTION_NON_VOLATILE, sam, NULL, phKey, NULL)
1102 == ERROR_SUCCESS;
1105 /******************************************************************************
1106 * open_container_key [Internal]
1108 * Opens a key container's persistent storage for reading.
1110 * PARAMS
1111 * pszContainerName [I] Name of the container to be opened. May be the empty
1112 * string if the parent key of all containers is to be
1113 * opened.
1114 * dwFlags [I] Flags indicating which keyset to be opened.
1115 * phKey [O] Returned key
1117 static BOOL open_container_key(LPCSTR pszContainerName, DWORD dwFlags, REGSAM access, HKEY *phKey)
1119 CHAR szRSABase[sizeof(RSAENH_REGKEY) + MAX_PATH];
1120 HKEY hRootKey;
1122 sprintf(szRSABase, RSAENH_REGKEY, pszContainerName);
1124 if (dwFlags & CRYPT_MACHINE_KEYSET)
1125 hRootKey = HKEY_LOCAL_MACHINE;
1126 else
1127 hRootKey = HKEY_CURRENT_USER;
1129 /* @@ Wine registry key: HKLM\Software\Wine\Crypto\RSA */
1130 /* @@ Wine registry key: HKCU\Software\Wine\Crypto\RSA */
1131 return RegOpenKeyExA(hRootKey, szRSABase, 0, access, phKey) ==
1132 ERROR_SUCCESS;
1135 /******************************************************************************
1136 * delete_container_key [Internal]
1138 * Deletes a key container's persistent storage.
1140 * PARAMS
1141 * pszContainerName [I] Name of the container to be opened.
1142 * dwFlags [I] Flags indicating which keyset to be opened.
1144 static BOOL delete_container_key(LPCSTR pszContainerName, DWORD dwFlags)
1146 CHAR szRegKey[sizeof(RSAENH_REGKEY) + MAX_PATH];
1147 HKEY hRootKey;
1149 sprintf(szRegKey, RSAENH_REGKEY, pszContainerName);
1151 if (dwFlags & CRYPT_MACHINE_KEYSET)
1152 hRootKey = HKEY_LOCAL_MACHINE;
1153 else
1154 hRootKey = HKEY_CURRENT_USER;
1155 if (!RegDeleteKeyA(hRootKey, szRegKey)) {
1156 SetLastError(ERROR_SUCCESS);
1157 return TRUE;
1158 } else {
1159 SetLastError(NTE_BAD_KEYSET);
1160 return FALSE;
1164 /******************************************************************************
1165 * store_key_container_keys [Internal]
1167 * Stores key container's keys in a persistent location.
1169 * PARAMS
1170 * pKeyContainer [I] Pointer to the key container whose keys are to be saved
1172 static void store_key_container_keys(KEYCONTAINER *pKeyContainer)
1174 HKEY hKey;
1175 DWORD dwFlags;
1177 /* On WinXP, persistent keys are stored in a file located at:
1178 * $AppData$\\Microsoft\\Crypto\\RSA\\$SID$\\some_hex_string
1181 if (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET)
1182 dwFlags = CRYPTPROTECT_LOCAL_MACHINE;
1183 else
1184 dwFlags = 0;
1186 if (create_container_key(pKeyContainer, KEY_WRITE, &hKey))
1188 store_key_pair(pKeyContainer->hKeyExchangeKeyPair, hKey,
1189 AT_KEYEXCHANGE, dwFlags);
1190 store_key_pair(pKeyContainer->hSignatureKeyPair, hKey,
1191 AT_SIGNATURE, dwFlags);
1192 RegCloseKey(hKey);
1196 /******************************************************************************
1197 * store_key_container_permissions [Internal]
1199 * Stores key container's key permissions in a persistent location.
1201 * PARAMS
1202 * pKeyContainer [I] Pointer to the key container whose key permissions are to
1203 * be saved
1205 static void store_key_container_permissions(KEYCONTAINER *pKeyContainer)
1207 HKEY hKey;
1209 if (create_container_key(pKeyContainer, KEY_WRITE, &hKey))
1211 store_key_permissions(pKeyContainer->hKeyExchangeKeyPair, hKey,
1212 AT_KEYEXCHANGE);
1213 store_key_permissions(pKeyContainer->hSignatureKeyPair, hKey,
1214 AT_SIGNATURE);
1215 RegCloseKey(hKey);
1219 /******************************************************************************
1220 * release_key_container_keys [Internal]
1222 * Releases key container's keys.
1224 * PARAMS
1225 * pKeyContainer [I] Pointer to the key container whose keys are to be released.
1227 static void release_key_container_keys(KEYCONTAINER *pKeyContainer)
1229 release_handle(&handle_table, pKeyContainer->hKeyExchangeKeyPair,
1230 RSAENH_MAGIC_KEY);
1231 release_handle(&handle_table, pKeyContainer->hSignatureKeyPair,
1232 RSAENH_MAGIC_KEY);
1235 /******************************************************************************
1236 * destroy_key_container [Internal]
1238 * Destructor for key containers.
1240 * PARAMS
1241 * pObjectHdr [I] Pointer to the key container to be destroyed.
1243 static void destroy_key_container(OBJECTHDR *pObjectHdr)
1245 KEYCONTAINER *pKeyContainer = (KEYCONTAINER*)pObjectHdr;
1247 if (!(pKeyContainer->dwFlags & CRYPT_VERIFYCONTEXT))
1249 store_key_container_keys(pKeyContainer);
1250 store_key_container_permissions(pKeyContainer);
1251 release_key_container_keys(pKeyContainer);
1253 else
1254 release_key_container_keys(pKeyContainer);
1255 HeapFree( GetProcessHeap(), 0, pKeyContainer );
1258 /******************************************************************************
1259 * new_key_container [Internal]
1261 * Create a new key container. The personality (RSA Base, Strong or Enhanced CP)
1262 * of the CSP is determined via the pVTable->pszProvName string.
1264 * PARAMS
1265 * pszContainerName [I] Name of the key container.
1266 * pVTable [I] Callback functions and context info provided by the OS
1268 * RETURNS
1269 * Success: Handle to the new key container.
1270 * Failure: INVALID_HANDLE_VALUE
1272 static HCRYPTPROV new_key_container(PCCH pszContainerName, DWORD dwFlags, const VTableProvStruc *pVTable)
1274 KEYCONTAINER *pKeyContainer;
1275 HCRYPTPROV hKeyContainer;
1277 hKeyContainer = new_object(&handle_table, sizeof(KEYCONTAINER), RSAENH_MAGIC_CONTAINER,
1278 destroy_key_container, (OBJECTHDR**)&pKeyContainer);
1279 if (hKeyContainer != (HCRYPTPROV)INVALID_HANDLE_VALUE)
1281 lstrcpynA(pKeyContainer->szName, pszContainerName, MAX_PATH);
1282 pKeyContainer->dwFlags = dwFlags;
1283 pKeyContainer->dwEnumAlgsCtr = 0;
1284 pKeyContainer->hKeyExchangeKeyPair = (HCRYPTKEY)INVALID_HANDLE_VALUE;
1285 pKeyContainer->hSignatureKeyPair = (HCRYPTKEY)INVALID_HANDLE_VALUE;
1286 if (pVTable && pVTable->pszProvName) {
1287 lstrcpynA(pKeyContainer->szProvName, pVTable->pszProvName, MAX_PATH);
1288 if (!strcmp(pVTable->pszProvName, MS_DEF_PROV_A)) {
1289 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_BASE;
1290 } else if (!strcmp(pVTable->pszProvName, MS_ENHANCED_PROV_A)) {
1291 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_ENHANCED;
1292 } else if (!strcmp(pVTable->pszProvName, MS_DEF_RSA_SCHANNEL_PROV_A)) {
1293 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_SCHANNEL;
1294 } else if (!strcmp(pVTable->pszProvName, MS_ENH_RSA_AES_PROV_A) ||
1295 !strcmp(pVTable->pszProvName, MS_ENH_RSA_AES_PROV_XP_A)) {
1296 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_AES;
1297 } else {
1298 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_STRONG;
1302 /* The new key container has to be inserted into the CSP immediately
1303 * after creation to be available for CPGetProvParam's PP_ENUMCONTAINERS. */
1304 if (!(dwFlags & CRYPT_VERIFYCONTEXT)) {
1305 HKEY hKey;
1307 if (create_container_key(pKeyContainer, KEY_WRITE, &hKey))
1308 RegCloseKey(hKey);
1312 return hKeyContainer;
1315 /******************************************************************************
1316 * read_key_value [Internal]
1318 * Reads a key pair value from the registry
1320 * PARAMS
1321 * hKeyContainer [I] Crypt provider to use to import the key
1322 * hKey [I] Registry key from which to read the key pair
1323 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
1324 * dwFlags [I] Flags for unprotecting the key
1325 * phCryptKey [O] Returned key
1327 static BOOL read_key_value(HCRYPTPROV hKeyContainer, HKEY hKey, DWORD dwKeySpec, DWORD dwFlags, HCRYPTKEY *phCryptKey)
1329 LPCSTR szValueName;
1330 DWORD dwValueType, dwLen;
1331 BYTE *pbKey;
1332 DATA_BLOB blobIn, blobOut;
1333 BOOL ret = FALSE;
1335 if (!(szValueName = map_key_spec_to_key_pair_name(dwKeySpec)))
1336 return FALSE;
1337 if (RegQueryValueExA(hKey, szValueName, 0, &dwValueType, NULL, &dwLen) ==
1338 ERROR_SUCCESS)
1340 pbKey = HeapAlloc(GetProcessHeap(), 0, dwLen);
1341 if (pbKey)
1343 if (RegQueryValueExA(hKey, szValueName, 0, &dwValueType, pbKey, &dwLen) ==
1344 ERROR_SUCCESS)
1346 blobIn.pbData = pbKey;
1347 blobIn.cbData = dwLen;
1349 if (CryptUnprotectData(&blobIn, NULL, NULL, NULL, NULL,
1350 dwFlags, &blobOut))
1352 ret = import_key(hKeyContainer, blobOut.pbData, blobOut.cbData, 0, 0,
1353 FALSE, phCryptKey);
1354 LocalFree(blobOut.pbData);
1357 HeapFree(GetProcessHeap(), 0, pbKey);
1360 if (ret)
1362 CRYPTKEY *pKey;
1364 if (lookup_handle(&handle_table, *phCryptKey, RSAENH_MAGIC_KEY,
1365 (OBJECTHDR**)&pKey))
1367 if ((szValueName = map_key_spec_to_permissions_name(dwKeySpec)))
1369 dwLen = sizeof(pKey->dwPermissions);
1370 RegQueryValueExA(hKey, szValueName, 0, NULL,
1371 (BYTE *)&pKey->dwPermissions, &dwLen);
1375 return ret;
1378 /******************************************************************************
1379 * read_key_container [Internal]
1381 * Tries to read the persistent state of the key container (mainly the signature
1382 * and key exchange private keys) given by pszContainerName.
1384 * PARAMS
1385 * pszContainerName [I] Name of the key container to read from the registry
1386 * pVTable [I] Pointer to context data provided by the operating system
1388 * RETURNS
1389 * Success: Handle to the key container read from the registry
1390 * Failure: INVALID_HANDLE_VALUE
1392 static HCRYPTPROV read_key_container(PCHAR pszContainerName, DWORD dwFlags, const VTableProvStruc *pVTable)
1394 HKEY hKey;
1395 KEYCONTAINER *pKeyContainer;
1396 HCRYPTPROV hKeyContainer;
1397 HCRYPTKEY hCryptKey;
1399 if (!open_container_key(pszContainerName, dwFlags, KEY_READ, &hKey))
1401 SetLastError(NTE_BAD_KEYSET);
1402 return (HCRYPTPROV)INVALID_HANDLE_VALUE;
1405 hKeyContainer = new_key_container(pszContainerName, dwFlags, pVTable);
1406 if (hKeyContainer != (HCRYPTPROV)INVALID_HANDLE_VALUE)
1408 DWORD dwProtectFlags = (dwFlags & CRYPT_MACHINE_KEYSET) ?
1409 CRYPTPROTECT_LOCAL_MACHINE : 0;
1411 if (!lookup_handle(&handle_table, hKeyContainer, RSAENH_MAGIC_CONTAINER,
1412 (OBJECTHDR**)&pKeyContainer))
1413 return (HCRYPTPROV)INVALID_HANDLE_VALUE;
1415 /* read_key_value calls import_key, which calls import_private_key,
1416 * which implicitly installs the key value into the appropriate key
1417 * container key. Thus the ref count is incremented twice, once for
1418 * the output key value, and once for the implicit install, and needs
1419 * to be decremented to balance the two.
1421 if (read_key_value(hKeyContainer, hKey, AT_KEYEXCHANGE,
1422 dwProtectFlags, &hCryptKey))
1423 release_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY);
1424 if (read_key_value(hKeyContainer, hKey, AT_SIGNATURE,
1425 dwProtectFlags, &hCryptKey))
1426 release_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY);
1429 return hKeyContainer;
1432 /******************************************************************************
1433 * build_hash_signature [Internal]
1435 * Builds a padded version of a hash to match the length of the RSA key modulus.
1437 * PARAMS
1438 * pbSignature [O] The padded hash object is stored here.
1439 * dwLen [I] Length of the pbSignature buffer.
1440 * aiAlgid [I] Algorithm identifier of the hash to be padded.
1441 * abHashValue [I] The value of the hash object.
1442 * dwHashLen [I] Length of the hash value.
1443 * dwFlags [I] Selection of padding algorithm.
1445 * RETURNS
1446 * Success: TRUE
1447 * Failure: FALSE (NTE_BAD_ALGID)
1449 static BOOL build_hash_signature(BYTE *pbSignature, DWORD dwLen, ALG_ID aiAlgid,
1450 const BYTE *abHashValue, DWORD dwHashLen, DWORD dwFlags)
1452 /* These prefixes are meant to be concatenated with hash values of the
1453 * respective kind to form a PKCS #7 DigestInfo. */
1454 static const struct tagOIDDescriptor {
1455 ALG_ID aiAlgid;
1456 DWORD dwLen;
1457 const BYTE abOID[19];
1458 } aOIDDescriptor[] = {
1459 { CALG_MD2, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48,
1460 0x86, 0xf7, 0x0d, 0x02, 0x02, 0x05, 0x00, 0x04, 0x10 } },
1461 { CALG_MD4, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48,
1462 0x86, 0xf7, 0x0d, 0x02, 0x04, 0x05, 0x00, 0x04, 0x10 } },
1463 { CALG_MD5, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48,
1464 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10 } },
1465 { CALG_SHA, 15, { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
1466 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 } },
1467 { CALG_SHA_256, 19, { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
1468 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01,
1469 0x05, 0x00, 0x04, 0x20 } },
1470 { CALG_SHA_384, 19, { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
1471 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02,
1472 0x05, 0x00, 0x04, 0x30 } },
1473 { CALG_SHA_512, 19, { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
1474 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03,
1475 0x05, 0x00, 0x04, 0x40 } },
1476 { CALG_SSL3_SHAMD5, 0, { 0 } },
1477 { 0, 0, { 0 } }
1479 DWORD dwIdxOID, i, j;
1481 for (dwIdxOID = 0; aOIDDescriptor[dwIdxOID].aiAlgid; dwIdxOID++) {
1482 if (aOIDDescriptor[dwIdxOID].aiAlgid == aiAlgid) break;
1485 if (!aOIDDescriptor[dwIdxOID].aiAlgid) {
1486 SetLastError(NTE_BAD_ALGID);
1487 return FALSE;
1490 /* Build the padded signature */
1491 if (dwFlags & CRYPT_X931_FORMAT) {
1492 pbSignature[0] = 0x6b;
1493 for (i=1; i < dwLen - dwHashLen - 3; i++) {
1494 pbSignature[i] = 0xbb;
1496 pbSignature[i++] = 0xba;
1497 for (j=0; j < dwHashLen; j++, i++) {
1498 pbSignature[i] = abHashValue[j];
1500 pbSignature[i++] = 0x33;
1501 pbSignature[i++] = 0xcc;
1502 } else {
1503 pbSignature[0] = 0x00;
1504 pbSignature[1] = 0x01;
1505 if (dwFlags & CRYPT_NOHASHOID) {
1506 for (i=2; i < dwLen - 1 - dwHashLen; i++) {
1507 pbSignature[i] = 0xff;
1509 pbSignature[i++] = 0x00;
1510 } else {
1511 for (i=2; i < dwLen - 1 - aOIDDescriptor[dwIdxOID].dwLen - dwHashLen; i++) {
1512 pbSignature[i] = 0xff;
1514 pbSignature[i++] = 0x00;
1515 for (j=0; j < aOIDDescriptor[dwIdxOID].dwLen; j++) {
1516 pbSignature[i++] = aOIDDescriptor[dwIdxOID].abOID[j];
1519 for (j=0; j < dwHashLen; j++) {
1520 pbSignature[i++] = abHashValue[j];
1524 return TRUE;
1527 /******************************************************************************
1528 * tls1_p [Internal]
1530 * This is an implementation of the 'P_hash' helper function for TLS1's PRF.
1531 * It is used exclusively by tls1_prf. For details see RFC 2246, chapter 5.
1532 * The pseudo random stream generated by this function is exclusive or'ed with
1533 * the data in pbBuffer.
1535 * PARAMS
1536 * hHMAC [I] HMAC object, which will be used in pseudo random generation
1537 * pblobSeed [I] Seed value
1538 * pbBuffer [I/O] Pseudo random stream will be xor'ed to the provided data
1539 * dwBufferLen [I] Number of pseudo random bytes desired
1541 * RETURNS
1542 * Success: TRUE
1543 * Failure: FALSE
1545 static BOOL tls1_p(HCRYPTHASH hHMAC, const PCRYPT_DATA_BLOB pblobSeed, BYTE *pbBuffer,
1546 DWORD dwBufferLen)
1548 CRYPTHASH *pHMAC;
1549 BYTE abAi[RSAENH_MAX_HASH_SIZE];
1550 DWORD i = 0;
1552 if (!lookup_handle(&handle_table, hHMAC, RSAENH_MAGIC_HASH, (OBJECTHDR**)&pHMAC)) {
1553 SetLastError(NTE_BAD_HASH);
1554 return FALSE;
1557 /* compute A_1 = HMAC(seed) */
1558 init_hash(pHMAC);
1559 update_hash(pHMAC, pblobSeed->pbData, pblobSeed->cbData);
1560 finalize_hash(pHMAC);
1561 memcpy(abAi, pHMAC->abHashValue, pHMAC->dwHashSize);
1563 do {
1564 /* compute HMAC(A_i + seed) */
1565 init_hash(pHMAC);
1566 update_hash(pHMAC, abAi, pHMAC->dwHashSize);
1567 update_hash(pHMAC, pblobSeed->pbData, pblobSeed->cbData);
1568 finalize_hash(pHMAC);
1570 /* pseudo random stream := CONCAT_{i=1..n} ( HMAC(A_i + seed) ) */
1571 do {
1572 if (i >= dwBufferLen) break;
1573 pbBuffer[i] ^= pHMAC->abHashValue[i % pHMAC->dwHashSize];
1574 i++;
1575 } while (i % pHMAC->dwHashSize);
1577 /* compute A_{i+1} = HMAC(A_i) */
1578 init_hash(pHMAC);
1579 update_hash(pHMAC, abAi, pHMAC->dwHashSize);
1580 finalize_hash(pHMAC);
1581 memcpy(abAi, pHMAC->abHashValue, pHMAC->dwHashSize);
1582 } while (i < dwBufferLen);
1584 return TRUE;
1587 /******************************************************************************
1588 * tls1_prf [Internal]
1590 * TLS1 pseudo random function as specified in RFC 2246, chapter 5
1592 * PARAMS
1593 * hProv [I] Key container used to compute the pseudo random stream
1594 * hSecret [I] Key that holds the (pre-)master secret
1595 * pblobLabel [I] Descriptive label
1596 * pblobSeed [I] Seed value
1597 * pbBuffer [O] Pseudo random numbers will be stored here
1598 * dwBufferLen [I] Number of pseudo random bytes desired
1600 * RETURNS
1601 * Success: TRUE
1602 * Failure: FALSE
1604 static BOOL tls1_prf(HCRYPTPROV hProv, HCRYPTPROV hSecret, const PCRYPT_DATA_BLOB pblobLabel,
1605 const PCRYPT_DATA_BLOB pblobSeed, BYTE *pbBuffer, DWORD dwBufferLen)
1607 HMAC_INFO hmacInfo = { 0, NULL, 0, NULL, 0 };
1608 HCRYPTHASH hHMAC = (HCRYPTHASH)INVALID_HANDLE_VALUE;
1609 HCRYPTKEY hHalfSecret = (HCRYPTKEY)INVALID_HANDLE_VALUE;
1610 CRYPTKEY *pHalfSecret, *pSecret;
1611 DWORD dwHalfSecretLen;
1612 BOOL result = FALSE;
1613 CRYPT_DATA_BLOB blobLabelSeed;
1615 TRACE("(hProv=%08lx, hSecret=%08lx, pblobLabel=%p, pblobSeed=%p, pbBuffer=%p, dwBufferLen=%d)\n",
1616 hProv, hSecret, pblobLabel, pblobSeed, pbBuffer, dwBufferLen);
1618 if (!lookup_handle(&handle_table, hSecret, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pSecret)) {
1619 SetLastError(NTE_FAIL);
1620 return FALSE;
1623 dwHalfSecretLen = (pSecret->dwKeyLen+1)/2;
1625 /* concatenation of the label and the seed */
1626 if (!concat_data_blobs(&blobLabelSeed, pblobLabel, pblobSeed)) goto exit;
1628 /* zero out the buffer, since two random streams will be xor'ed into it. */
1629 memset(pbBuffer, 0, dwBufferLen);
1631 /* build a 'fake' key, to hold the secret. CALG_SSL2_MASTER is used since it provides
1632 * the biggest range of valid key lengths. */
1633 hHalfSecret = new_key(hProv, CALG_SSL2_MASTER, MAKELONG(0,dwHalfSecretLen*8), &pHalfSecret);
1634 if (hHalfSecret == (HCRYPTKEY)INVALID_HANDLE_VALUE) goto exit;
1636 /* Derive an HMAC_MD5 hash and call the helper function. */
1637 memcpy(pHalfSecret->abKeyValue, pSecret->abKeyValue, dwHalfSecretLen);
1638 if (!RSAENH_CPCreateHash(hProv, CALG_HMAC, hHalfSecret, 0, &hHMAC)) goto exit;
1639 hmacInfo.HashAlgid = CALG_MD5;
1640 if (!RSAENH_CPSetHashParam(hProv, hHMAC, HP_HMAC_INFO, (BYTE*)&hmacInfo, 0)) goto exit;
1641 if (!tls1_p(hHMAC, &blobLabelSeed, pbBuffer, dwBufferLen)) goto exit;
1643 /* Reconfigure to HMAC_SHA hash and call helper function again. */
1644 memcpy(pHalfSecret->abKeyValue, pSecret->abKeyValue + (pSecret->dwKeyLen/2), dwHalfSecretLen);
1645 hmacInfo.HashAlgid = CALG_SHA;
1646 if (!RSAENH_CPSetHashParam(hProv, hHMAC, HP_HMAC_INFO, (BYTE*)&hmacInfo, 0)) goto exit;
1647 if (!tls1_p(hHMAC, &blobLabelSeed, pbBuffer, dwBufferLen)) goto exit;
1649 result = TRUE;
1650 exit:
1651 release_handle(&handle_table, hHalfSecret, RSAENH_MAGIC_KEY);
1652 if (hHMAC != (HCRYPTHASH)INVALID_HANDLE_VALUE) RSAENH_CPDestroyHash(hProv, hHMAC);
1653 free_data_blob(&blobLabelSeed);
1654 return result;
1657 /******************************************************************************
1658 * pad_data_pkcs1 [Internal]
1660 * Helper function for data padding according to PKCS1 #2
1662 * PARAMS
1663 * abData [I] The data to be padded
1664 * dwDataLen [I] Length of the data
1665 * abBuffer [O] Padded data will be stored here
1666 * dwBufferLen [I] Length of the buffer (also length of padded data)
1667 * dwFlags [I] Padding format (CRYPT_SSL2_FALLBACK)
1669 * RETURN
1670 * Success: TRUE
1671 * Failure: FALSE (NTE_BAD_LEN, too much data to pad)
1673 static BOOL pad_data_pkcs1(const BYTE *abData, DWORD dwDataLen, BYTE *abBuffer, DWORD dwBufferLen, DWORD dwFlags)
1675 DWORD i;
1677 /* Ensure there is enough space for PKCS1 #2 padding */
1678 if (dwDataLen > dwBufferLen-11) {
1679 SetLastError(NTE_BAD_LEN);
1680 return FALSE;
1683 memmove(abBuffer + dwBufferLen - dwDataLen, abData, dwDataLen);
1685 abBuffer[0] = 0x00;
1686 abBuffer[1] = RSAENH_PKC_BLOCKTYPE;
1687 for (i=2; i < dwBufferLen - dwDataLen - 1; i++)
1688 do gen_rand_impl(&abBuffer[i], 1); while (!abBuffer[i]);
1689 if (dwFlags & CRYPT_SSL2_FALLBACK)
1690 for (i-=8; i < dwBufferLen - dwDataLen - 1; i++)
1691 abBuffer[i] = 0x03;
1692 abBuffer[i] = 0x00;
1694 return TRUE;
1697 /******************************************************************************
1698 * pkcs1_mgf1 [Internal]
1700 * MGF function for RSA EM-OAEP as specified in RFC 8017 PKCS #1 V2.2, Appendix B.2.1. MGF1
1702 * PARAMS
1703 * hProv [I] Cryptographic provider handle
1704 * pbSeed [I] Seed from which mask is generated
1705 * dwSeedLength [I] Length of pbSeed
1706 * dwLength [I] Intended length in octets of the mask
1707 * pbMask [O] Generated mask if success. Caller is responsible for freeing the mask when it's done
1709 * RETURNS
1710 * Success: TRUE
1711 * Failure: FALSE
1713 static BOOL pkcs1_mgf1(HCRYPTPROV hProv, const BYTE *pbSeed, DWORD dwSeedLength, DWORD dwLength, PCRYPT_DATA_BLOB pbMask)
1715 HCRYPTHASH hHash;
1716 BYTE *pbHashInput, *pbCounter;
1717 DWORD dwCounter;
1718 DWORD dwLen, dwHashLen;
1720 RSAENH_CPCreateHash(hProv, CALG_SHA1, 0, 0, &hHash);
1721 RSAENH_CPHashData(hProv, hHash, 0, 0, 0);
1722 dwLen = sizeof(dwHashLen);
1723 RSAENH_CPGetHashParam(hProv, hHash, HP_HASHSIZE, (BYTE *)&dwHashLen, &dwLen, 0);
1724 RSAENH_CPDestroyHash(hProv, hHash);
1726 /* Allocate multiples of hash value */
1727 pbMask->pbData = HeapAlloc(GetProcessHeap(), 0, (dwLength + dwHashLen - 1) / dwHashLen * dwHashLen);
1728 if (!pbMask->pbData)
1730 SetLastError(NTE_NO_MEMORY);
1731 return FALSE;
1733 pbMask->cbData = dwLength;
1735 pbHashInput = HeapAlloc(GetProcessHeap(), 0, dwSeedLength + sizeof(DWORD));
1736 if (!pbHashInput)
1738 free_data_blob(pbMask);
1739 SetLastError(NTE_NO_MEMORY);
1740 return FALSE;
1743 dwLen = dwHashLen;
1744 memcpy(pbHashInput, pbSeed, dwSeedLength);
1745 pbCounter = pbHashInput + dwSeedLength;
1746 for (dwCounter = 0; dwCounter < (dwLength + dwHashLen - 1) / dwHashLen; dwCounter++)
1748 *(pbCounter) = (BYTE)((dwCounter >> 24) & 0xff);
1749 *(pbCounter + 1) = (BYTE)((dwCounter >> 16) & 0xff);
1750 *(pbCounter + 2) = (BYTE)((dwCounter >> 8) & 0xff);
1751 *(pbCounter + 3) = (BYTE)(dwCounter & 0xff);
1752 RSAENH_CPCreateHash(hProv, CALG_SHA1, 0, 0, &hHash);
1753 RSAENH_CPHashData(hProv, hHash, pbHashInput, dwSeedLength + sizeof(DWORD), 0);
1754 /* pbMask->pbData = old pbMask->pbData || Hash(Seed || Counter) */
1755 RSAENH_CPGetHashParam(hProv, hHash, HP_HASHVAL, pbMask->pbData + dwCounter * dwHashLen, &dwLen, 0);
1756 RSAENH_CPDestroyHash(hProv, hHash);
1759 HeapFree(GetProcessHeap(), 0, pbHashInput);
1760 return TRUE;
1763 /******************************************************************************
1764 * pad_data_oaep [Internal]
1766 * Helper function for data OAEP padding scheme according to RFC 8017 PKCS #1 V2.2
1768 * PARAMS
1769 * hProv [I] Cryptographic provider handle
1770 * abData [I] The data to be padded
1771 * dwDataLen [I] Length of the data
1772 * abBuffer [O] Padded data will be stored here
1773 * dwBufferLen [I] Length of the buffer (also length of padded data)
1774 * dwFlags [I] Currently only CRYPT_OAEP is defined
1776 * RETURN
1777 * Success: TRUE
1778 * Failure: FALSE
1780 static BOOL pad_data_oaep(HCRYPTPROV hProv, const BYTE *abData, DWORD dwDataLen, BYTE *abBuffer, DWORD dwBufferLen,
1781 DWORD dwFlags)
1783 CRYPT_DATA_BLOB blobDbMask = {0}, blobSeedMask = {0};
1784 HCRYPTHASH hHash;
1785 BYTE *pbPadded = NULL, *pbDb, *pbSeed;
1786 DWORD dwLen, dwHashLen;
1787 DWORD dwDbLen, dwSeedLen;
1788 BOOL result, ret = FALSE;
1789 DWORD i;
1791 RSAENH_CPCreateHash(hProv, CALG_SHA1, 0, 0, &hHash);
1792 /* Empty label */
1793 RSAENH_CPHashData(hProv, hHash, 0, 0, 0);
1794 dwLen = sizeof(dwHashLen);
1795 RSAENH_CPGetHashParam(hProv, hHash, HP_HASHSIZE, (BYTE *)&dwHashLen, &dwLen, 0);
1797 if (dwDataLen > dwBufferLen - 2 * dwHashLen - 2)
1799 SetLastError(NTE_BAD_LEN);
1800 goto done;
1803 if (dwBufferLen < 2 * dwHashLen + 2)
1805 SetLastError(ERROR_MORE_DATA);
1806 goto done;
1809 pbPadded = HeapAlloc(GetProcessHeap(), 0, dwBufferLen);
1810 if (!pbPadded)
1812 SetLastError(NTE_NO_MEMORY);
1813 goto done;
1816 /* EM = 00 || maskedSeed || maskedDB */
1817 pbPadded[0] = 0;
1818 pbSeed = pbPadded + 1;
1819 dwSeedLen = dwHashLen;
1820 pbDb = pbPadded + 1 + dwHashLen;
1821 dwDbLen = dwBufferLen - dwSeedLen - 1;
1823 /* DB = pHash || PS || 01 || M */
1824 /* Set pHash in DB */
1825 dwLen = dwHashLen;
1826 RSAENH_CPGetHashParam(hProv, hHash, HP_HASHVAL, pbDb, &dwLen, 0);
1827 /* Set PS(zeros) in DB */
1828 memset(pbDb + dwHashLen, 0, dwDbLen - dwHashLen - 1 - dwDataLen);
1829 /* Set 01 in DB */
1830 pbDb[dwDbLen - dwDataLen - 1] = 1;
1831 /* Set M in DB */
1832 memcpy(pbDb + dwDbLen - dwDataLen, abData, dwDataLen);
1834 /* Get seed */
1835 gen_rand_impl(pbSeed, dwHashLen);
1836 /* Get masked DB */
1837 result = pkcs1_mgf1(hProv, pbSeed, dwHashLen, dwDbLen, &blobDbMask);
1838 if (!result) goto done;
1839 for (i = 0; i < dwDbLen; i++) pbDb[i] ^= blobDbMask.pbData[i];
1841 /* Get masked seed */
1842 result = pkcs1_mgf1(hProv, pbDb, dwDbLen, dwHashLen, &blobSeedMask);
1843 if (!result) goto done;
1844 for (i = 0; i < dwHashLen; i++) pbSeed[i] ^= blobSeedMask.pbData[i];
1846 memcpy(abBuffer, pbPadded, dwBufferLen);
1847 ret = TRUE;
1848 done:
1849 RSAENH_CPDestroyHash(hProv, hHash);
1850 HeapFree(GetProcessHeap(), 0, pbPadded);
1851 free_data_blob(&blobDbMask);
1852 free_data_blob(&blobSeedMask);
1853 return ret;
1856 /******************************************************************************
1857 * pad_data [Internal]
1859 * Helper function for data padding according to padding format
1861 * PARAMS
1862 * hProv [I] Cryptographic provider handle
1863 * abData [I] The data to be padded
1864 * dwDataLen [I] Length of the data
1865 * abBuffer [O] Padded data will be stored here
1866 * dwBufferLen [I] Length of the buffer (also length of padded data)
1867 * dwFlags [I] 0, CRYPT_SSL2_FALLBACK or CRYPT_OAEP
1869 * RETURN
1870 * Success: TRUE
1871 * Failure: FALSE
1873 static BOOL pad_data(HCRYPTPROV hProv, const BYTE *abData, DWORD dwDataLen, BYTE *abBuffer, DWORD dwBufferLen,
1874 DWORD dwFlags)
1876 if (dwFlags == CRYPT_OAEP)
1877 return pad_data_oaep(hProv, abData, dwDataLen, abBuffer, dwBufferLen, dwFlags);
1878 else
1879 return pad_data_pkcs1(abData, dwDataLen, abBuffer, dwBufferLen, dwFlags);
1882 /******************************************************************************
1883 * unpad_data_pkcs1 [Internal]
1885 * Remove the PKCS1 padding from RSA decrypted data
1887 * PARAMS
1888 * abData [I] The padded data
1889 * dwDataLen [I] Length of the padded data
1890 * abBuffer [O] Data without padding will be stored here
1891 * dwBufferLen [I/O] I: Length of the buffer, O: Length of unpadded data
1892 * dwFlags [I] Currently none defined
1894 * RETURNS
1895 * Success: TRUE
1896 * Failure: FALSE, (NTE_BAD_DATA, no valid PKCS1 padding or buffer too small)
1898 static BOOL unpad_data_pkcs1(const BYTE *abData, DWORD dwDataLen, BYTE *abBuffer, DWORD *dwBufferLen, DWORD dwFlags)
1900 DWORD i;
1902 if (dwDataLen < 3)
1904 SetLastError(NTE_BAD_DATA);
1905 return FALSE;
1907 for (i=2; i<dwDataLen; i++)
1908 if (!abData[i])
1909 break;
1911 if ((i == dwDataLen) || (*dwBufferLen < dwDataLen - i - 1) ||
1912 (abData[0] != 0x00) || (abData[1] != RSAENH_PKC_BLOCKTYPE))
1914 SetLastError(NTE_BAD_DATA);
1915 return FALSE;
1918 *dwBufferLen = dwDataLen - i - 1;
1919 memmove(abBuffer, abData + i + 1, *dwBufferLen);
1920 return TRUE;
1923 /******************************************************************************
1924 * unpad_data_oaep [Internal]
1926 * Remove the OAEP padding from RSA decrypted data
1928 * PARAMS
1929 * hProv [I] Cryptographic provider handle
1930 * abData [I] The padded data
1931 * dwDataLen [I] Length of the padded data
1932 * abBuffer [O] Data without padding will be stored here
1933 * dwBufferLen [I/O] I: Length of the buffer, O: Length of unpadded data
1934 * dwFlags [I] Currently only CRYPT_OAEP is defined
1936 * RETURNS
1937 * Success: TRUE
1938 * Failure: FALSE
1940 static BOOL unpad_data_oaep(HCRYPTPROV hProv, const BYTE *abData, DWORD dwDataLen, BYTE *abBuffer, DWORD *dwBufferLen,
1941 DWORD dwFlags)
1943 CRYPT_DATA_BLOB blobDbMask = {0}, blobSeedMask = {0};
1944 HCRYPTHASH hHash;
1945 BYTE *pbBuffer = NULL, *pbHashValue = NULL;
1946 const BYTE *pbPaddedSeed, *pbPaddedDb;
1947 BYTE *pbUnpaddedSeed, *pbUnpaddedDb;
1948 DWORD dwLen, dwHashLen;
1949 DWORD dwSeedLen, dwDbLen;
1950 DWORD dwZeroCount, dwMsgCount;
1951 BOOL result, ret = FALSE;
1952 DWORD i;
1954 RSAENH_CPCreateHash(hProv, CALG_SHA1, 0, 0, &hHash);
1955 RSAENH_CPHashData(hProv, hHash, 0, 0, 0);
1956 dwLen = sizeof(dwHashLen);
1957 RSAENH_CPGetHashParam(hProv, hHash, HP_HASHSIZE, (BYTE *)&dwHashLen, &dwLen, 0);
1958 if (dwDataLen < 2 * dwHashLen + 2)
1960 SetLastError(NTE_BAD_DATA);
1961 goto done;
1964 /* Get default hash value */
1965 pbHashValue = HeapAlloc(GetProcessHeap(), 0, dwHashLen);
1966 if (!pbHashValue)
1968 SetLastError(NTE_NO_MEMORY);
1969 goto done;
1971 dwLen = dwHashLen;
1972 RSAENH_CPGetHashParam(hProv, hHash, HP_HASHVAL, pbHashValue, &dwLen, 0);
1974 /* Store seed and DB */
1975 pbBuffer = HeapAlloc(GetProcessHeap(), 0, dwDataLen - 1);
1976 if (!pbBuffer)
1978 SetLastError(NTE_NO_MEMORY);
1979 goto done;
1982 pbPaddedSeed = abData + 1;
1983 pbPaddedDb = abData + 1 + dwHashLen;
1984 pbUnpaddedSeed = pbBuffer;
1985 pbUnpaddedDb = pbBuffer + dwHashLen;
1986 dwSeedLen = dwHashLen;
1987 dwDbLen = dwDataLen - dwHashLen - 1;
1989 /* Get unpadded seed */
1990 result = pkcs1_mgf1(hProv, pbPaddedDb, dwDbLen, dwSeedLen, &blobSeedMask);
1991 if (!result) goto done;
1992 for (i = 0; i < dwSeedLen; i++) pbUnpaddedSeed[i] = pbPaddedSeed[i] ^ blobSeedMask.pbData[i];
1994 /* Get unpadded DB */
1995 result = pkcs1_mgf1(hProv, pbUnpaddedSeed, dwSeedLen, dwDbLen, &blobDbMask);
1996 if (!result) goto done;
1997 for (i = 0; i < dwDbLen; i++) pbUnpaddedDb[i] = pbPaddedDb[i] ^ blobDbMask.pbData[i];
1999 /* Compare hash in DB */
2000 result = memcmp(pbUnpaddedDb, pbHashValue, dwHashLen);
2002 /* Get count of zero paddings(PS) */
2003 dwZeroCount = 0;
2004 while (dwHashLen + dwZeroCount + 1 <= dwDbLen && pbUnpaddedDb[dwHashLen + dwZeroCount] == 0) dwZeroCount++;
2005 dwMsgCount = dwDbLen - dwHashLen - dwZeroCount - 1;
2007 if (dwHashLen + dwZeroCount + 1 > dwDbLen || abData[0] || result || pbUnpaddedDb[dwHashLen + dwZeroCount] != 1
2008 || *dwBufferLen < dwMsgCount)
2010 SetLastError(NTE_BAD_DATA);
2011 goto done;
2014 *dwBufferLen = dwMsgCount;
2015 memcpy(abBuffer, pbUnpaddedDb + dwHashLen + dwZeroCount + 1, dwMsgCount);
2016 ret = TRUE;
2017 done:
2018 RSAENH_CPDestroyHash(hProv, hHash);
2019 HeapFree(GetProcessHeap(), 0, pbHashValue);
2020 HeapFree(GetProcessHeap(), 0, pbBuffer);
2021 free_data_blob(&blobDbMask);
2022 free_data_blob(&blobSeedMask);
2023 return ret;
2026 /******************************************************************************
2027 * unpad_data [Internal]
2029 * Remove the padding from RSA decrypted data according to padding format
2031 * PARAMS
2032 * hProv [I] Cryptographic provider handle
2033 * abData [I] The padded data
2034 * dwDataLen [I] Length of the padded data
2035 * abBuffer [O] Data without padding will be stored here
2036 * dwBufferLen [I/O] I: Length of the buffer, O: Length of unpadded data
2037 * dwFlags [I] 0 or CRYPT_OAEP
2039 * RETURNS
2040 * Success: TRUE
2041 * Failure: FALSE
2043 static BOOL unpad_data(HCRYPTPROV hProv, const BYTE *abData, DWORD dwDataLen, BYTE *abBuffer, DWORD *dwBufferLen,
2044 DWORD dwFlags)
2046 if (dwFlags == CRYPT_OAEP)
2047 return unpad_data_oaep(hProv, abData, dwDataLen, abBuffer, dwBufferLen, dwFlags);
2048 else
2049 return unpad_data_pkcs1(abData, dwDataLen, abBuffer, dwBufferLen, dwFlags);
2052 /******************************************************************************
2053 * CPAcquireContext (RSAENH.@)
2055 * Acquire a handle to the key container specified by pszContainer
2057 * PARAMS
2058 * phProv [O] Pointer to the location the acquired handle will be written to.
2059 * pszContainer [I] Name of the desired key container. See Notes
2060 * dwFlags [I] Flags. See Notes.
2061 * pVTable [I] Pointer to a PVTableProvStruct containing callbacks.
2063 * RETURNS
2064 * Success: TRUE
2065 * Failure: FALSE
2067 * NOTES
2068 * If pszContainer is NULL or points to a zero length string the user's login
2069 * name will be used as the key container name.
2071 * If the CRYPT_NEW_KEYSET flag is set in dwFlags a new keyset will be created.
2072 * If a keyset with the given name already exists, the function fails and sets
2073 * last error to NTE_EXISTS. If CRYPT_NEW_KEYSET is not set and the specified
2074 * key container does not exist, function fails and sets last error to
2075 * NTE_BAD_KEYSET.
2077 BOOL WINAPI RSAENH_CPAcquireContext(HCRYPTPROV *phProv, LPSTR pszContainer,
2078 DWORD dwFlags, PVTableProvStruc pVTable)
2080 CHAR szKeyContainerName[MAX_PATH];
2082 TRACE("(phProv=%p, pszContainer=%s, dwFlags=%08x, pVTable=%p)\n", phProv,
2083 debugstr_a(pszContainer), dwFlags, pVTable);
2085 if (pszContainer && *pszContainer)
2087 lstrcpynA(szKeyContainerName, pszContainer, MAX_PATH);
2089 else
2091 DWORD dwLen = sizeof(szKeyContainerName);
2092 if (!GetUserNameA(szKeyContainerName, &dwLen)) return FALSE;
2095 switch (dwFlags & (CRYPT_NEWKEYSET|CRYPT_VERIFYCONTEXT|CRYPT_DELETEKEYSET))
2097 case 0:
2098 *phProv = read_key_container(szKeyContainerName, dwFlags, pVTable);
2099 break;
2101 case CRYPT_DELETEKEYSET:
2102 return delete_container_key(szKeyContainerName, dwFlags);
2104 case CRYPT_NEWKEYSET:
2105 *phProv = read_key_container(szKeyContainerName, dwFlags, pVTable);
2106 if (*phProv != (HCRYPTPROV)INVALID_HANDLE_VALUE)
2108 release_handle(&handle_table, *phProv, RSAENH_MAGIC_CONTAINER);
2109 TRACE("Can't create new keyset, already exists\n");
2110 SetLastError(NTE_EXISTS);
2111 return FALSE;
2113 *phProv = new_key_container(szKeyContainerName, dwFlags, pVTable);
2114 break;
2116 case CRYPT_VERIFYCONTEXT|CRYPT_NEWKEYSET:
2117 case CRYPT_VERIFYCONTEXT:
2118 if (pszContainer && *pszContainer) {
2119 TRACE("pszContainer should be empty\n");
2120 SetLastError(NTE_BAD_FLAGS);
2121 return FALSE;
2123 *phProv = new_key_container("", dwFlags, pVTable);
2124 break;
2126 default:
2127 *phProv = (HCRYPTPROV)INVALID_HANDLE_VALUE;
2128 SetLastError(NTE_BAD_FLAGS);
2129 return FALSE;
2132 if (*phProv != (HCRYPTPROV)INVALID_HANDLE_VALUE) {
2133 SetLastError(ERROR_SUCCESS);
2134 return TRUE;
2135 } else {
2136 return FALSE;
2140 /******************************************************************************
2141 * CPCreateHash (RSAENH.@)
2143 * CPCreateHash creates and initializes a new hash object.
2145 * PARAMS
2146 * hProv [I] Handle to the key container to which the new hash will belong.
2147 * Algid [I] Identifies the hash algorithm, which will be used for the hash.
2148 * hKey [I] Handle to a session key applied for keyed hashes.
2149 * dwFlags [I] Currently no flags defined. Must be zero.
2150 * phHash [O] Points to the location where a handle to the new hash will be stored.
2152 * RETURNS
2153 * Success: TRUE
2154 * Failure: FALSE
2156 * NOTES
2157 * hKey is a handle to a session key applied in keyed hashes like MAC and HMAC.
2158 * If a normal hash object is to be created (like e.g. MD2 or SHA1) hKey must be zero.
2160 BOOL WINAPI RSAENH_CPCreateHash(HCRYPTPROV hProv, ALG_ID Algid, HCRYPTKEY hKey, DWORD dwFlags,
2161 HCRYPTHASH *phHash)
2163 CRYPTKEY *pCryptKey;
2164 CRYPTHASH *pCryptHash;
2165 const PROV_ENUMALGS_EX *peaAlgidInfo;
2167 TRACE("(hProv=%08lx, Algid=%08x, hKey=%08lx, dwFlags=%08x, phHash=%p)\n", hProv, Algid, hKey,
2168 dwFlags, phHash);
2170 peaAlgidInfo = get_algid_info(hProv, Algid);
2171 if (!peaAlgidInfo) return FALSE;
2173 if (dwFlags)
2175 SetLastError(NTE_BAD_FLAGS);
2176 return FALSE;
2179 if (Algid == CALG_MAC || Algid == CALG_HMAC || Algid == CALG_SCHANNEL_MASTER_HASH ||
2180 Algid == CALG_TLS1PRF)
2182 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey)) {
2183 SetLastError(NTE_BAD_KEY);
2184 return FALSE;
2187 if ((Algid == CALG_MAC) && (GET_ALG_TYPE(pCryptKey->aiAlgid) != ALG_TYPE_BLOCK)) {
2188 SetLastError(NTE_BAD_KEY);
2189 return FALSE;
2192 if ((Algid == CALG_SCHANNEL_MASTER_HASH || Algid == CALG_TLS1PRF) &&
2193 (pCryptKey->aiAlgid != CALG_TLS1_MASTER))
2195 SetLastError(NTE_BAD_KEY);
2196 return FALSE;
2198 if (Algid == CALG_SCHANNEL_MASTER_HASH &&
2199 ((!pCryptKey->siSChannelInfo.blobClientRandom.cbData) ||
2200 (!pCryptKey->siSChannelInfo.blobServerRandom.cbData)))
2202 SetLastError(ERROR_INVALID_PARAMETER);
2203 return FALSE;
2206 if ((Algid == CALG_TLS1PRF) && (pCryptKey->dwState != RSAENH_KEYSTATE_MASTERKEY)) {
2207 SetLastError(NTE_BAD_KEY_STATE);
2208 return FALSE;
2212 *phHash = new_object(&handle_table, sizeof(CRYPTHASH), RSAENH_MAGIC_HASH,
2213 destroy_hash, (OBJECTHDR**)&pCryptHash);
2214 if (!pCryptHash) return FALSE;
2216 pCryptHash->aiAlgid = Algid;
2217 pCryptHash->hKey = hKey;
2218 pCryptHash->hProv = hProv;
2219 pCryptHash->dwState = RSAENH_HASHSTATE_HASHING;
2220 pCryptHash->pHMACInfo = NULL;
2221 pCryptHash->dwHashSize = peaAlgidInfo->dwDefaultLen >> 3;
2222 init_data_blob(&pCryptHash->tpPRFParams.blobLabel);
2223 init_data_blob(&pCryptHash->tpPRFParams.blobSeed);
2225 if (Algid == CALG_SCHANNEL_MASTER_HASH) {
2226 static const char keyex[] = "key expansion";
2227 BYTE key_expansion[sizeof keyex];
2228 CRYPT_DATA_BLOB blobRandom, blobKeyExpansion = { 13, key_expansion };
2230 memcpy( key_expansion, keyex, sizeof keyex );
2232 if (pCryptKey->dwState != RSAENH_KEYSTATE_MASTERKEY) {
2233 static const char msec[] = "master secret";
2234 BYTE master_secret[sizeof msec];
2235 CRYPT_DATA_BLOB blobLabel = { 13, master_secret };
2236 BYTE abKeyValue[48];
2238 memcpy( master_secret, msec, sizeof msec );
2240 /* See RFC 2246, chapter 8.1 */
2241 if (!concat_data_blobs(&blobRandom,
2242 &pCryptKey->siSChannelInfo.blobClientRandom,
2243 &pCryptKey->siSChannelInfo.blobServerRandom))
2245 return FALSE;
2247 tls1_prf(hProv, hKey, &blobLabel, &blobRandom, abKeyValue, 48);
2248 pCryptKey->dwState = RSAENH_KEYSTATE_MASTERKEY;
2249 memcpy(pCryptKey->abKeyValue, abKeyValue, 48);
2250 free_data_blob(&blobRandom);
2253 /* See RFC 2246, chapter 6.3 */
2254 if (!concat_data_blobs(&blobRandom,
2255 &pCryptKey->siSChannelInfo.blobServerRandom,
2256 &pCryptKey->siSChannelInfo.blobClientRandom))
2258 return FALSE;
2260 tls1_prf(hProv, hKey, &blobKeyExpansion, &blobRandom, pCryptHash->abHashValue,
2261 RSAENH_MAX_HASH_SIZE);
2262 free_data_blob(&blobRandom);
2265 return init_hash(pCryptHash);
2268 /******************************************************************************
2269 * CPDestroyHash (RSAENH.@)
2271 * Releases the handle to a hash object. The object is destroyed if its reference
2272 * count reaches zero.
2274 * PARAMS
2275 * hProv [I] Handle to the key container to which the hash object belongs.
2276 * hHash [I] Handle to the hash object to be released.
2278 * RETURNS
2279 * Success: TRUE
2280 * Failure: FALSE
2282 BOOL WINAPI RSAENH_CPDestroyHash(HCRYPTPROV hProv, HCRYPTHASH hHash)
2284 TRACE("(hProv=%08lx, hHash=%08lx)\n", hProv, hHash);
2286 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2288 SetLastError(NTE_BAD_UID);
2289 return FALSE;
2292 if (!release_handle(&handle_table, hHash, RSAENH_MAGIC_HASH))
2294 SetLastError(NTE_BAD_HASH);
2295 return FALSE;
2298 return TRUE;
2301 /******************************************************************************
2302 * CPDestroyKey (RSAENH.@)
2304 * Releases the handle to a key object. The object is destroyed if its reference
2305 * count reaches zero.
2307 * PARAMS
2308 * hProv [I] Handle to the key container to which the key object belongs.
2309 * hKey [I] Handle to the key object to be released.
2311 * RETURNS
2312 * Success: TRUE
2313 * Failure: FALSE
2315 BOOL WINAPI RSAENH_CPDestroyKey(HCRYPTPROV hProv, HCRYPTKEY hKey)
2317 TRACE("(hProv=%08lx, hKey=%08lx)\n", hProv, hKey);
2319 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2321 SetLastError(NTE_BAD_UID);
2322 return FALSE;
2325 if (!release_handle(&handle_table, hKey, RSAENH_MAGIC_KEY))
2327 SetLastError(NTE_BAD_KEY);
2328 return FALSE;
2331 return TRUE;
2334 /******************************************************************************
2335 * CPDuplicateHash (RSAENH.@)
2337 * Clones a hash object including its current state.
2339 * PARAMS
2340 * hUID [I] Handle to the key container the hash belongs to.
2341 * hHash [I] Handle to the hash object to be cloned.
2342 * pdwReserved [I] Reserved. Must be NULL.
2343 * dwFlags [I] No flags are currently defined. Must be 0.
2344 * phHash [O] Handle to the cloned hash object.
2346 * RETURNS
2347 * Success: TRUE.
2348 * Failure: FALSE.
2350 BOOL WINAPI RSAENH_CPDuplicateHash(HCRYPTPROV hUID, HCRYPTHASH hHash, DWORD *pdwReserved,
2351 DWORD dwFlags, HCRYPTHASH *phHash)
2353 CRYPTHASH *pSrcHash, *pDestHash;
2355 TRACE("(hUID=%08lx, hHash=%08lx, pdwReserved=%p, dwFlags=%08x, phHash=%p)\n", hUID, hHash,
2356 pdwReserved, dwFlags, phHash);
2358 if (!is_valid_handle(&handle_table, hUID, RSAENH_MAGIC_CONTAINER))
2360 SetLastError(NTE_BAD_UID);
2361 return FALSE;
2364 if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH, (OBJECTHDR**)&pSrcHash))
2366 SetLastError(NTE_BAD_HASH);
2367 return FALSE;
2370 if (!phHash || pdwReserved || dwFlags)
2372 SetLastError(ERROR_INVALID_PARAMETER);
2373 return FALSE;
2376 *phHash = new_object(&handle_table, sizeof(CRYPTHASH), RSAENH_MAGIC_HASH,
2377 destroy_hash, (OBJECTHDR**)&pDestHash);
2378 if (*phHash != (HCRYPTHASH)INVALID_HANDLE_VALUE)
2380 *pDestHash = *pSrcHash;
2381 duplicate_hash_impl(&pSrcHash->context, &pDestHash->context);
2382 copy_hmac_info(&pDestHash->pHMACInfo, pSrcHash->pHMACInfo);
2383 copy_data_blob(&pDestHash->tpPRFParams.blobLabel, &pSrcHash->tpPRFParams.blobLabel);
2384 copy_data_blob(&pDestHash->tpPRFParams.blobSeed, &pSrcHash->tpPRFParams.blobSeed);
2387 return *phHash != (HCRYPTHASH)INVALID_HANDLE_VALUE;
2390 /******************************************************************************
2391 * CPDuplicateKey (RSAENH.@)
2393 * Clones a key object including its current state.
2395 * PARAMS
2396 * hUID [I] Handle to the key container the hash belongs to.
2397 * hKey [I] Handle to the key object to be cloned.
2398 * pdwReserved [I] Reserved. Must be NULL.
2399 * dwFlags [I] No flags are currently defined. Must be 0.
2400 * phHash [O] Handle to the cloned key object.
2402 * RETURNS
2403 * Success: TRUE.
2404 * Failure: FALSE.
2406 BOOL WINAPI RSAENH_CPDuplicateKey(HCRYPTPROV hUID, HCRYPTKEY hKey, DWORD *pdwReserved,
2407 DWORD dwFlags, HCRYPTKEY *phKey)
2409 CRYPTKEY *pSrcKey, *pDestKey;
2411 TRACE("(hUID=%08lx, hKey=%08lx, pdwReserved=%p, dwFlags=%08x, phKey=%p)\n", hUID, hKey,
2412 pdwReserved, dwFlags, phKey);
2414 if (!is_valid_handle(&handle_table, hUID, RSAENH_MAGIC_CONTAINER))
2416 SetLastError(NTE_BAD_UID);
2417 return FALSE;
2420 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pSrcKey))
2422 SetLastError(NTE_BAD_KEY);
2423 return FALSE;
2426 if (!phKey || pdwReserved || dwFlags)
2428 SetLastError(ERROR_INVALID_PARAMETER);
2429 return FALSE;
2432 *phKey = new_object(&handle_table, sizeof(CRYPTKEY), RSAENH_MAGIC_KEY, destroy_key,
2433 (OBJECTHDR**)&pDestKey);
2434 if (*phKey != (HCRYPTKEY)INVALID_HANDLE_VALUE)
2436 *pDestKey = *pSrcKey;
2437 copy_data_blob(&pDestKey->siSChannelInfo.blobServerRandom,
2438 &pSrcKey->siSChannelInfo.blobServerRandom);
2439 copy_data_blob(&pDestKey->siSChannelInfo.blobClientRandom,
2440 &pSrcKey->siSChannelInfo.blobClientRandom);
2441 duplicate_key_impl(pSrcKey->aiAlgid, &pSrcKey->context, &pDestKey->context);
2442 return TRUE;
2444 else
2446 return FALSE;
2450 /******************************************************************************
2451 * CPEncrypt (RSAENH.@)
2453 * Encrypt data.
2455 * PARAMS
2456 * hProv [I] The key container hKey and hHash belong to.
2457 * hKey [I] The key used to encrypt the data.
2458 * hHash [I] An optional hash object for parallel hashing. See notes.
2459 * Final [I] Indicates if this is the last block of data to encrypt.
2460 * dwFlags [I] Must be zero or CRYPT_OAEP
2461 * pbData [I/O] Pointer to the data to encrypt. Encrypted data will also be stored there.
2462 * pdwDataLen [I/O] I: Length of data to encrypt, O: Length of encrypted data.
2463 * dwBufLen [I] Size of the buffer at pbData.
2465 * RETURNS
2466 * Success: TRUE.
2467 * Failure: FALSE.
2469 * NOTES
2470 * If a hash object handle is provided in hHash, it will be updated with the plaintext.
2471 * This is useful for message signatures.
2473 * This function uses the standard WINAPI protocol for querying data of dynamic length.
2475 BOOL WINAPI RSAENH_CPEncrypt(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final,
2476 DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen, DWORD dwBufLen)
2478 CRYPTKEY *pCryptKey;
2479 BYTE *in, out[RSAENH_MAX_BLOCK_SIZE], o[RSAENH_MAX_BLOCK_SIZE];
2480 DWORD dwEncryptedLen, i, j, k;
2482 TRACE("(hProv=%08lx, hKey=%08lx, hHash=%08lx, Final=%d, dwFlags=%08x, pbData=%p, "
2483 "pdwDataLen=%p, dwBufLen=%d)\n", hProv, hKey, hHash, Final, dwFlags, pbData, pdwDataLen,
2484 dwBufLen);
2486 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2488 SetLastError(NTE_BAD_UID);
2489 return FALSE;
2492 if (dwFlags != 0 && dwFlags != CRYPT_OAEP)
2494 SetLastError(NTE_BAD_FLAGS);
2495 return FALSE;
2498 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2500 SetLastError(NTE_BAD_KEY);
2501 return FALSE;
2504 if (pCryptKey->dwState == RSAENH_KEYSTATE_IDLE)
2505 pCryptKey->dwState = RSAENH_KEYSTATE_ENCRYPTING;
2507 if (pCryptKey->dwState != RSAENH_KEYSTATE_ENCRYPTING)
2509 SetLastError(NTE_BAD_DATA);
2510 return FALSE;
2513 if (is_valid_handle(&handle_table, hHash, RSAENH_MAGIC_HASH)) {
2514 if (!RSAENH_CPHashData(hProv, hHash, pbData, *pdwDataLen, 0)) return FALSE;
2517 if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_BLOCK) {
2518 if (!Final && (*pdwDataLen % pCryptKey->dwBlockLen)) {
2519 SetLastError(NTE_BAD_DATA);
2520 return FALSE;
2523 dwEncryptedLen = (*pdwDataLen/pCryptKey->dwBlockLen+(Final?1:0))*pCryptKey->dwBlockLen;
2525 if (pbData == NULL) {
2526 *pdwDataLen = dwEncryptedLen;
2527 return TRUE;
2529 else if (dwEncryptedLen > dwBufLen) {
2530 *pdwDataLen = dwEncryptedLen;
2531 SetLastError(ERROR_MORE_DATA);
2532 return FALSE;
2535 /* Pad final block with length bytes */
2536 for (i=*pdwDataLen; i<dwEncryptedLen; i++) pbData[i] = dwEncryptedLen - *pdwDataLen;
2537 *pdwDataLen = dwEncryptedLen;
2539 for (i=0, in=pbData; i<*pdwDataLen; i+=pCryptKey->dwBlockLen, in+=pCryptKey->dwBlockLen) {
2540 switch (pCryptKey->dwMode) {
2541 case CRYPT_MODE_ECB:
2542 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out,
2543 RSAENH_ENCRYPT);
2544 break;
2546 case CRYPT_MODE_CBC:
2547 for (j=0; j<pCryptKey->dwBlockLen; j++) in[j] ^= pCryptKey->abChainVector[j];
2548 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out,
2549 RSAENH_ENCRYPT);
2550 memcpy(pCryptKey->abChainVector, out, pCryptKey->dwBlockLen);
2551 break;
2553 case CRYPT_MODE_CFB:
2554 for (j=0; j<pCryptKey->dwBlockLen; j++) {
2555 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context,
2556 pCryptKey->abChainVector, o, RSAENH_ENCRYPT);
2557 out[j] = in[j] ^ o[0];
2558 for (k=0; k<pCryptKey->dwBlockLen-1; k++)
2559 pCryptKey->abChainVector[k] = pCryptKey->abChainVector[k+1];
2560 pCryptKey->abChainVector[k] = out[j];
2562 break;
2564 default:
2565 SetLastError(NTE_BAD_ALGID);
2566 return FALSE;
2568 memcpy(in, out, pCryptKey->dwBlockLen);
2570 } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_STREAM) {
2571 if (pbData == NULL) {
2572 *pdwDataLen = dwBufLen;
2573 return TRUE;
2575 encrypt_stream_impl(pCryptKey->aiAlgid, &pCryptKey->context, pbData, *pdwDataLen);
2576 } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_RSA) {
2577 if (pCryptKey->aiAlgid == CALG_RSA_SIGN) {
2578 SetLastError(NTE_BAD_KEY);
2579 return FALSE;
2581 if (!pbData) {
2582 *pdwDataLen = pCryptKey->dwBlockLen;
2583 return TRUE;
2585 if (dwBufLen < pCryptKey->dwBlockLen) {
2586 SetLastError(ERROR_MORE_DATA);
2587 return FALSE;
2589 if (!pad_data(hProv, pbData, *pdwDataLen, pbData, pCryptKey->dwBlockLen, dwFlags)) return FALSE;
2590 encrypt_block_impl(pCryptKey->aiAlgid, PK_PUBLIC, &pCryptKey->context, pbData, pbData, RSAENH_ENCRYPT);
2591 *pdwDataLen = pCryptKey->dwBlockLen;
2592 Final = TRUE;
2593 } else {
2594 SetLastError(NTE_BAD_TYPE);
2595 return FALSE;
2598 if (Final) setup_key(pCryptKey);
2600 return TRUE;
2603 /******************************************************************************
2604 * CPDecrypt (RSAENH.@)
2606 * Decrypt data.
2608 * PARAMS
2609 * hProv [I] The key container hKey and hHash belong to.
2610 * hKey [I] The key used to decrypt the data.
2611 * hHash [I] An optional hash object for parallel hashing. See notes.
2612 * Final [I] Indicates if this is the last block of data to decrypt.
2613 * dwFlags [I] Must be zero or CRYPT_OAEP
2614 * pbData [I/O] Pointer to the data to decrypt. Plaintext will also be stored there.
2615 * pdwDataLen [I/O] I: Length of ciphertext, O: Length of plaintext.
2617 * RETURNS
2618 * Success: TRUE.
2619 * Failure: FALSE.
2621 * NOTES
2622 * If a hash object handle is provided in hHash, it will be updated with the plaintext.
2623 * This is useful for message signatures.
2625 * This function uses the standard WINAPI protocol for querying data of dynamic length.
2627 BOOL WINAPI RSAENH_CPDecrypt(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final,
2628 DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2630 CRYPTKEY *pCryptKey;
2631 BYTE *in, out[RSAENH_MAX_BLOCK_SIZE], o[RSAENH_MAX_BLOCK_SIZE];
2632 DWORD i, j, k;
2633 DWORD dwMax;
2635 TRACE("(hProv=%08lx, hKey=%08lx, hHash=%08lx, Final=%d, dwFlags=%08x, pbData=%p, "
2636 "pdwDataLen=%p)\n", hProv, hKey, hHash, Final, dwFlags, pbData, pdwDataLen);
2638 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2640 SetLastError(NTE_BAD_UID);
2641 return FALSE;
2644 if (dwFlags != 0 && dwFlags != CRYPT_OAEP)
2646 SetLastError(NTE_BAD_FLAGS);
2647 return FALSE;
2650 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2652 SetLastError(NTE_BAD_KEY);
2653 return FALSE;
2656 if (pCryptKey->dwState == RSAENH_KEYSTATE_IDLE)
2657 pCryptKey->dwState = RSAENH_KEYSTATE_ENCRYPTING;
2659 if (pCryptKey->dwState != RSAENH_KEYSTATE_ENCRYPTING)
2661 SetLastError(NTE_BAD_DATA);
2662 return FALSE;
2665 dwMax=*pdwDataLen;
2667 if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_BLOCK) {
2668 for (i=0, in=pbData; i<*pdwDataLen; i+=pCryptKey->dwBlockLen, in+=pCryptKey->dwBlockLen) {
2669 switch (pCryptKey->dwMode) {
2670 case CRYPT_MODE_ECB:
2671 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out,
2672 RSAENH_DECRYPT);
2673 break;
2675 case CRYPT_MODE_CBC:
2676 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out,
2677 RSAENH_DECRYPT);
2678 for (j=0; j<pCryptKey->dwBlockLen; j++) out[j] ^= pCryptKey->abChainVector[j];
2679 memcpy(pCryptKey->abChainVector, in, pCryptKey->dwBlockLen);
2680 break;
2682 case CRYPT_MODE_CFB:
2683 for (j=0; j<pCryptKey->dwBlockLen; j++) {
2684 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context,
2685 pCryptKey->abChainVector, o, RSAENH_ENCRYPT);
2686 out[j] = in[j] ^ o[0];
2687 for (k=0; k<pCryptKey->dwBlockLen-1; k++)
2688 pCryptKey->abChainVector[k] = pCryptKey->abChainVector[k+1];
2689 pCryptKey->abChainVector[k] = in[j];
2691 break;
2693 default:
2694 SetLastError(NTE_BAD_ALGID);
2695 return FALSE;
2697 memcpy(in, out, pCryptKey->dwBlockLen);
2699 if (Final) {
2700 if (pbData[*pdwDataLen-1] &&
2701 pbData[*pdwDataLen-1] <= pCryptKey->dwBlockLen &&
2702 pbData[*pdwDataLen-1] <= *pdwDataLen) {
2703 BOOL padOkay = TRUE;
2705 /* check that every bad byte has the same value */
2706 for (i = 1; padOkay && i < pbData[*pdwDataLen-1]; i++)
2707 if (pbData[*pdwDataLen - i - 1] != pbData[*pdwDataLen - 1])
2708 padOkay = FALSE;
2709 if (padOkay)
2710 *pdwDataLen -= pbData[*pdwDataLen-1];
2711 else {
2712 SetLastError(NTE_BAD_DATA);
2713 setup_key(pCryptKey);
2714 return FALSE;
2717 else {
2718 SetLastError(NTE_BAD_DATA);
2719 setup_key(pCryptKey);
2720 return FALSE;
2724 } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_STREAM) {
2725 encrypt_stream_impl(pCryptKey->aiAlgid, &pCryptKey->context, pbData, *pdwDataLen);
2726 } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_RSA) {
2727 if (pCryptKey->aiAlgid == CALG_RSA_SIGN) {
2728 SetLastError(NTE_BAD_KEY);
2729 return FALSE;
2731 encrypt_block_impl(pCryptKey->aiAlgid, PK_PRIVATE, &pCryptKey->context, pbData, pbData, RSAENH_DECRYPT);
2732 if (!unpad_data(hProv, pbData, pCryptKey->dwBlockLen, pbData, pdwDataLen, dwFlags)) return FALSE;
2733 Final = TRUE;
2734 } else {
2735 SetLastError(NTE_BAD_TYPE);
2736 return FALSE;
2739 if (Final) setup_key(pCryptKey);
2741 if (is_valid_handle(&handle_table, hHash, RSAENH_MAGIC_HASH)) {
2742 if (*pdwDataLen>dwMax ||
2743 !RSAENH_CPHashData(hProv, hHash, pbData, *pdwDataLen, 0)) return FALSE;
2746 return TRUE;
2749 static BOOL crypt_export_simple(CRYPTKEY *pCryptKey, CRYPTKEY *pPubKey,
2750 DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2752 BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2753 ALG_ID *pAlgid = (ALG_ID*)(pBlobHeader+1);
2754 DWORD dwDataLen;
2756 if (!(GET_ALG_CLASS(pCryptKey->aiAlgid)&(ALG_CLASS_DATA_ENCRYPT|ALG_CLASS_MSG_ENCRYPT))) {
2757 SetLastError(NTE_BAD_KEY); /* FIXME: error code? */
2758 return FALSE;
2761 dwDataLen = sizeof(BLOBHEADER) + sizeof(ALG_ID) + pPubKey->dwBlockLen;
2762 if (pbData) {
2763 if (*pdwDataLen < dwDataLen) {
2764 SetLastError(ERROR_MORE_DATA);
2765 *pdwDataLen = dwDataLen;
2766 return FALSE;
2769 pBlobHeader->bType = SIMPLEBLOB;
2770 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2771 pBlobHeader->reserved = 0;
2772 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2774 *pAlgid = pPubKey->aiAlgid;
2776 if (!pad_data(pCryptKey->hProv, pCryptKey->abKeyValue, pCryptKey->dwKeyLen, (BYTE*)(pAlgid+1),
2777 pPubKey->dwBlockLen, dwFlags))
2779 return FALSE;
2782 encrypt_block_impl(pPubKey->aiAlgid, PK_PUBLIC, &pPubKey->context, (BYTE*)(pAlgid+1),
2783 (BYTE*)(pAlgid+1), RSAENH_ENCRYPT);
2785 *pdwDataLen = dwDataLen;
2786 return TRUE;
2789 static BOOL crypt_export_public_key(CRYPTKEY *pCryptKey, BYTE *pbData,
2790 DWORD *pdwDataLen)
2792 BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2793 RSAPUBKEY *pRSAPubKey = (RSAPUBKEY*)(pBlobHeader+1);
2794 DWORD dwDataLen;
2796 if ((pCryptKey->aiAlgid != CALG_RSA_KEYX) && (pCryptKey->aiAlgid != CALG_RSA_SIGN)) {
2797 SetLastError(NTE_BAD_KEY);
2798 return FALSE;
2801 dwDataLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) + pCryptKey->dwKeyLen;
2802 if (pbData) {
2803 if (*pdwDataLen < dwDataLen) {
2804 SetLastError(ERROR_MORE_DATA);
2805 *pdwDataLen = dwDataLen;
2806 return FALSE;
2809 pBlobHeader->bType = PUBLICKEYBLOB;
2810 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2811 pBlobHeader->reserved = 0;
2812 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2814 pRSAPubKey->magic = RSAENH_MAGIC_RSA1;
2815 pRSAPubKey->bitlen = pCryptKey->dwKeyLen << 3;
2817 export_public_key_impl((BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2818 pCryptKey->dwKeyLen, &pRSAPubKey->pubexp);
2820 *pdwDataLen = dwDataLen;
2821 return TRUE;
2824 static BOOL crypt_export_private_key(CRYPTKEY *pCryptKey, BOOL force,
2825 BYTE *pbData, DWORD *pdwDataLen)
2827 BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2828 RSAPUBKEY *pRSAPubKey = (RSAPUBKEY*)(pBlobHeader+1);
2829 DWORD dwDataLen;
2831 if ((pCryptKey->aiAlgid != CALG_RSA_KEYX) && (pCryptKey->aiAlgid != CALG_RSA_SIGN)) {
2832 SetLastError(NTE_BAD_KEY);
2833 return FALSE;
2835 if (!force && !(pCryptKey->dwPermissions & CRYPT_EXPORT))
2837 SetLastError(NTE_BAD_KEY_STATE);
2838 return FALSE;
2841 dwDataLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) +
2842 2 * pCryptKey->dwKeyLen + 5 * ((pCryptKey->dwKeyLen + 1) >> 1);
2843 if (pbData) {
2844 if (*pdwDataLen < dwDataLen) {
2845 SetLastError(ERROR_MORE_DATA);
2846 *pdwDataLen = dwDataLen;
2847 return FALSE;
2850 pBlobHeader->bType = PRIVATEKEYBLOB;
2851 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2852 pBlobHeader->reserved = 0;
2853 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2855 pRSAPubKey->magic = RSAENH_MAGIC_RSA2;
2856 pRSAPubKey->bitlen = pCryptKey->dwKeyLen << 3;
2858 export_private_key_impl((BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2859 pCryptKey->dwKeyLen, &pRSAPubKey->pubexp);
2861 *pdwDataLen = dwDataLen;
2862 return TRUE;
2865 static BOOL crypt_export_plaintext_key(CRYPTKEY *pCryptKey, BYTE *pbData,
2866 DWORD *pdwDataLen)
2868 BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2869 DWORD *pKeyLen = (DWORD*)(pBlobHeader+1);
2870 BYTE *pbKey = (BYTE*)(pKeyLen+1);
2871 DWORD dwDataLen;
2873 dwDataLen = sizeof(BLOBHEADER) + sizeof(DWORD) + pCryptKey->dwKeyLen;
2874 if (pbData) {
2875 if (*pdwDataLen < dwDataLen) {
2876 SetLastError(ERROR_MORE_DATA);
2877 *pdwDataLen = dwDataLen;
2878 return FALSE;
2881 pBlobHeader->bType = PLAINTEXTKEYBLOB;
2882 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2883 pBlobHeader->reserved = 0;
2884 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2886 *pKeyLen = pCryptKey->dwKeyLen;
2887 memcpy(pbKey, pCryptKey->abKeyValue, pCryptKey->dwKeyLen);
2889 *pdwDataLen = dwDataLen;
2890 return TRUE;
2892 /******************************************************************************
2893 * crypt_export_key [Internal]
2895 * Export a key into a binary large object (BLOB). Called by CPExportKey and
2896 * by store_key_pair.
2898 * PARAMS
2899 * pCryptKey [I] Key to be exported.
2900 * hPubKey [I] Key used to encrypt sensitive BLOB data.
2901 * dwBlobType [I] SIMPLEBLOB, PUBLICKEYBLOB or PRIVATEKEYBLOB.
2902 * dwFlags [I] Currently none defined.
2903 * force [I] If TRUE, the key is written no matter what the key's
2904 * permissions are. Otherwise the key's permissions are
2905 * checked before exporting.
2906 * pbData [O] Pointer to a buffer where the BLOB will be written to.
2907 * pdwDataLen [I/O] I: Size of buffer at pbData, O: Size of BLOB
2909 * RETURNS
2910 * Success: TRUE.
2911 * Failure: FALSE.
2913 static BOOL crypt_export_key(CRYPTKEY *pCryptKey, HCRYPTKEY hPubKey,
2914 DWORD dwBlobType, DWORD dwFlags, BOOL force,
2915 BYTE *pbData, DWORD *pdwDataLen)
2917 CRYPTKEY *pPubKey;
2919 if (dwFlags & CRYPT_SSL2_FALLBACK) {
2920 if (pCryptKey->aiAlgid != CALG_SSL2_MASTER) {
2921 SetLastError(NTE_BAD_KEY);
2922 return FALSE;
2926 switch ((BYTE)dwBlobType)
2928 case SIMPLEBLOB:
2929 if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pPubKey)){
2930 SetLastError(NTE_BAD_PUBLIC_KEY); /* FIXME: error_code? */
2931 return FALSE;
2933 return crypt_export_simple(pCryptKey, pPubKey, dwFlags, pbData,
2934 pdwDataLen);
2936 case PUBLICKEYBLOB:
2937 if (is_valid_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY)) {
2938 SetLastError(NTE_BAD_KEY); /* FIXME: error code? */
2939 return FALSE;
2942 return crypt_export_public_key(pCryptKey, pbData, pdwDataLen);
2944 case PRIVATEKEYBLOB:
2945 return crypt_export_private_key(pCryptKey, force, pbData, pdwDataLen);
2947 case PLAINTEXTKEYBLOB:
2948 return crypt_export_plaintext_key(pCryptKey, pbData, pdwDataLen);
2950 default:
2951 SetLastError(NTE_BAD_TYPE); /* FIXME: error code? */
2952 return FALSE;
2956 /******************************************************************************
2957 * CPExportKey (RSAENH.@)
2959 * Export a key into a binary large object (BLOB).
2961 * PARAMS
2962 * hProv [I] Key container from which a key is to be exported.
2963 * hKey [I] Key to be exported.
2964 * hPubKey [I] Key used to encrypt sensitive BLOB data.
2965 * dwBlobType [I] SIMPLEBLOB, PUBLICKEYBLOB or PRIVATEKEYBLOB.
2966 * dwFlags [I] Currently none defined.
2967 * pbData [O] Pointer to a buffer where the BLOB will be written to.
2968 * pdwDataLen [I/O] I: Size of buffer at pbData, O: Size of BLOB
2970 * RETURNS
2971 * Success: TRUE.
2972 * Failure: FALSE.
2974 BOOL WINAPI RSAENH_CPExportKey(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTKEY hPubKey,
2975 DWORD dwBlobType, DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2977 CRYPTKEY *pCryptKey;
2979 TRACE("(hProv=%08lx, hKey=%08lx, hPubKey=%08lx, dwBlobType=%08x, dwFlags=%08x, pbData=%p,"
2980 "pdwDataLen=%p)\n", hProv, hKey, hPubKey, dwBlobType, dwFlags, pbData, pdwDataLen);
2982 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2984 SetLastError(NTE_BAD_UID);
2985 return FALSE;
2988 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2990 SetLastError(NTE_BAD_KEY);
2991 return FALSE;
2994 return crypt_export_key(pCryptKey, hPubKey, dwBlobType, dwFlags, FALSE,
2995 pbData, pdwDataLen);
2998 /******************************************************************************
2999 * release_and_install_key [Internal]
3001 * Release an existing key, if present, and replaces it with a new one.
3003 * PARAMS
3004 * hProv [I] Key container into which the key is to be imported.
3005 * src [I] Key which will replace *dest
3006 * dest [I] Points to key to be released and replaced with src
3007 * fStoreKey [I] If TRUE, the newly installed key is stored to the registry.
3009 static void release_and_install_key(HCRYPTPROV hProv, HCRYPTKEY src,
3010 HCRYPTKEY *dest, DWORD fStoreKey)
3012 RSAENH_CPDestroyKey(hProv, *dest);
3013 copy_handle(&handle_table, src, RSAENH_MAGIC_KEY, dest);
3014 if (fStoreKey)
3016 KEYCONTAINER *pKeyContainer;
3018 if ((pKeyContainer = get_key_container(hProv)))
3020 store_key_container_keys(pKeyContainer);
3021 store_key_container_permissions(pKeyContainer);
3026 /******************************************************************************
3027 * import_private_key [Internal]
3029 * Import a BLOB'ed private key into a key container.
3031 * PARAMS
3032 * hProv [I] Key container into which the private key is to be imported.
3033 * pbData [I] Pointer to a buffer which holds the private key BLOB.
3034 * dwDataLen [I] Length of data in buffer at pbData.
3035 * dwFlags [I] One of:
3036 * CRYPT_EXPORTABLE: the imported key is marked exportable
3037 * fStoreKey [I] If TRUE, the imported key is stored to the registry.
3038 * phKey [O] Handle to the imported key.
3041 * NOTES
3042 * Assumes the caller has already checked the BLOBHEADER at pbData to ensure
3043 * it's a PRIVATEKEYBLOB.
3045 * RETURNS
3046 * Success: TRUE.
3047 * Failure: FALSE.
3049 static BOOL import_private_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
3050 DWORD dwFlags, BOOL fStoreKey, HCRYPTKEY *phKey)
3052 KEYCONTAINER *pKeyContainer;
3053 CRYPTKEY *pCryptKey;
3054 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
3055 const RSAPUBKEY *pRSAPubKey = (const RSAPUBKEY*)(pBlobHeader+1);
3056 BOOL ret;
3058 if (dwFlags & CRYPT_IPSEC_HMAC_KEY)
3060 FIXME("unimplemented for CRYPT_IPSEC_HMAC_KEY\n");
3061 SetLastError(NTE_BAD_FLAGS);
3062 return FALSE;
3064 if (!(pKeyContainer = get_key_container(hProv)))
3065 return FALSE;
3067 if ((dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY)))
3069 ERR("datalen %d not long enough for a BLOBHEADER + RSAPUBKEY\n",
3070 dwDataLen);
3071 SetLastError(NTE_BAD_DATA);
3072 return FALSE;
3074 if (pRSAPubKey->magic != RSAENH_MAGIC_RSA2)
3076 ERR("unexpected magic %08x\n", pRSAPubKey->magic);
3077 SetLastError(NTE_BAD_DATA);
3078 return FALSE;
3080 if ((dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) +
3081 (pRSAPubKey->bitlen >> 3) + (5 * ((pRSAPubKey->bitlen+8)>>4))))
3083 DWORD expectedLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) +
3084 (pRSAPubKey->bitlen >> 3) + (5 * ((pRSAPubKey->bitlen+8)>>4));
3086 ERR("blob too short for pub key: expect %d, got %d\n",
3087 expectedLen, dwDataLen);
3088 SetLastError(NTE_BAD_DATA);
3089 return FALSE;
3092 *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, MAKELONG(0,pRSAPubKey->bitlen), &pCryptKey);
3093 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
3094 setup_key(pCryptKey);
3095 ret = import_private_key_impl((const BYTE*)(pRSAPubKey+1), &pCryptKey->context,
3096 pRSAPubKey->bitlen/8, dwDataLen, pRSAPubKey->pubexp);
3097 if (ret) {
3098 if (dwFlags & CRYPT_EXPORTABLE)
3099 pCryptKey->dwPermissions |= CRYPT_EXPORT;
3100 switch (pBlobHeader->aiKeyAlg)
3102 case AT_SIGNATURE:
3103 case CALG_RSA_SIGN:
3104 TRACE("installing signing key\n");
3105 release_and_install_key(hProv, *phKey, &pKeyContainer->hSignatureKeyPair,
3106 fStoreKey);
3107 break;
3108 case AT_KEYEXCHANGE:
3109 case CALG_RSA_KEYX:
3110 TRACE("installing key exchange key\n");
3111 release_and_install_key(hProv, *phKey, &pKeyContainer->hKeyExchangeKeyPair,
3112 fStoreKey);
3113 break;
3116 return ret;
3119 /******************************************************************************
3120 * import_public_key [Internal]
3122 * Import a BLOB'ed public key.
3124 * PARAMS
3125 * hProv [I] A CSP.
3126 * pbData [I] Pointer to a buffer which holds the public key BLOB.
3127 * dwDataLen [I] Length of data in buffer at pbData.
3128 * dwFlags [I] One of:
3129 * CRYPT_EXPORTABLE: the imported key is marked exportable
3130 * phKey [O] Handle to the imported key.
3133 * NOTES
3134 * Assumes the caller has already checked the BLOBHEADER at pbData to ensure
3135 * it's a PUBLICKEYBLOB.
3137 * RETURNS
3138 * Success: TRUE.
3139 * Failure: FALSE.
3141 static BOOL import_public_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
3142 DWORD dwFlags, HCRYPTKEY *phKey)
3144 CRYPTKEY *pCryptKey;
3145 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
3146 const RSAPUBKEY *pRSAPubKey = (const RSAPUBKEY*)(pBlobHeader+1);
3147 ALG_ID algID;
3148 BOOL ret;
3150 if (dwFlags & CRYPT_IPSEC_HMAC_KEY)
3152 FIXME("unimplemented for CRYPT_IPSEC_HMAC_KEY\n");
3153 SetLastError(NTE_BAD_FLAGS);
3154 return FALSE;
3157 if ((dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY)) ||
3158 (pRSAPubKey->magic != RSAENH_MAGIC_RSA1) ||
3159 (dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) + (pRSAPubKey->bitlen >> 3)))
3161 SetLastError(NTE_BAD_DATA);
3162 return FALSE;
3165 /* Since this is a public key blob, only the public key is
3166 * available, so only signature verification is possible.
3168 algID = pBlobHeader->aiKeyAlg;
3169 *phKey = new_key(hProv, algID, MAKELONG(0,pRSAPubKey->bitlen), &pCryptKey);
3170 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
3171 setup_key(pCryptKey);
3172 ret = import_public_key_impl((const BYTE*)(pRSAPubKey+1), &pCryptKey->context,
3173 pRSAPubKey->bitlen >> 3, pRSAPubKey->pubexp);
3174 if (ret) {
3175 if (dwFlags & CRYPT_EXPORTABLE)
3176 pCryptKey->dwPermissions |= CRYPT_EXPORT;
3178 return ret;
3181 /******************************************************************************
3182 * import_symmetric_key [Internal]
3184 * Import a BLOB'ed symmetric key into a key container.
3186 * PARAMS
3187 * hProv [I] Key container into which the symmetric key is to be imported.
3188 * pbData [I] Pointer to a buffer which holds the symmetric key BLOB.
3189 * dwDataLen [I] Length of data in buffer at pbData.
3190 * hPubKey [I] Key used to decrypt sensitive BLOB data.
3191 * dwFlags [I] One of:
3192 * CRYPT_EXPORTABLE: the imported key is marked exportable
3193 * phKey [O] Handle to the imported key.
3196 * NOTES
3197 * Assumes the caller has already checked the BLOBHEADER at pbData to ensure
3198 * it's a SIMPLEBLOB.
3200 * RETURNS
3201 * Success: TRUE.
3202 * Failure: FALSE.
3204 static BOOL import_symmetric_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
3205 HCRYPTKEY hPubKey, DWORD dwFlags, HCRYPTKEY *phKey)
3207 CRYPTKEY *pCryptKey, *pPubKey;
3208 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
3209 const ALG_ID *pAlgid = (const ALG_ID*)(pBlobHeader+1);
3210 const BYTE *pbKeyStream = (const BYTE*)(pAlgid + 1);
3211 BYTE *pbDecrypted;
3212 DWORD dwKeyLen;
3214 if (dwFlags & CRYPT_IPSEC_HMAC_KEY)
3216 FIXME("unimplemented for CRYPT_IPSEC_HMAC_KEY\n");
3217 SetLastError(NTE_BAD_FLAGS);
3218 return FALSE;
3220 if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pPubKey) ||
3221 pPubKey->aiAlgid != CALG_RSA_KEYX)
3223 SetLastError(NTE_BAD_PUBLIC_KEY); /* FIXME: error code? */
3224 return FALSE;
3227 if (dwDataLen < sizeof(BLOBHEADER)+sizeof(ALG_ID)+pPubKey->dwBlockLen)
3229 SetLastError(NTE_BAD_DATA); /* FIXME: error code */
3230 return FALSE;
3233 pbDecrypted = HeapAlloc(GetProcessHeap(), 0, pPubKey->dwBlockLen);
3234 if (!pbDecrypted) return FALSE;
3235 encrypt_block_impl(pPubKey->aiAlgid, PK_PRIVATE, &pPubKey->context, pbKeyStream, pbDecrypted,
3236 RSAENH_DECRYPT);
3238 dwKeyLen = RSAENH_MAX_KEY_SIZE;
3239 if (!unpad_data(hProv, pbDecrypted, pPubKey->dwBlockLen, pbDecrypted, &dwKeyLen, dwFlags)) {
3240 HeapFree(GetProcessHeap(), 0, pbDecrypted);
3241 return FALSE;
3244 *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, dwKeyLen<<19, &pCryptKey);
3245 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
3247 HeapFree(GetProcessHeap(), 0, pbDecrypted);
3248 return FALSE;
3250 memcpy(pCryptKey->abKeyValue, pbDecrypted, dwKeyLen);
3251 HeapFree(GetProcessHeap(), 0, pbDecrypted);
3252 setup_key(pCryptKey);
3253 if (dwFlags & CRYPT_EXPORTABLE)
3254 pCryptKey->dwPermissions |= CRYPT_EXPORT;
3255 return TRUE;
3258 /******************************************************************************
3259 * import_plaintext_key [Internal]
3261 * Import a plaintext key into a key container.
3263 * PARAMS
3264 * hProv [I] Key container into which the symmetric key is to be imported.
3265 * pbData [I] Pointer to a buffer which holds the plaintext key BLOB.
3266 * dwDataLen [I] Length of data in buffer at pbData.
3267 * dwFlags [I] One of:
3268 * CRYPT_EXPORTABLE: the imported key is marked exportable
3269 * phKey [O] Handle to the imported key.
3272 * NOTES
3273 * Assumes the caller has already checked the BLOBHEADER at pbData to ensure
3274 * it's a PLAINTEXTKEYBLOB.
3276 * RETURNS
3277 * Success: TRUE.
3278 * Failure: FALSE.
3280 static BOOL import_plaintext_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
3281 DWORD dwFlags, HCRYPTKEY *phKey)
3283 CRYPTKEY *pCryptKey;
3284 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
3285 const DWORD *pKeyLen = (const DWORD *)(pBlobHeader + 1);
3286 const BYTE *pbKeyStream = (const BYTE*)(pKeyLen + 1);
3288 if (dwDataLen < sizeof(BLOBHEADER)+sizeof(DWORD)+*pKeyLen)
3290 SetLastError(NTE_BAD_DATA); /* FIXME: error code */
3291 return FALSE;
3294 if (dwFlags & CRYPT_IPSEC_HMAC_KEY)
3296 *phKey = new_key(hProv, CALG_HMAC, 0, &pCryptKey);
3297 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
3298 return FALSE;
3299 if (*pKeyLen <= RSAENH_MIN(sizeof(pCryptKey->abKeyValue), RSAENH_HMAC_BLOCK_LEN))
3301 memcpy(pCryptKey->abKeyValue, pbKeyStream, *pKeyLen);
3302 pCryptKey->dwKeyLen = *pKeyLen;
3304 else
3306 CRYPT_DATA_BLOB blobHmacKey = { *pKeyLen, (BYTE *)pbKeyStream };
3308 /* In order to initialize an HMAC key, the key material is hashed,
3309 * and the output of the hash function is used as the key material.
3310 * Unfortunately, the way the Crypto API is designed, we don't know
3311 * the hash algorithm yet, so we have to copy the entire key
3312 * material.
3314 if (!copy_data_blob(&pCryptKey->blobHmacKey, &blobHmacKey))
3316 release_handle(&handle_table, *phKey, RSAENH_MAGIC_KEY);
3317 *phKey = (HCRYPTKEY)INVALID_HANDLE_VALUE;
3318 return FALSE;
3321 setup_key(pCryptKey);
3322 if (dwFlags & CRYPT_EXPORTABLE)
3323 pCryptKey->dwPermissions |= CRYPT_EXPORT;
3325 else
3327 *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, *pKeyLen<<19, &pCryptKey);
3328 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
3329 return FALSE;
3330 memcpy(pCryptKey->abKeyValue, pbKeyStream, *pKeyLen);
3331 setup_key(pCryptKey);
3332 if (dwFlags & CRYPT_EXPORTABLE)
3333 pCryptKey->dwPermissions |= CRYPT_EXPORT;
3335 return TRUE;
3338 /******************************************************************************
3339 * import_key [Internal]
3341 * Import a BLOB'ed key into a key container, optionally storing the key's
3342 * value to the registry.
3344 * PARAMS
3345 * hProv [I] Key container into which the key is to be imported.
3346 * pbData [I] Pointer to a buffer which holds the BLOB.
3347 * dwDataLen [I] Length of data in buffer at pbData.
3348 * hPubKey [I] Key used to decrypt sensitive BLOB data.
3349 * dwFlags [I] One of:
3350 * CRYPT_EXPORTABLE: the imported key is marked exportable
3351 * fStoreKey [I] If TRUE, the imported key is stored to the registry.
3352 * phKey [O] Handle to the imported key.
3354 * RETURNS
3355 * Success: TRUE.
3356 * Failure: FALSE.
3358 static BOOL import_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen, HCRYPTKEY hPubKey,
3359 DWORD dwFlags, BOOL fStoreKey, HCRYPTKEY *phKey)
3361 KEYCONTAINER *pKeyContainer;
3362 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
3364 if (!(pKeyContainer = get_key_container(hProv)))
3365 return FALSE;
3367 if (dwDataLen < sizeof(BLOBHEADER) ||
3368 pBlobHeader->bVersion != CUR_BLOB_VERSION ||
3369 pBlobHeader->reserved != 0)
3371 TRACE("bVersion = %d, reserved = %d\n", pBlobHeader->bVersion,
3372 pBlobHeader->reserved);
3373 SetLastError(NTE_BAD_DATA);
3374 return FALSE;
3377 /* If this is a verify-only context, the key is not persisted regardless of
3378 * fStoreKey's original value.
3380 fStoreKey = fStoreKey && !(dwFlags & CRYPT_VERIFYCONTEXT);
3381 TRACE("blob type: %x\n", pBlobHeader->bType);
3382 switch (pBlobHeader->bType)
3384 case PRIVATEKEYBLOB:
3385 return import_private_key(hProv, pbData, dwDataLen, dwFlags,
3386 fStoreKey, phKey);
3388 case PUBLICKEYBLOB:
3389 return import_public_key(hProv, pbData, dwDataLen, dwFlags,
3390 phKey);
3392 case SIMPLEBLOB:
3393 return import_symmetric_key(hProv, pbData, dwDataLen, hPubKey,
3394 dwFlags, phKey);
3396 case PLAINTEXTKEYBLOB:
3397 return import_plaintext_key(hProv, pbData, dwDataLen, dwFlags,
3398 phKey);
3400 default:
3401 SetLastError(NTE_BAD_TYPE); /* FIXME: error code? */
3402 return FALSE;
3406 /******************************************************************************
3407 * CPImportKey (RSAENH.@)
3409 * Import a BLOB'ed key into a key container.
3411 * PARAMS
3412 * hProv [I] Key container into which the key is to be imported.
3413 * pbData [I] Pointer to a buffer which holds the BLOB.
3414 * dwDataLen [I] Length of data in buffer at pbData.
3415 * hPubKey [I] Key used to decrypt sensitive BLOB data.
3416 * dwFlags [I] One of:
3417 * CRYPT_EXPORTABLE: the imported key is marked exportable
3418 * phKey [O] Handle to the imported key.
3420 * RETURNS
3421 * Success: TRUE.
3422 * Failure: FALSE.
3424 BOOL WINAPI RSAENH_CPImportKey(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
3425 HCRYPTKEY hPubKey, DWORD dwFlags, HCRYPTKEY *phKey)
3427 TRACE("(hProv=%08lx, pbData=%p, dwDataLen=%d, hPubKey=%08lx, dwFlags=%08x, phKey=%p)\n",
3428 hProv, pbData, dwDataLen, hPubKey, dwFlags, phKey);
3430 return import_key(hProv, pbData, dwDataLen, hPubKey, dwFlags, TRUE, phKey);
3433 /******************************************************************************
3434 * CPGenKey (RSAENH.@)
3436 * Generate a key in the key container
3438 * PARAMS
3439 * hProv [I] Key container for which a key is to be generated.
3440 * Algid [I] Crypto algorithm identifier for the key to be generated.
3441 * dwFlags [I] Upper 16 bits: Binary length of key. Lower 16 bits: Flags. See Notes
3442 * phKey [O] Handle to the generated key.
3444 * RETURNS
3445 * Success: TRUE.
3446 * Failure: FALSE.
3448 * FIXME
3449 * Flags currently not considered.
3451 * NOTES
3452 * Private key-exchange- and signature-keys can be generated with Algid AT_KEYEXCHANGE
3453 * and AT_SIGNATURE values.
3455 BOOL WINAPI RSAENH_CPGenKey(HCRYPTPROV hProv, ALG_ID Algid, DWORD dwFlags, HCRYPTKEY *phKey)
3457 KEYCONTAINER *pKeyContainer;
3458 CRYPTKEY *pCryptKey;
3460 TRACE("(hProv=%08lx, aiAlgid=%d, dwFlags=%08x, phKey=%p)\n", hProv, Algid, dwFlags, phKey);
3462 if (!(pKeyContainer = get_key_container(hProv)))
3464 /* MSDN: hProv not containing valid context handle */
3465 return FALSE;
3468 switch (Algid)
3470 case AT_SIGNATURE:
3471 case CALG_RSA_SIGN:
3472 *phKey = new_key(hProv, CALG_RSA_SIGN, dwFlags, &pCryptKey);
3473 if (pCryptKey) {
3474 new_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen);
3475 setup_key(pCryptKey);
3476 release_and_install_key(hProv, *phKey,
3477 &pKeyContainer->hSignatureKeyPair,
3478 FALSE);
3480 break;
3482 case AT_KEYEXCHANGE:
3483 case CALG_RSA_KEYX:
3484 *phKey = new_key(hProv, CALG_RSA_KEYX, dwFlags, &pCryptKey);
3485 if (pCryptKey) {
3486 new_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen);
3487 setup_key(pCryptKey);
3488 release_and_install_key(hProv, *phKey,
3489 &pKeyContainer->hKeyExchangeKeyPair,
3490 FALSE);
3492 break;
3494 case CALG_RC2:
3495 case CALG_RC4:
3496 case CALG_DES:
3497 case CALG_3DES_112:
3498 case CALG_3DES:
3499 case CALG_AES_128:
3500 case CALG_AES_192:
3501 case CALG_AES_256:
3502 case CALG_PCT1_MASTER:
3503 case CALG_SSL2_MASTER:
3504 case CALG_SSL3_MASTER:
3505 case CALG_TLS1_MASTER:
3506 *phKey = new_key(hProv, Algid, dwFlags, &pCryptKey);
3507 if (pCryptKey) {
3508 gen_rand_impl(pCryptKey->abKeyValue, RSAENH_MAX_KEY_SIZE);
3509 switch (Algid) {
3510 case CALG_SSL3_MASTER:
3511 pCryptKey->abKeyValue[0] = RSAENH_SSL3_VERSION_MAJOR;
3512 pCryptKey->abKeyValue[1] = RSAENH_SSL3_VERSION_MINOR;
3513 break;
3515 case CALG_TLS1_MASTER:
3516 pCryptKey->abKeyValue[0] = RSAENH_TLS1_VERSION_MAJOR;
3517 pCryptKey->abKeyValue[1] = RSAENH_TLS1_VERSION_MINOR;
3518 break;
3520 setup_key(pCryptKey);
3522 break;
3524 default:
3525 /* MSDN: Algorithm not supported specified by Algid */
3526 SetLastError(NTE_BAD_ALGID);
3527 return FALSE;
3530 return *phKey != (HCRYPTKEY)INVALID_HANDLE_VALUE;
3533 /******************************************************************************
3534 * CPGenRandom (RSAENH.@)
3536 * Generate a random byte stream.
3538 * PARAMS
3539 * hProv [I] Key container that is used to generate random bytes.
3540 * dwLen [I] Specifies the number of requested random data bytes.
3541 * pbBuffer [O] Random bytes will be stored here.
3543 * RETURNS
3544 * Success: TRUE
3545 * Failure: FALSE
3547 BOOL WINAPI RSAENH_CPGenRandom(HCRYPTPROV hProv, DWORD dwLen, BYTE *pbBuffer)
3549 TRACE("(hProv=%08lx, dwLen=%d, pbBuffer=%p)\n", hProv, dwLen, pbBuffer);
3551 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3553 /* MSDN: hProv not containing valid context handle */
3554 SetLastError(NTE_BAD_UID);
3555 return FALSE;
3558 return gen_rand_impl(pbBuffer, dwLen);
3561 /******************************************************************************
3562 * CPGetHashParam (RSAENH.@)
3564 * Query parameters of an hash object.
3566 * PARAMS
3567 * hProv [I] The kea container, which the hash belongs to.
3568 * hHash [I] The hash object that is to be queried.
3569 * dwParam [I] Specifies the parameter that is to be queried.
3570 * pbData [I] Pointer to the buffer where the parameter value will be stored.
3571 * pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
3572 * dwFlags [I] None currently defined.
3574 * RETURNS
3575 * Success: TRUE
3576 * Failure: FALSE
3578 * NOTES
3579 * Valid dwParams are: HP_ALGID, HP_HASHSIZE, HP_HASHVALUE. The hash will be
3580 * finalized if HP_HASHVALUE is queried.
3582 BOOL WINAPI RSAENH_CPGetHashParam(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwParam, BYTE *pbData,
3583 DWORD *pdwDataLen, DWORD dwFlags)
3585 CRYPTHASH *pCryptHash;
3587 TRACE("(hProv=%08lx, hHash=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p, dwFlags=%08x)\n",
3588 hProv, hHash, dwParam, pbData, pdwDataLen, dwFlags);
3590 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3592 SetLastError(NTE_BAD_UID);
3593 return FALSE;
3596 if (dwFlags)
3598 SetLastError(NTE_BAD_FLAGS);
3599 return FALSE;
3602 if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH,
3603 (OBJECTHDR**)&pCryptHash))
3605 SetLastError(NTE_BAD_HASH);
3606 return FALSE;
3609 if (!pdwDataLen)
3611 SetLastError(ERROR_INVALID_PARAMETER);
3612 return FALSE;
3615 switch (dwParam)
3617 case HP_ALGID:
3618 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptHash->aiAlgid,
3619 sizeof(ALG_ID));
3621 case HP_HASHSIZE:
3622 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptHash->dwHashSize,
3623 sizeof(DWORD));
3625 case HP_HASHVAL:
3626 if (pCryptHash->aiAlgid == CALG_TLS1PRF) {
3627 return tls1_prf(hProv, pCryptHash->hKey, &pCryptHash->tpPRFParams.blobLabel,
3628 &pCryptHash->tpPRFParams.blobSeed, pbData, *pdwDataLen);
3631 if (pCryptHash->dwState != RSAENH_HASHSTATE_FINISHED)
3633 finalize_hash(pCryptHash);
3634 pCryptHash->dwState = RSAENH_HASHSTATE_FINISHED;
3637 if (!pbData)
3639 *pdwDataLen = pCryptHash->dwHashSize;
3640 return TRUE;
3643 return copy_param(pbData, pdwDataLen, pCryptHash->abHashValue,
3644 pCryptHash->dwHashSize);
3646 default:
3647 SetLastError(NTE_BAD_TYPE);
3648 return FALSE;
3652 /******************************************************************************
3653 * CPSetKeyParam (RSAENH.@)
3655 * Set a parameter of a key object
3657 * PARAMS
3658 * hProv [I] The key container to which the key belongs.
3659 * hKey [I] The key for which a parameter is to be set.
3660 * dwParam [I] Parameter type. See Notes.
3661 * pbData [I] Pointer to the parameter value.
3662 * dwFlags [I] Currently none defined.
3664 * RETURNS
3665 * Success: TRUE.
3666 * Failure: FALSE.
3668 * NOTES:
3669 * Defined dwParam types are:
3670 * - KP_MODE: Values MODE_CBC, MODE_ECB, MODE_CFB.
3671 * - KP_MODE_BITS: Shift width for cipher feedback mode. (Currently ignored by MS CSP's)
3672 * - KP_PERMISSIONS: Or'ed combination of CRYPT_ENCRYPT, CRYPT_DECRYPT,
3673 * CRYPT_EXPORT, CRYPT_READ, CRYPT_WRITE, CRYPT_MAC
3674 * - KP_IV: Initialization vector
3676 BOOL WINAPI RSAENH_CPSetKeyParam(HCRYPTPROV hProv, HCRYPTKEY hKey, DWORD dwParam, BYTE *pbData,
3677 DWORD dwFlags)
3679 CRYPTKEY *pCryptKey;
3681 TRACE("(hProv=%08lx, hKey=%08lx, dwParam=%08x, pbData=%p, dwFlags=%08x)\n", hProv, hKey,
3682 dwParam, pbData, dwFlags);
3684 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3686 SetLastError(NTE_BAD_UID);
3687 return FALSE;
3690 if (dwFlags) {
3691 SetLastError(NTE_BAD_FLAGS);
3692 return FALSE;
3695 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
3697 SetLastError(NTE_BAD_KEY);
3698 return FALSE;
3701 switch (dwParam) {
3702 case KP_PADDING:
3703 /* The MS providers only support PKCS5_PADDING */
3704 if (*(DWORD *)pbData != PKCS5_PADDING) {
3705 SetLastError(NTE_BAD_DATA);
3706 return FALSE;
3708 return TRUE;
3710 case KP_MODE:
3711 pCryptKey->dwMode = *(DWORD*)pbData;
3712 return TRUE;
3714 case KP_MODE_BITS:
3715 pCryptKey->dwModeBits = *(DWORD*)pbData;
3716 return TRUE;
3718 case KP_PERMISSIONS:
3720 DWORD perms = *(DWORD *)pbData;
3722 if ((perms & CRYPT_EXPORT) &&
3723 !(pCryptKey->dwPermissions & CRYPT_EXPORT))
3725 SetLastError(NTE_BAD_DATA);
3726 return FALSE;
3728 else if (!(perms & CRYPT_EXPORT) &&
3729 (pCryptKey->dwPermissions & CRYPT_EXPORT))
3731 /* Clearing the export permission appears to be ignored,
3732 * see tests.
3734 perms |= CRYPT_EXPORT;
3736 pCryptKey->dwPermissions = perms;
3737 return TRUE;
3740 case KP_IV:
3741 memcpy(pCryptKey->abInitVector, pbData, pCryptKey->dwBlockLen);
3742 setup_key(pCryptKey);
3743 return TRUE;
3745 case KP_SALT:
3746 switch (pCryptKey->aiAlgid) {
3747 case CALG_RC2:
3748 case CALG_RC4:
3750 KEYCONTAINER *pKeyContainer = get_key_container(pCryptKey->hProv);
3751 if (!pbData)
3753 SetLastError(ERROR_INVALID_PARAMETER);
3754 return FALSE;
3756 /* MSDN: the base provider always sets eleven bytes of
3757 * salt value.
3759 memcpy(pCryptKey->abKeyValue + pCryptKey->dwKeyLen,
3760 pbData, 11);
3761 pCryptKey->dwSaltLen = 11;
3762 setup_key(pCryptKey);
3763 /* After setting the salt value if the provider is not base or
3764 * strong the salt length will be reset. */
3765 if (pKeyContainer->dwPersonality != RSAENH_PERSONALITY_BASE &&
3766 pKeyContainer->dwPersonality != RSAENH_PERSONALITY_STRONG)
3767 pCryptKey->dwSaltLen = 0;
3768 break;
3770 default:
3771 SetLastError(NTE_BAD_KEY);
3772 return FALSE;
3774 return TRUE;
3776 case KP_SALT_EX:
3778 CRYPT_INTEGER_BLOB *blob = (CRYPT_INTEGER_BLOB *)pbData;
3780 /* salt length can't be greater than 184 bits = 24 bytes */
3781 if (blob->cbData > 24)
3783 SetLastError(NTE_BAD_DATA);
3784 return FALSE;
3786 memcpy(pCryptKey->abKeyValue + pCryptKey->dwKeyLen, blob->pbData,
3787 blob->cbData);
3788 pCryptKey->dwSaltLen = blob->cbData;
3789 setup_key(pCryptKey);
3790 return TRUE;
3793 case KP_EFFECTIVE_KEYLEN:
3794 switch (pCryptKey->aiAlgid) {
3795 case CALG_RC2:
3797 DWORD keylen, deflen;
3798 BOOL ret = TRUE;
3799 KEYCONTAINER *pKeyContainer = get_key_container(pCryptKey->hProv);
3801 if (!pbData)
3803 SetLastError(ERROR_INVALID_PARAMETER);
3804 return FALSE;
3806 keylen = *(DWORD *)pbData;
3807 if (!keylen || keylen > 1024)
3809 SetLastError(NTE_BAD_DATA);
3810 return FALSE;
3814 * The Base provider will force the key length to default
3815 * and set an error state if a key length different from
3816 * the default is tried.
3818 deflen = aProvEnumAlgsEx[pKeyContainer->dwPersonality]->dwDefaultLen;
3819 if (pKeyContainer->dwPersonality == RSAENH_PERSONALITY_BASE
3820 && keylen != deflen)
3822 keylen = deflen;
3823 SetLastError(NTE_BAD_DATA);
3824 ret = FALSE;
3826 pCryptKey->dwEffectiveKeyLen = keylen;
3827 setup_key(pCryptKey);
3828 return ret;
3830 default:
3831 SetLastError(NTE_BAD_TYPE);
3832 return FALSE;
3834 return TRUE;
3836 case KP_SCHANNEL_ALG:
3837 switch (((PSCHANNEL_ALG)pbData)->dwUse) {
3838 case SCHANNEL_ENC_KEY:
3839 memcpy(&pCryptKey->siSChannelInfo.saEncAlg, pbData, sizeof(SCHANNEL_ALG));
3840 break;
3842 case SCHANNEL_MAC_KEY:
3843 memcpy(&pCryptKey->siSChannelInfo.saMACAlg, pbData, sizeof(SCHANNEL_ALG));
3844 break;
3846 default:
3847 SetLastError(NTE_FAIL); /* FIXME: error code */
3848 return FALSE;
3850 return TRUE;
3852 case KP_CLIENT_RANDOM:
3853 return copy_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom, (PCRYPT_DATA_BLOB)pbData);
3855 case KP_SERVER_RANDOM:
3856 return copy_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom, (PCRYPT_DATA_BLOB)pbData);
3858 default:
3859 SetLastError(NTE_BAD_TYPE);
3860 return FALSE;
3864 /******************************************************************************
3865 * CPGetKeyParam (RSAENH.@)
3867 * Query a key parameter.
3869 * PARAMS
3870 * hProv [I] The key container, which the key belongs to.
3871 * hHash [I] The key object that is to be queried.
3872 * dwParam [I] Specifies the parameter that is to be queried.
3873 * pbData [I] Pointer to the buffer where the parameter value will be stored.
3874 * pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
3875 * dwFlags [I] None currently defined.
3877 * RETURNS
3878 * Success: TRUE
3879 * Failure: FALSE
3881 * NOTES
3882 * Defined dwParam types are:
3883 * - KP_MODE: Values MODE_CBC, MODE_ECB, MODE_CFB.
3884 * - KP_MODE_BITS: Shift width for cipher feedback mode.
3885 * (Currently ignored by MS CSP's - always eight)
3886 * - KP_PERMISSIONS: Or'ed combination of CRYPT_ENCRYPT, CRYPT_DECRYPT,
3887 * CRYPT_EXPORT, CRYPT_READ, CRYPT_WRITE, CRYPT_MAC
3888 * - KP_IV: Initialization vector.
3889 * - KP_KEYLEN: Bitwidth of the key.
3890 * - KP_BLOCKLEN: Size of a block cipher block.
3891 * - KP_SALT: Salt value.
3893 BOOL WINAPI RSAENH_CPGetKeyParam(HCRYPTPROV hProv, HCRYPTKEY hKey, DWORD dwParam, BYTE *pbData,
3894 DWORD *pdwDataLen, DWORD dwFlags)
3896 CRYPTKEY *pCryptKey;
3897 DWORD dwValue;
3899 TRACE("(hProv=%08lx, hKey=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p dwFlags=%08x)\n",
3900 hProv, hKey, dwParam, pbData, pdwDataLen, dwFlags);
3902 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3904 SetLastError(NTE_BAD_UID);
3905 return FALSE;
3908 if (dwFlags) {
3909 SetLastError(NTE_BAD_FLAGS);
3910 return FALSE;
3913 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
3915 SetLastError(NTE_BAD_KEY);
3916 return FALSE;
3919 switch (dwParam)
3921 case KP_IV:
3922 return copy_param(pbData, pdwDataLen, pCryptKey->abInitVector,
3923 pCryptKey->dwBlockLen);
3925 case KP_SALT:
3926 switch (pCryptKey->aiAlgid) {
3927 case CALG_RC2:
3928 case CALG_RC4:
3929 return copy_param(pbData, pdwDataLen,
3930 &pCryptKey->abKeyValue[pCryptKey->dwKeyLen],
3931 pCryptKey->dwSaltLen);
3932 default:
3933 SetLastError(NTE_BAD_KEY);
3934 return FALSE;
3937 case KP_PADDING:
3938 dwValue = PKCS5_PADDING;
3939 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwValue, sizeof(DWORD));
3941 case KP_KEYLEN:
3942 dwValue = pCryptKey->dwKeyLen << 3;
3943 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwValue, sizeof(DWORD));
3945 case KP_EFFECTIVE_KEYLEN:
3946 if (pCryptKey->dwEffectiveKeyLen)
3947 dwValue = pCryptKey->dwEffectiveKeyLen;
3948 else
3949 dwValue = pCryptKey->dwKeyLen << 3;
3950 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwValue, sizeof(DWORD));
3952 case KP_BLOCKLEN:
3953 dwValue = pCryptKey->dwBlockLen << 3;
3954 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwValue, sizeof(DWORD));
3956 case KP_MODE:
3957 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptKey->dwMode, sizeof(DWORD));
3959 case KP_MODE_BITS:
3960 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptKey->dwModeBits,
3961 sizeof(DWORD));
3963 case KP_PERMISSIONS:
3964 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptKey->dwPermissions,
3965 sizeof(DWORD));
3967 case KP_ALGID:
3968 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptKey->aiAlgid, sizeof(DWORD));
3970 default:
3971 SetLastError(NTE_BAD_TYPE);
3972 return FALSE;
3976 /******************************************************************************
3977 * CPGetProvParam (RSAENH.@)
3979 * Query a CSP parameter.
3981 * PARAMS
3982 * hProv [I] The key container that is to be queried.
3983 * dwParam [I] Specifies the parameter that is to be queried.
3984 * pbData [I] Pointer to the buffer where the parameter value will be stored.
3985 * pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
3986 * dwFlags [I] CRYPT_FIRST: Start enumeration (for PP_ENUMALGS{_EX}).
3988 * RETURNS
3989 * Success: TRUE
3990 * Failure: FALSE
3991 * NOTES:
3992 * Defined dwParam types:
3993 * - PP_CONTAINER: Name of the key container.
3994 * - PP_NAME: Name of the cryptographic service provider.
3995 * - PP_SIG_KEYSIZE_INC: RSA signature keywidth granularity in bits.
3996 * - PP_KEYX_KEYSIZE_INC: RSA key-exchange keywidth granularity in bits.
3997 * - PP_ENUMALGS{_EX}: Query provider capabilities.
3998 * - PP_KEYSET_SEC_DESCR: Retrieve security descriptor on container.
4000 BOOL WINAPI RSAENH_CPGetProvParam(HCRYPTPROV hProv, DWORD dwParam, BYTE *pbData,
4001 DWORD *pdwDataLen, DWORD dwFlags)
4003 KEYCONTAINER *pKeyContainer;
4004 PROV_ENUMALGS provEnumalgs;
4005 DWORD dwTemp;
4006 HKEY hKey;
4008 /* This is for dwParam PP_CRYPT_COUNT_KEY_USE.
4009 * IE6 SP1 asks for it in the 'About' dialog.
4010 * Returning this BLOB seems to satisfy IE. The marked 0x00 seem
4011 * to be 'don't care's. If you know anything more specific about
4012 * this provider parameter, please report to wine-devel@winehq.org */
4013 static const BYTE abWTF[96] = {
4014 0xb0, 0x25, 0x63, 0x86, 0x9c, 0xab, 0xb6, 0x37,
4015 0xe8, 0x82, /**/0x00,/**/ 0x72, 0x06, 0xb2, /**/0x00,/**/ 0x3b,
4016 0x60, 0x35, /**/0x00,/**/ 0x3b, 0x88, 0xce, /**/0x00,/**/ 0x82,
4017 0xbc, 0x7a, /**/0x00,/**/ 0xb7, 0x4f, 0x7e, /**/0x00,/**/ 0xde,
4018 0x92, 0xf1, /**/0x00,/**/ 0x83, 0xea, 0x5e, /**/0x00,/**/ 0xc8,
4019 0x12, 0x1e, 0xd4, 0x06, 0xf7, 0x66, /**/0x00,/**/ 0x01,
4020 0x29, 0xa4, /**/0x00,/**/ 0xf8, 0x24, 0x0c, /**/0x00,/**/ 0x33,
4021 0x06, 0x80, /**/0x00,/**/ 0x02, 0x46, 0x0b, /**/0x00,/**/ 0x6d,
4022 0x5b, 0xca, /**/0x00,/**/ 0x9a, 0x10, 0xf0, /**/0x00,/**/ 0x05,
4023 0x19, 0xd0, /**/0x00,/**/ 0x2c, 0xf6, 0x27, /**/0x00,/**/ 0xaa,
4024 0x7c, 0x6f, /**/0x00,/**/ 0xb9, 0xd8, 0x72, /**/0x00,/**/ 0x03,
4025 0xf3, 0x81, /**/0x00,/**/ 0xfa, 0xe8, 0x26, /**/0x00,/**/ 0xca
4028 TRACE("(hProv=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p, dwFlags=%08x)\n",
4029 hProv, dwParam, pbData, pdwDataLen, dwFlags);
4031 if (!pdwDataLen) {
4032 SetLastError(ERROR_INVALID_PARAMETER);
4033 return FALSE;
4036 if (!(pKeyContainer = get_key_container(hProv)))
4038 /* MSDN: hProv not containing valid context handle */
4039 return FALSE;
4042 switch (dwParam)
4044 case PP_CONTAINER:
4045 case PP_UNIQUE_CONTAINER:/* MSDN says we can return the same value as PP_CONTAINER */
4046 return copy_param(pbData, pdwDataLen, (const BYTE*)pKeyContainer->szName,
4047 strlen(pKeyContainer->szName)+1);
4049 case PP_NAME:
4050 return copy_param(pbData, pdwDataLen, (const BYTE*)pKeyContainer->szProvName,
4051 strlen(pKeyContainer->szProvName)+1);
4053 case PP_PROVTYPE:
4054 dwTemp = PROV_RSA_FULL;
4055 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
4057 case PP_KEYSPEC:
4058 dwTemp = AT_SIGNATURE | AT_KEYEXCHANGE;
4059 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
4061 case PP_KEYSET_TYPE:
4062 dwTemp = pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET;
4063 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
4065 case PP_KEYSTORAGE:
4066 dwTemp = CRYPT_SEC_DESCR;
4067 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
4069 case PP_SIG_KEYSIZE_INC:
4070 case PP_KEYX_KEYSIZE_INC:
4071 dwTemp = 8;
4072 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
4074 case PP_IMPTYPE:
4075 dwTemp = CRYPT_IMPL_SOFTWARE;
4076 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
4078 case PP_VERSION:
4079 dwTemp = 0x00000200;
4080 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
4082 case PP_ENUMCONTAINERS:
4083 if ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) pKeyContainer->dwEnumContainersCtr = 0;
4085 if (!pbData) {
4086 *pdwDataLen = (DWORD)MAX_PATH + 1;
4087 return TRUE;
4090 if (!open_container_key("", dwFlags, KEY_READ, &hKey))
4092 SetLastError(ERROR_NO_MORE_ITEMS);
4093 return FALSE;
4096 dwTemp = *pdwDataLen;
4097 switch (RegEnumKeyExA(hKey, pKeyContainer->dwEnumContainersCtr, (LPSTR)pbData, &dwTemp,
4098 NULL, NULL, NULL, NULL))
4100 case ERROR_MORE_DATA:
4101 *pdwDataLen = (DWORD)MAX_PATH + 1;
4103 case ERROR_SUCCESS:
4104 pKeyContainer->dwEnumContainersCtr++;
4105 RegCloseKey(hKey);
4106 return TRUE;
4108 case ERROR_NO_MORE_ITEMS:
4109 default:
4110 SetLastError(ERROR_NO_MORE_ITEMS);
4111 RegCloseKey(hKey);
4112 return FALSE;
4115 case PP_ENUMALGS:
4116 case PP_ENUMALGS_EX:
4117 if (((pKeyContainer->dwEnumAlgsCtr >= RSAENH_MAX_ENUMALGS-1) ||
4118 (!aProvEnumAlgsEx[pKeyContainer->dwPersonality]
4119 [pKeyContainer->dwEnumAlgsCtr+1].aiAlgid)) &&
4120 ((dwFlags & CRYPT_FIRST) != CRYPT_FIRST))
4122 SetLastError(ERROR_NO_MORE_ITEMS);
4123 return FALSE;
4126 if (dwParam == PP_ENUMALGS) {
4127 if (pbData && (*pdwDataLen >= sizeof(PROV_ENUMALGS)))
4128 pKeyContainer->dwEnumAlgsCtr = ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) ?
4129 0 : pKeyContainer->dwEnumAlgsCtr+1;
4131 provEnumalgs.aiAlgid = aProvEnumAlgsEx
4132 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].aiAlgid;
4133 provEnumalgs.dwBitLen = aProvEnumAlgsEx
4134 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].dwDefaultLen;
4135 provEnumalgs.dwNameLen = aProvEnumAlgsEx
4136 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].dwNameLen;
4137 memcpy(provEnumalgs.szName, aProvEnumAlgsEx
4138 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].szName,
4139 20*sizeof(CHAR));
4141 return copy_param(pbData, pdwDataLen, (const BYTE*)&provEnumalgs,
4142 sizeof(PROV_ENUMALGS));
4143 } else {
4144 if (pbData && (*pdwDataLen >= sizeof(PROV_ENUMALGS_EX)))
4145 pKeyContainer->dwEnumAlgsCtr = ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) ?
4146 0 : pKeyContainer->dwEnumAlgsCtr+1;
4148 return copy_param(pbData, pdwDataLen,
4149 (const BYTE*)&aProvEnumAlgsEx
4150 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr],
4151 sizeof(PROV_ENUMALGS_EX));
4154 case PP_CRYPT_COUNT_KEY_USE: /* Asked for by IE About dialog */
4155 return copy_param(pbData, pdwDataLen, abWTF, sizeof(abWTF));
4157 case PP_KEYSET_SEC_DESCR:
4159 SECURITY_DESCRIPTOR *sd;
4160 DWORD err, len, flags = (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET);
4162 if (!open_container_key(pKeyContainer->szName, flags, KEY_READ, &hKey))
4164 SetLastError(NTE_BAD_KEYSET);
4165 return FALSE;
4168 err = GetSecurityInfo(hKey, SE_REGISTRY_KEY, dwFlags, NULL, NULL, NULL, NULL, (void **)&sd);
4169 RegCloseKey(hKey);
4170 if (err)
4172 SetLastError(err);
4173 return FALSE;
4176 len = GetSecurityDescriptorLength(sd);
4177 if (*pdwDataLen >= len) memcpy(pbData, sd, len);
4178 else SetLastError(ERROR_INSUFFICIENT_BUFFER);
4179 *pdwDataLen = len;
4181 LocalFree(sd);
4182 return TRUE;
4185 default:
4186 /* MSDN: Unknown parameter number in dwParam */
4187 SetLastError(NTE_BAD_TYPE);
4188 return FALSE;
4192 /******************************************************************************
4193 * CPDeriveKey (RSAENH.@)
4195 * Derives a key from a hash value.
4197 * PARAMS
4198 * hProv [I] Key container for which a key is to be generated.
4199 * Algid [I] Crypto algorithm identifier for the key to be generated.
4200 * hBaseData [I] Hash from whose value the key will be derived.
4201 * dwFlags [I] See Notes.
4202 * phKey [O] The generated key.
4204 * RETURNS
4205 * Success: TRUE
4206 * Failure: FALSE
4208 * NOTES
4209 * Defined flags:
4210 * - CRYPT_EXPORTABLE: Key can be exported.
4211 * - CRYPT_NO_SALT: No salt is used for 40 bit keys.
4212 * - CRYPT_CREATE_SALT: Use remaining bits as salt value.
4214 BOOL WINAPI RSAENH_CPDeriveKey(HCRYPTPROV hProv, ALG_ID Algid, HCRYPTHASH hBaseData,
4215 DWORD dwFlags, HCRYPTKEY *phKey)
4217 CRYPTKEY *pCryptKey, *pMasterKey;
4218 CRYPTHASH *pCryptHash;
4219 BYTE abHashValue[RSAENH_MAX_HASH_SIZE*2];
4220 DWORD dwLen;
4222 TRACE("(hProv=%08lx, Algid=%d, hBaseData=%08lx, dwFlags=%08x phKey=%p)\n", hProv, Algid,
4223 hBaseData, dwFlags, phKey);
4225 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
4227 SetLastError(NTE_BAD_UID);
4228 return FALSE;
4231 if (!lookup_handle(&handle_table, hBaseData, RSAENH_MAGIC_HASH,
4232 (OBJECTHDR**)&pCryptHash))
4234 SetLastError(NTE_BAD_HASH);
4235 return FALSE;
4238 if (!phKey)
4240 SetLastError(ERROR_INVALID_PARAMETER);
4241 return FALSE;
4244 switch (GET_ALG_CLASS(Algid))
4246 case ALG_CLASS_DATA_ENCRYPT:
4248 int need_padding, copy_len;
4249 *phKey = new_key(hProv, Algid, dwFlags, &pCryptKey);
4250 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
4253 * We derive the key material from the hash.
4254 * If the hash value is not large enough for the claimed key, we have to construct
4255 * a larger binary value based on the hash. This is documented in MSDN: CryptDeriveKey.
4257 dwLen = RSAENH_MAX_HASH_SIZE;
4258 RSAENH_CPGetHashParam(pCryptHash->hProv, hBaseData, HP_HASHVAL, abHashValue, &dwLen, 0);
4261 * The usage of padding seems to vary from algorithm to algorithm.
4262 * For now the only different case found was for AES with 128 bit key.
4264 switch(Algid)
4266 case CALG_AES_128:
4267 /* To reduce the chance of regressions we will only deviate
4268 * from the old behavior for the tested hash lengths */
4269 if (dwLen == 16 || dwLen == 20)
4271 need_padding = 1;
4272 break;
4274 default:
4275 need_padding = dwLen < pCryptKey->dwKeyLen;
4278 copy_len = pCryptKey->dwKeyLen;
4279 if (need_padding)
4281 BYTE pad1[RSAENH_HMAC_DEF_PAD_LEN], pad2[RSAENH_HMAC_DEF_PAD_LEN];
4282 BYTE old_hashval[RSAENH_MAX_HASH_SIZE];
4283 DWORD i;
4285 memcpy(old_hashval, pCryptHash->abHashValue, RSAENH_MAX_HASH_SIZE);
4287 for (i=0; i<RSAENH_HMAC_DEF_PAD_LEN; i++) {
4288 pad1[i] = RSAENH_HMAC_DEF_IPAD_CHAR ^ (i<dwLen ? abHashValue[i] : 0);
4289 pad2[i] = RSAENH_HMAC_DEF_OPAD_CHAR ^ (i<dwLen ? abHashValue[i] : 0);
4292 init_hash(pCryptHash);
4293 update_hash(pCryptHash, pad1, RSAENH_HMAC_DEF_PAD_LEN);
4294 finalize_hash(pCryptHash);
4295 memcpy(abHashValue, pCryptHash->abHashValue, pCryptHash->dwHashSize);
4297 init_hash(pCryptHash);
4298 update_hash(pCryptHash, pad2, RSAENH_HMAC_DEF_PAD_LEN);
4299 finalize_hash(pCryptHash);
4300 memcpy(abHashValue+pCryptHash->dwHashSize, pCryptHash->abHashValue,
4301 pCryptHash->dwHashSize);
4303 memcpy(pCryptHash->abHashValue, old_hashval, RSAENH_MAX_HASH_SIZE);
4306 * Padding was not required, we have more hash than needed.
4307 * Do we need to use the remaining hash as salt?
4309 else if((dwFlags & CRYPT_CREATE_SALT) &&
4310 (Algid == CALG_RC2 || Algid == CALG_RC4))
4312 copy_len += pCryptKey->dwSaltLen;
4315 memcpy(pCryptKey->abKeyValue, abHashValue,
4316 RSAENH_MIN(copy_len, sizeof(pCryptKey->abKeyValue)));
4317 break;
4319 case ALG_CLASS_MSG_ENCRYPT:
4320 if (!lookup_handle(&handle_table, pCryptHash->hKey, RSAENH_MAGIC_KEY,
4321 (OBJECTHDR**)&pMasterKey))
4323 SetLastError(NTE_FAIL); /* FIXME error code */
4324 return FALSE;
4327 switch (Algid)
4329 /* See RFC 2246, chapter 6.3 Key calculation */
4330 case CALG_SCHANNEL_ENC_KEY:
4331 if (!pMasterKey->siSChannelInfo.saEncAlg.Algid ||
4332 !pMasterKey->siSChannelInfo.saEncAlg.cBits)
4334 SetLastError(NTE_BAD_FLAGS);
4335 return FALSE;
4337 *phKey = new_key(hProv, pMasterKey->siSChannelInfo.saEncAlg.Algid,
4338 MAKELONG(LOWORD(dwFlags),pMasterKey->siSChannelInfo.saEncAlg.cBits),
4339 &pCryptKey);
4340 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
4341 memcpy(pCryptKey->abKeyValue,
4342 pCryptHash->abHashValue + (
4343 2 * (pMasterKey->siSChannelInfo.saMACAlg.cBits / 8) +
4344 ((dwFlags & CRYPT_SERVER) ?
4345 (pMasterKey->siSChannelInfo.saEncAlg.cBits / 8) : 0)),
4346 pMasterKey->siSChannelInfo.saEncAlg.cBits / 8);
4347 memcpy(pCryptKey->abInitVector,
4348 pCryptHash->abHashValue + (
4349 2 * (pMasterKey->siSChannelInfo.saMACAlg.cBits / 8) +
4350 2 * (pMasterKey->siSChannelInfo.saEncAlg.cBits / 8) +
4351 ((dwFlags & CRYPT_SERVER) ? pCryptKey->dwBlockLen : 0)),
4352 pCryptKey->dwBlockLen);
4353 break;
4355 case CALG_SCHANNEL_MAC_KEY:
4356 *phKey = new_key(hProv, Algid,
4357 MAKELONG(LOWORD(dwFlags),pMasterKey->siSChannelInfo.saMACAlg.cBits),
4358 &pCryptKey);
4359 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
4360 memcpy(pCryptKey->abKeyValue,
4361 pCryptHash->abHashValue + ((dwFlags & CRYPT_SERVER) ?
4362 pMasterKey->siSChannelInfo.saMACAlg.cBits / 8 : 0),
4363 pMasterKey->siSChannelInfo.saMACAlg.cBits / 8);
4364 break;
4366 default:
4367 SetLastError(NTE_BAD_ALGID);
4368 return FALSE;
4370 break;
4372 default:
4373 SetLastError(NTE_BAD_ALGID);
4374 return FALSE;
4377 setup_key(pCryptKey);
4378 return TRUE;
4381 /******************************************************************************
4382 * CPGetUserKey (RSAENH.@)
4384 * Returns a handle to the user's private key-exchange- or signature-key.
4386 * PARAMS
4387 * hProv [I] The key container from which a user key is requested.
4388 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
4389 * phUserKey [O] Handle to the requested key or INVALID_HANDLE_VALUE in case of failure.
4391 * RETURNS
4392 * Success: TRUE.
4393 * Failure: FALSE.
4395 * NOTE
4396 * A newly created key container does not contain private user key. Create them with CPGenKey.
4398 BOOL WINAPI RSAENH_CPGetUserKey(HCRYPTPROV hProv, DWORD dwKeySpec, HCRYPTKEY *phUserKey)
4400 KEYCONTAINER *pKeyContainer;
4402 TRACE("(hProv=%08lx, dwKeySpec=%08x, phUserKey=%p)\n", hProv, dwKeySpec, phUserKey);
4404 if (!(pKeyContainer = get_key_container(hProv)))
4406 /* MSDN: hProv not containing valid context handle */
4407 return FALSE;
4410 switch (dwKeySpec)
4412 case AT_KEYEXCHANGE:
4413 copy_handle(&handle_table, pKeyContainer->hKeyExchangeKeyPair, RSAENH_MAGIC_KEY,
4414 phUserKey);
4415 break;
4417 case AT_SIGNATURE:
4418 copy_handle(&handle_table, pKeyContainer->hSignatureKeyPair, RSAENH_MAGIC_KEY,
4419 phUserKey);
4420 break;
4422 default:
4423 *phUserKey = (HCRYPTKEY)INVALID_HANDLE_VALUE;
4426 if (*phUserKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
4428 /* MSDN: dwKeySpec parameter specifies nonexistent key */
4429 SetLastError(NTE_NO_KEY);
4430 return FALSE;
4433 return TRUE;
4436 /******************************************************************************
4437 * CPHashData (RSAENH.@)
4439 * Updates a hash object with the given data.
4441 * PARAMS
4442 * hProv [I] Key container to which the hash object belongs.
4443 * hHash [I] Hash object which is to be updated.
4444 * pbData [I] Pointer to data with which the hash object is to be updated.
4445 * dwDataLen [I] Length of the data.
4446 * dwFlags [I] Currently none defined.
4448 * RETURNS
4449 * Success: TRUE.
4450 * Failure: FALSE.
4452 * NOTES
4453 * The actual hash value is queried with CPGetHashParam, which will finalize
4454 * the hash. Updating a finalized hash will fail with a last error NTE_BAD_HASH_STATE.
4456 BOOL WINAPI RSAENH_CPHashData(HCRYPTPROV hProv, HCRYPTHASH hHash, const BYTE *pbData,
4457 DWORD dwDataLen, DWORD dwFlags)
4459 CRYPTHASH *pCryptHash;
4461 TRACE("(hProv=%08lx, hHash=%08lx, pbData=%p, dwDataLen=%d, dwFlags=%08x)\n",
4462 hProv, hHash, pbData, dwDataLen, dwFlags);
4464 if (dwFlags & ~CRYPT_USERDATA)
4466 SetLastError(NTE_BAD_FLAGS);
4467 return FALSE;
4470 if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH,
4471 (OBJECTHDR**)&pCryptHash))
4473 SetLastError(NTE_BAD_HASH);
4474 return FALSE;
4477 if (!get_algid_info(hProv, pCryptHash->aiAlgid) || pCryptHash->aiAlgid == CALG_SSL3_SHAMD5)
4479 SetLastError(NTE_BAD_ALGID);
4480 return FALSE;
4483 if (pCryptHash->dwState != RSAENH_HASHSTATE_HASHING)
4485 SetLastError(NTE_BAD_HASH_STATE);
4486 return FALSE;
4489 update_hash(pCryptHash, pbData, dwDataLen);
4490 return TRUE;
4493 /******************************************************************************
4494 * CPHashSessionKey (RSAENH.@)
4496 * Updates a hash object with the binary representation of a symmetric key.
4498 * PARAMS
4499 * hProv [I] Key container to which the hash object belongs.
4500 * hHash [I] Hash object which is to be updated.
4501 * hKey [I] The symmetric key, whose binary value will be added to the hash.
4502 * dwFlags [I] CRYPT_LITTLE_ENDIAN, if the binary key value shall be interpreted as little endian.
4504 * RETURNS
4505 * Success: TRUE.
4506 * Failure: FALSE.
4508 BOOL WINAPI RSAENH_CPHashSessionKey(HCRYPTPROV hProv, HCRYPTHASH hHash, HCRYPTKEY hKey,
4509 DWORD dwFlags)
4511 BYTE abKeyValue[RSAENH_MAX_KEY_SIZE], bTemp;
4512 CRYPTKEY *pKey;
4513 DWORD i;
4515 TRACE("(hProv=%08lx, hHash=%08lx, hKey=%08lx, dwFlags=%08x)\n", hProv, hHash, hKey, dwFlags);
4517 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pKey) ||
4518 (GET_ALG_CLASS(pKey->aiAlgid) != ALG_CLASS_DATA_ENCRYPT))
4520 SetLastError(NTE_BAD_KEY);
4521 return FALSE;
4524 if (dwFlags & ~CRYPT_LITTLE_ENDIAN) {
4525 SetLastError(NTE_BAD_FLAGS);
4526 return FALSE;
4529 memcpy(abKeyValue, pKey->abKeyValue, pKey->dwKeyLen);
4530 if (!(dwFlags & CRYPT_LITTLE_ENDIAN)) {
4531 for (i=0; i<pKey->dwKeyLen/2; i++) {
4532 bTemp = abKeyValue[i];
4533 abKeyValue[i] = abKeyValue[pKey->dwKeyLen-i-1];
4534 abKeyValue[pKey->dwKeyLen-i-1] = bTemp;
4538 return RSAENH_CPHashData(hProv, hHash, abKeyValue, pKey->dwKeyLen, 0);
4541 /******************************************************************************
4542 * CPReleaseContext (RSAENH.@)
4544 * Release a key container.
4546 * PARAMS
4547 * hProv [I] Key container to be released.
4548 * dwFlags [I] Currently none defined.
4550 * RETURNS
4551 * Success: TRUE
4552 * Failure: FALSE
4554 BOOL WINAPI RSAENH_CPReleaseContext(HCRYPTPROV hProv, DWORD dwFlags)
4556 TRACE("(hProv=%08lx, dwFlags=%08x)\n", hProv, dwFlags);
4558 if (!release_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
4560 /* MSDN: hProv not containing valid context handle */
4561 SetLastError(NTE_BAD_UID);
4562 return FALSE;
4565 if (dwFlags) {
4566 SetLastError(NTE_BAD_FLAGS);
4567 return FALSE;
4570 return TRUE;
4573 /******************************************************************************
4574 * CPSetHashParam (RSAENH.@)
4576 * Set a parameter of a hash object
4578 * PARAMS
4579 * hProv [I] The key container to which the key belongs.
4580 * hHash [I] The hash object for which a parameter is to be set.
4581 * dwParam [I] Parameter type. See Notes.
4582 * pbData [I] Pointer to the parameter value.
4583 * dwFlags [I] Currently none defined.
4585 * RETURNS
4586 * Success: TRUE.
4587 * Failure: FALSE.
4589 * NOTES
4590 * Currently only the HP_HMAC_INFO dwParam type is defined.
4591 * The HMAC_INFO struct will be deep copied into the hash object.
4592 * See Internet RFC 2104 for details on the HMAC algorithm.
4594 BOOL WINAPI RSAENH_CPSetHashParam(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwParam,
4595 BYTE *pbData, DWORD dwFlags)
4597 CRYPTHASH *pCryptHash;
4598 CRYPTKEY *pCryptKey;
4599 DWORD i;
4601 TRACE("(hProv=%08lx, hHash=%08lx, dwParam=%08x, pbData=%p, dwFlags=%08x)\n",
4602 hProv, hHash, dwParam, pbData, dwFlags);
4604 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
4606 SetLastError(NTE_BAD_UID);
4607 return FALSE;
4610 if (dwFlags) {
4611 SetLastError(NTE_BAD_FLAGS);
4612 return FALSE;
4615 if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH,
4616 (OBJECTHDR**)&pCryptHash))
4618 SetLastError(NTE_BAD_HASH);
4619 return FALSE;
4622 switch (dwParam) {
4623 case HP_HMAC_INFO:
4624 free_hmac_info(pCryptHash->pHMACInfo);
4625 if (!copy_hmac_info(&pCryptHash->pHMACInfo, (PHMAC_INFO)pbData)) return FALSE;
4627 if (!lookup_handle(&handle_table, pCryptHash->hKey, RSAENH_MAGIC_KEY,
4628 (OBJECTHDR**)&pCryptKey))
4630 SetLastError(NTE_FAIL); /* FIXME: correct error code? */
4631 return FALSE;
4634 if (pCryptKey->aiAlgid == CALG_HMAC && !pCryptKey->dwKeyLen) {
4635 HCRYPTHASH hKeyHash;
4636 DWORD keyLen;
4638 if (!RSAENH_CPCreateHash(hProv, ((PHMAC_INFO)pbData)->HashAlgid, 0, 0,
4639 &hKeyHash))
4640 return FALSE;
4641 if (!RSAENH_CPHashData(hProv, hKeyHash, pCryptKey->blobHmacKey.pbData,
4642 pCryptKey->blobHmacKey.cbData, 0))
4644 RSAENH_CPDestroyHash(hProv, hKeyHash);
4645 return FALSE;
4647 keyLen = sizeof(pCryptKey->abKeyValue);
4648 if (!RSAENH_CPGetHashParam(hProv, hKeyHash, HP_HASHVAL, pCryptKey->abKeyValue,
4649 &keyLen, 0))
4651 RSAENH_CPDestroyHash(hProv, hKeyHash);
4652 return FALSE;
4654 pCryptKey->dwKeyLen = keyLen;
4655 RSAENH_CPDestroyHash(hProv, hKeyHash);
4657 for (i=0; i<RSAENH_MIN(pCryptKey->dwKeyLen,pCryptHash->pHMACInfo->cbInnerString); i++) {
4658 pCryptHash->pHMACInfo->pbInnerString[i] ^= pCryptKey->abKeyValue[i];
4660 for (i=0; i<RSAENH_MIN(pCryptKey->dwKeyLen,pCryptHash->pHMACInfo->cbOuterString); i++) {
4661 pCryptHash->pHMACInfo->pbOuterString[i] ^= pCryptKey->abKeyValue[i];
4664 init_hash(pCryptHash);
4665 return TRUE;
4667 case HP_HASHVAL:
4668 memcpy(pCryptHash->abHashValue, pbData, pCryptHash->dwHashSize);
4669 pCryptHash->dwState = RSAENH_HASHSTATE_FINISHED;
4670 return TRUE;
4672 case HP_TLS1PRF_SEED:
4673 return copy_data_blob(&pCryptHash->tpPRFParams.blobSeed, (PCRYPT_DATA_BLOB)pbData);
4675 case HP_TLS1PRF_LABEL:
4676 return copy_data_blob(&pCryptHash->tpPRFParams.blobLabel, (PCRYPT_DATA_BLOB)pbData);
4678 default:
4679 SetLastError(NTE_BAD_TYPE);
4680 return FALSE;
4684 /******************************************************************************
4685 * CPSetProvParam (RSAENH.@)
4687 BOOL WINAPI RSAENH_CPSetProvParam(HCRYPTPROV hProv, DWORD dwParam, BYTE *pbData, DWORD dwFlags)
4689 KEYCONTAINER *pKeyContainer;
4690 HKEY hKey;
4692 TRACE("(hProv=%08lx, dwParam=%08x, pbData=%p, dwFlags=%08x)\n", hProv, dwParam, pbData, dwFlags);
4694 if (!(pKeyContainer = get_key_container(hProv)))
4695 return FALSE;
4697 switch (dwParam)
4699 case PP_KEYSET_SEC_DESCR:
4701 SECURITY_DESCRIPTOR *sd = (SECURITY_DESCRIPTOR *)pbData;
4702 DWORD err, flags = (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET);
4703 BOOL def, present;
4704 REGSAM access = WRITE_DAC | WRITE_OWNER | ACCESS_SYSTEM_SECURITY;
4705 PSID owner = NULL, group = NULL;
4706 PACL dacl = NULL, sacl = NULL;
4708 if (!open_container_key(pKeyContainer->szName, flags, access, &hKey))
4710 SetLastError(NTE_BAD_KEYSET);
4711 return FALSE;
4714 if ((dwFlags & OWNER_SECURITY_INFORMATION && !GetSecurityDescriptorOwner(sd, &owner, &def)) ||
4715 (dwFlags & GROUP_SECURITY_INFORMATION && !GetSecurityDescriptorGroup(sd, &group, &def)) ||
4716 (dwFlags & DACL_SECURITY_INFORMATION && !GetSecurityDescriptorDacl(sd, &present, &dacl, &def)) ||
4717 (dwFlags & SACL_SECURITY_INFORMATION && !GetSecurityDescriptorSacl(sd, &present, &sacl, &def)))
4719 RegCloseKey(hKey);
4720 return FALSE;
4723 err = SetSecurityInfo(hKey, SE_REGISTRY_KEY, dwFlags, owner, group, dacl, sacl);
4724 RegCloseKey(hKey);
4725 if (err)
4727 SetLastError(err);
4728 return FALSE;
4730 return TRUE;
4732 default:
4733 FIXME("unimplemented parameter %08x\n", dwParam);
4734 return FALSE;
4738 /******************************************************************************
4739 * CPSignHash (RSAENH.@)
4741 * Sign a hash object
4743 * PARAMS
4744 * hProv [I] The key container, to which the hash object belongs.
4745 * hHash [I] The hash object to be signed.
4746 * dwKeySpec [I] AT_SIGNATURE or AT_KEYEXCHANGE: Key used to generate the signature.
4747 * sDescription [I] Should be NULL for security reasons.
4748 * dwFlags [I] 0, CRYPT_NOHASHOID or CRYPT_X931_FORMAT: Format of the signature.
4749 * pbSignature [O] Buffer, to which the signature will be stored. May be NULL to query SigLen.
4750 * pdwSigLen [I/O] Size of the buffer (in), Length of the signature (out)
4752 * RETURNS
4753 * Success: TRUE
4754 * Failure: FALSE
4756 BOOL WINAPI RSAENH_CPSignHash(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwKeySpec,
4757 LPCWSTR sDescription, DWORD dwFlags, BYTE *pbSignature,
4758 DWORD *pdwSigLen)
4760 HCRYPTKEY hCryptKey = (HCRYPTKEY)INVALID_HANDLE_VALUE;
4761 CRYPTKEY *pCryptKey;
4762 DWORD dwHashLen;
4763 BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
4764 ALG_ID aiAlgid;
4765 BOOL ret = FALSE;
4767 TRACE("(hProv=%08lx, hHash=%08lx, dwKeySpec=%08x, sDescription=%s, dwFlags=%08x, "
4768 "pbSignature=%p, pdwSigLen=%p)\n", hProv, hHash, dwKeySpec, debugstr_w(sDescription),
4769 dwFlags, pbSignature, pdwSigLen);
4771 if (dwFlags & ~(CRYPT_NOHASHOID|CRYPT_X931_FORMAT)) {
4772 SetLastError(NTE_BAD_FLAGS);
4773 return FALSE;
4776 if (!RSAENH_CPGetUserKey(hProv, dwKeySpec, &hCryptKey)) return FALSE;
4778 if (!lookup_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY,
4779 (OBJECTHDR**)&pCryptKey))
4781 SetLastError(NTE_NO_KEY);
4782 goto out;
4785 if (!pbSignature) {
4786 *pdwSigLen = pCryptKey->dwKeyLen;
4787 ret = TRUE;
4788 goto out;
4790 if (pCryptKey->dwKeyLen > *pdwSigLen)
4792 SetLastError(ERROR_MORE_DATA);
4793 *pdwSigLen = pCryptKey->dwKeyLen;
4794 goto out;
4796 *pdwSigLen = pCryptKey->dwKeyLen;
4798 if (sDescription) {
4799 if (!RSAENH_CPHashData(hProv, hHash, (const BYTE*)sDescription,
4800 (DWORD)lstrlenW(sDescription)*sizeof(WCHAR), 0))
4802 goto out;
4806 dwHashLen = sizeof(DWORD);
4807 if (!RSAENH_CPGetHashParam(hProv, hHash, HP_ALGID, (BYTE*)&aiAlgid, &dwHashLen, 0)) goto out;
4809 dwHashLen = RSAENH_MAX_HASH_SIZE;
4810 if (!RSAENH_CPGetHashParam(hProv, hHash, HP_HASHVAL, abHashValue, &dwHashLen, 0)) goto out;
4813 if (!build_hash_signature(pbSignature, *pdwSigLen, aiAlgid, abHashValue, dwHashLen, dwFlags)) {
4814 goto out;
4817 ret = encrypt_block_impl(pCryptKey->aiAlgid, PK_PRIVATE, &pCryptKey->context, pbSignature, pbSignature, RSAENH_ENCRYPT);
4818 out:
4819 RSAENH_CPDestroyKey(hProv, hCryptKey);
4820 return ret;
4823 /******************************************************************************
4824 * CPVerifySignature (RSAENH.@)
4826 * Verify the signature of a hash object.
4828 * PARAMS
4829 * hProv [I] The key container, to which the hash belongs.
4830 * hHash [I] The hash for which the signature is verified.
4831 * pbSignature [I] The binary signature.
4832 * dwSigLen [I] Length of the signature BLOB.
4833 * hPubKey [I] Public key used to verify the signature.
4834 * sDescription [I] Should be NULL for security reasons.
4835 * dwFlags [I] 0, CRYPT_NOHASHOID or CRYPT_X931_FORMAT: Format of the signature.
4837 * RETURNS
4838 * Success: TRUE (Signature is valid)
4839 * Failure: FALSE (GetLastError() == NTE_BAD_SIGNATURE, if signature is invalid)
4841 BOOL WINAPI RSAENH_CPVerifySignature(HCRYPTPROV hProv, HCRYPTHASH hHash, const BYTE *pbSignature,
4842 DWORD dwSigLen, HCRYPTKEY hPubKey, LPCWSTR sDescription,
4843 DWORD dwFlags)
4845 BYTE *pbConstructed = NULL, *pbDecrypted = NULL;
4846 CRYPTKEY *pCryptKey;
4847 DWORD dwHashLen;
4848 ALG_ID aiAlgid;
4849 BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
4850 BOOL res = FALSE;
4852 TRACE("(hProv=%08lx, hHash=%08lx, pbSignature=%p, dwSigLen=%d, hPubKey=%08lx, sDescription=%s, "
4853 "dwFlags=%08x)\n", hProv, hHash, pbSignature, dwSigLen, hPubKey, debugstr_w(sDescription),
4854 dwFlags);
4856 if (dwFlags & ~(CRYPT_NOHASHOID|CRYPT_X931_FORMAT)) {
4857 SetLastError(NTE_BAD_FLAGS);
4858 return FALSE;
4861 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
4863 SetLastError(NTE_BAD_UID);
4864 return FALSE;
4867 if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY,
4868 (OBJECTHDR**)&pCryptKey))
4870 SetLastError(NTE_BAD_KEY);
4871 return FALSE;
4874 /* in Microsoft implementation, the signature length is checked before
4875 * the signature pointer.
4877 if (dwSigLen != pCryptKey->dwKeyLen)
4879 SetLastError(NTE_BAD_SIGNATURE);
4880 return FALSE;
4883 if (!hHash || !pbSignature)
4885 SetLastError(ERROR_INVALID_PARAMETER);
4886 return FALSE;
4889 if (sDescription) {
4890 if (!RSAENH_CPHashData(hProv, hHash, (const BYTE*)sDescription,
4891 (DWORD)lstrlenW(sDescription)*sizeof(WCHAR), 0))
4893 return FALSE;
4897 dwHashLen = sizeof(DWORD);
4898 if (!RSAENH_CPGetHashParam(hProv, hHash, HP_ALGID, (BYTE*)&aiAlgid, &dwHashLen, 0)) return FALSE;
4900 dwHashLen = RSAENH_MAX_HASH_SIZE;
4901 if (!RSAENH_CPGetHashParam(hProv, hHash, HP_HASHVAL, abHashValue, &dwHashLen, 0)) return FALSE;
4903 pbConstructed = HeapAlloc(GetProcessHeap(), 0, dwSigLen);
4904 if (!pbConstructed) {
4905 SetLastError(NTE_NO_MEMORY);
4906 goto cleanup;
4909 pbDecrypted = HeapAlloc(GetProcessHeap(), 0, dwSigLen);
4910 if (!pbDecrypted) {
4911 SetLastError(NTE_NO_MEMORY);
4912 goto cleanup;
4915 if (!encrypt_block_impl(pCryptKey->aiAlgid, PK_PUBLIC, &pCryptKey->context, pbSignature, pbDecrypted,
4916 RSAENH_DECRYPT))
4918 goto cleanup;
4921 if (build_hash_signature(pbConstructed, dwSigLen, aiAlgid, abHashValue, dwHashLen, dwFlags) &&
4922 !memcmp(pbDecrypted, pbConstructed, dwSigLen)) {
4923 res = TRUE;
4924 goto cleanup;
4927 if (!(dwFlags & CRYPT_NOHASHOID) &&
4928 build_hash_signature(pbConstructed, dwSigLen, aiAlgid, abHashValue, dwHashLen, dwFlags|CRYPT_NOHASHOID) &&
4929 !memcmp(pbDecrypted, pbConstructed, dwSigLen)) {
4930 res = TRUE;
4931 goto cleanup;
4934 SetLastError(NTE_BAD_SIGNATURE);
4936 cleanup:
4937 HeapFree(GetProcessHeap(), 0, pbConstructed);
4938 HeapFree(GetProcessHeap(), 0, pbDecrypted);
4939 return res;
4942 /******************************************************************************
4943 * DllRegisterServer (RSAENH.@)
4945 HRESULT WINAPI DllRegisterServer(void)
4947 return __wine_register_resources( instance );
4950 /******************************************************************************
4951 * DllUnregisterServer (RSAENH.@)
4953 HRESULT WINAPI DllUnregisterServer(void)
4955 return __wine_unregister_resources( instance );