dinput: Clear action mapping with SetDataFormat().
[wine.git] / dlls / rsaenh / rsaenh.c
blob38c4831864119617a5c633c531f5bf8921874025
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 <stdarg.h>
26 #include <stdio.h>
28 #include "windef.h"
29 #include "winbase.h"
30 #include "winreg.h"
31 #include "wincrypt.h"
32 #include "handle.h"
33 #include "implglue.h"
34 #include "objbase.h"
35 #include "rpcproxy.h"
36 #include "aclapi.h"
37 #include "wine/debug.h"
39 WINE_DEFAULT_DEBUG_CHANNEL(crypt);
41 static HINSTANCE instance;
43 /******************************************************************************
44 * CRYPTHASH - hash objects
46 #define RSAENH_MAGIC_HASH 0x85938417u
47 #define RSAENH_HASHSTATE_HASHING 1
48 #define RSAENH_HASHSTATE_FINISHED 2
49 typedef struct _RSAENH_TLS1PRF_PARAMS
51 CRYPT_DATA_BLOB blobLabel;
52 CRYPT_DATA_BLOB blobSeed;
53 } RSAENH_TLS1PRF_PARAMS;
55 typedef struct tagCRYPTHASH
57 OBJECTHDR header;
58 ALG_ID aiAlgid;
59 HCRYPTKEY hKey;
60 HCRYPTPROV hProv;
61 DWORD dwHashSize;
62 DWORD dwState;
63 HASH_CONTEXT context;
64 BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
65 PHMAC_INFO pHMACInfo;
66 RSAENH_TLS1PRF_PARAMS tpPRFParams;
67 } CRYPTHASH;
69 /******************************************************************************
70 * CRYPTKEY - key objects
72 #define RSAENH_MAGIC_KEY 0x73620457u
73 #define RSAENH_MAX_KEY_SIZE 64
74 #define RSAENH_MAX_BLOCK_SIZE 24
75 #define RSAENH_KEYSTATE_IDLE 0
76 #define RSAENH_KEYSTATE_ENCRYPTING 1
77 #define RSAENH_KEYSTATE_MASTERKEY 2
78 typedef struct _RSAENH_SCHANNEL_INFO
80 SCHANNEL_ALG saEncAlg;
81 SCHANNEL_ALG saMACAlg;
82 CRYPT_DATA_BLOB blobClientRandom;
83 CRYPT_DATA_BLOB blobServerRandom;
84 } RSAENH_SCHANNEL_INFO;
86 typedef struct tagCRYPTKEY
88 OBJECTHDR header;
89 ALG_ID aiAlgid;
90 HCRYPTPROV hProv;
91 DWORD dwMode;
92 DWORD dwModeBits;
93 DWORD dwPermissions;
94 DWORD dwKeyLen;
95 DWORD dwEffectiveKeyLen;
96 DWORD dwSaltLen;
97 DWORD dwBlockLen;
98 DWORD dwState;
99 KEY_CONTEXT context;
100 BYTE abKeyValue[RSAENH_MAX_KEY_SIZE];
101 BYTE abInitVector[RSAENH_MAX_BLOCK_SIZE];
102 BYTE abChainVector[RSAENH_MAX_BLOCK_SIZE];
103 RSAENH_SCHANNEL_INFO siSChannelInfo;
104 CRYPT_DATA_BLOB blobHmacKey;
105 } CRYPTKEY;
107 /******************************************************************************
108 * KEYCONTAINER - key containers
110 #define RSAENH_PERSONALITY_BASE 0u
111 #define RSAENH_PERSONALITY_STRONG 1u
112 #define RSAENH_PERSONALITY_ENHANCED 2u
113 #define RSAENH_PERSONALITY_SCHANNEL 3u
114 #define RSAENH_PERSONALITY_AES 4u
116 #define RSAENH_MAGIC_CONTAINER 0x26384993u
117 typedef struct tagKEYCONTAINER
119 OBJECTHDR header;
120 DWORD dwFlags;
121 DWORD dwPersonality;
122 DWORD dwEnumAlgsCtr;
123 DWORD dwEnumContainersCtr;
124 CHAR szName[MAX_PATH];
125 CHAR szProvName[MAX_PATH];
126 HCRYPTKEY hKeyExchangeKeyPair;
127 HCRYPTKEY hSignatureKeyPair;
128 } KEYCONTAINER;
130 /******************************************************************************
131 * Some magic constants
133 #define RSAENH_ENCRYPT 1
134 #define RSAENH_DECRYPT 0
135 #define RSAENH_HMAC_DEF_IPAD_CHAR 0x36
136 #define RSAENH_HMAC_DEF_OPAD_CHAR 0x5c
137 #define RSAENH_HMAC_DEF_PAD_LEN 64
138 #define RSAENH_HMAC_BLOCK_LEN 64
139 #define RSAENH_DES_EFFECTIVE_KEYLEN 56
140 #define RSAENH_DES_STORAGE_KEYLEN 64
141 #define RSAENH_3DES112_EFFECTIVE_KEYLEN 112
142 #define RSAENH_3DES112_STORAGE_KEYLEN 128
143 #define RSAENH_3DES_EFFECTIVE_KEYLEN 168
144 #define RSAENH_3DES_STORAGE_KEYLEN 192
145 #define RSAENH_MAGIC_RSA2 0x32415352
146 #define RSAENH_MAGIC_RSA1 0x31415352
147 #define RSAENH_PKC_BLOCKTYPE 0x02
148 #define RSAENH_SSL3_VERSION_MAJOR 3
149 #define RSAENH_SSL3_VERSION_MINOR 0
150 #define RSAENH_TLS1_VERSION_MAJOR 3
151 #define RSAENH_TLS1_VERSION_MINOR 1
152 #define RSAENH_REGKEY "Software\\Wine\\Crypto\\RSA\\%s"
154 #define RSAENH_MIN(a,b) ((a)<(b)?(a):(b))
155 /******************************************************************************
156 * aProvEnumAlgsEx - Defines the capabilities of the CSP personalities.
158 #define RSAENH_MAX_ENUMALGS 24
159 #define RSAENH_PCT1_SSL2_SSL3_TLS1 (CRYPT_FLAG_PCT1|CRYPT_FLAG_SSL2|CRYPT_FLAG_SSL3|CRYPT_FLAG_TLS1)
160 #define S(s) sizeof(s), s
161 static const PROV_ENUMALGS_EX aProvEnumAlgsEx[5][RSAENH_MAX_ENUMALGS+1] =
164 {CALG_RC2, 40, 40, 56, 0, S("RC2"), S("RSA Data Security's RC2")},
165 {CALG_RC4, 40, 40, 56, 0, S("RC4"), S("RSA Data Security's RC4")},
166 {CALG_DES, 56, 56, 56, 0, S("DES"), S("Data Encryption Standard (DES)")},
167 {CALG_SHA, 160, 160, 160, CRYPT_FLAG_SIGNING, S("SHA-1"), S("Secure Hash Algorithm (SHA-1)")},
168 {CALG_MD2, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD2"), S("Message Digest 2 (MD2)")},
169 {CALG_MD4, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD4"), S("Message Digest 4 (MD4)")},
170 {CALG_MD5, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD5"), S("Message Digest 5 (MD5)")},
171 {CALG_SSL3_SHAMD5, 288, 288, 288, 0, S("SSL3 SHAMD5"), S("SSL3 SHAMD5")},
172 {CALG_MAC, 0, 0, 0, 0, S("MAC"), S("Message Authentication Code")},
173 {CALG_RSA_SIGN, 512, 384, 16384, CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC, S("RSA_SIGN"), S("RSA Signature")},
174 {CALG_RSA_KEYX, 512, 384, 1024, CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC, S("RSA_KEYX"), S("RSA Key Exchange")},
175 {CALG_HMAC, 0, 0, 0, 0, S("HMAC"), S("Hugo's MAC (HMAC)")},
176 {0, 0, 0, 0, 0, S(""), S("")}
179 {CALG_RC2, 128, 40, 128, 0, S("RC2"), S("RSA Data Security's RC2")},
180 {CALG_RC4, 128, 40, 128, 0, S("RC4"), S("RSA Data Security's RC4")},
181 {CALG_DES, 56, 56, 56, 0, S("DES"), S("Data Encryption Standard (DES)")},
182 {CALG_3DES_112, 112, 112, 112, 0, S("3DES TWO KEY"), S("Two Key Triple DES")},
183 {CALG_3DES, 168, 168, 168, 0, S("3DES"), S("Three Key Triple DES")},
184 {CALG_SHA, 160, 160, 160, CRYPT_FLAG_SIGNING, S("SHA-1"), S("Secure Hash Algorithm (SHA-1)")},
185 {CALG_MD2, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD2"), S("Message Digest 2 (MD2)")},
186 {CALG_MD4, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD4"), S("Message Digest 4 (MD4)")},
187 {CALG_MD5, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD5"), S("Message Digest 5 (MD5)")},
188 {CALG_SSL3_SHAMD5, 288, 288, 288, 0, S("SSL3 SHAMD5"), S("SSL3 SHAMD5")},
189 {CALG_MAC, 0, 0, 0, 0, S("MAC"), S("Message Authentication Code")},
190 {CALG_RSA_SIGN, 1024, 384, 16384, CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC, S("RSA_SIGN"), S("RSA Signature")},
191 {CALG_RSA_KEYX, 1024, 384, 16384, CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC, S("RSA_KEYX"), S("RSA Key Exchange")},
192 {CALG_HMAC, 0, 0, 0, 0, S("HMAC"), S("Hugo's MAC (HMAC)")},
193 {0, 0, 0, 0, 0, S(""), S("")}
196 {CALG_RC2, 128, 40, 128, 0, S("RC2"), S("RSA Data Security's RC2")},
197 {CALG_RC4, 128, 40, 128, 0, S("RC4"), S("RSA Data Security's RC4")},
198 {CALG_DES, 56, 56, 56, 0, S("DES"), S("Data Encryption Standard (DES)")},
199 {CALG_3DES_112, 112, 112, 112, 0, S("3DES TWO KEY"), S("Two Key Triple DES")},
200 {CALG_3DES, 168, 168, 168, 0, S("3DES"), S("Three Key Triple DES")},
201 {CALG_SHA, 160, 160, 160, CRYPT_FLAG_SIGNING, S("SHA-1"), S("Secure Hash Algorithm (SHA-1)")},
202 {CALG_MD2, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD2"), S("Message Digest 2 (MD2)")},
203 {CALG_MD4, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD4"), S("Message Digest 4 (MD4)")},
204 {CALG_MD5, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD5"), S("Message Digest 5 (MD5)")},
205 {CALG_SSL3_SHAMD5, 288, 288, 288, 0, S("SSL3 SHAMD5"), S("SSL3 SHAMD5")},
206 {CALG_MAC, 0, 0, 0, 0, S("MAC"), S("Message Authentication Code")},
207 {CALG_RSA_SIGN, 1024, 384, 16384, CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC, S("RSA_SIGN"), S("RSA Signature")},
208 {CALG_RSA_KEYX, 1024, 384, 16384, CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC, S("RSA_KEYX"), S("RSA Key Exchange")},
209 {CALG_HMAC, 0, 0, 0, 0, S("HMAC"), S("Hugo's MAC (HMAC)")},
210 {0, 0, 0, 0, 0, S(""), S("")}
213 {CALG_RC2, 128, 40, 128, RSAENH_PCT1_SSL2_SSL3_TLS1, S("RC2"), S("RSA Data Security's RC2")},
214 {CALG_RC4, 128, 40, 128, RSAENH_PCT1_SSL2_SSL3_TLS1, S("RC4"), S("RSA Data Security's RC4")},
215 {CALG_DES, 56, 56, 56, RSAENH_PCT1_SSL2_SSL3_TLS1, S("DES"), S("Data Encryption Standard (DES)")},
216 {CALG_3DES_112, 112, 112, 112, RSAENH_PCT1_SSL2_SSL3_TLS1, S("3DES TWO KEY"), S("Two Key Triple DES")},
217 {CALG_3DES, 168, 168, 168, RSAENH_PCT1_SSL2_SSL3_TLS1, S("3DES"), S("Three Key Triple DES")},
218 {CALG_SHA, 160, 160, 160, CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1, S("SHA-1"), S("Secure Hash Algorithm (SHA-1)")},
219 {CALG_MD5, 128, 128, 128, CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1, S("MD5"), S("Message Digest 5 (MD5)")},
220 {CALG_SSL3_SHAMD5, 288, 288, 288, 0, S("SSL3 SHAMD5"), S("SSL3 SHAMD5")},
221 {CALG_MAC, 0, 0, 0, 0, S("MAC"), S("Message Authentication Code")},
222 {CALG_RSA_SIGN, 1024, 384, 16384, CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1, S("RSA_SIGN"), S("RSA Signature")},
223 {CALG_RSA_KEYX, 1024, 384, 16384, CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1, S("RSA_KEYX"), S("RSA Key Exchange")},
224 {CALG_HMAC, 0, 0, 0, 0, S("HMAC"), S("Hugo's MAC (HMAC)")},
225 {CALG_PCT1_MASTER, 128, 128, 128, CRYPT_FLAG_PCT1, S("PCT1 MASTER"), S("PCT1 Master")},
226 {CALG_SSL2_MASTER, 40, 40, 192, CRYPT_FLAG_SSL2, S("SSL2 MASTER"), S("SSL2 Master")},
227 {CALG_SSL3_MASTER, 384, 384, 384, CRYPT_FLAG_SSL3, S("SSL3 MASTER"), S("SSL3 Master")},
228 {CALG_TLS1_MASTER, 384, 384, 384, CRYPT_FLAG_TLS1, S("TLS1 MASTER"), S("TLS1 Master")},
229 {CALG_SCHANNEL_MASTER_HASH, 0, 0, -1, 0, S("SCH MASTER HASH"), S("SChannel Master Hash")},
230 {CALG_SCHANNEL_MAC_KEY, 0, 0, -1, 0, S("SCH MAC KEY"), S("SChannel MAC Key")},
231 {CALG_SCHANNEL_ENC_KEY, 0, 0, -1, 0, S("SCH ENC KEY"), S("SChannel Encryption Key")},
232 {CALG_TLS1PRF, 0, 0, -1, 0, S("TLS1 PRF"), S("TLS1 Pseudo Random Function")},
233 {0, 0, 0, 0, 0, S(""), S("")}
236 {CALG_RC2, 128, 40, 128, 0, S("RC2"), S("RSA Data Security's RC2")},
237 {CALG_RC4, 128, 40, 128, 0, S("RC4"), S("RSA Data Security's RC4")},
238 {CALG_DES, 56, 56, 56, 0, S("DES"), S("Data Encryption Standard (DES)")},
239 {CALG_3DES_112, 112, 112, 112, 0, S("3DES TWO KEY"), S("Two Key Triple DES")},
240 {CALG_3DES, 168, 168, 168, 0, S("3DES"), S("Three Key Triple DES")},
241 {CALG_AES_128, 128, 128, 128, 0, S("AES-128"), S("Advanced Encryption Standard (AES-128)")},
242 {CALG_AES_192, 192, 192, 192, 0, S("AES-192"), S("Advanced Encryption Standard (AES-192)")},
243 {CALG_AES_256, 256, 256, 256, 0, S("AES-256"), S("Advanced Encryption Standard (AES-256)")},
244 {CALG_SHA, 160, 160, 160, CRYPT_FLAG_SIGNING, S("SHA-1"), S("Secure Hash Algorithm (SHA-1)")},
245 {CALG_SHA_256, 256, 256, 256, CRYPT_FLAG_SIGNING, S("SHA-256"), S("Secure Hash Algorithm (SHA-256)")},
246 {CALG_SHA_384, 384, 384, 384, CRYPT_FLAG_SIGNING, S("SHA-384"), S("Secure Hash Algorithm (SHA-384)")},
247 {CALG_SHA_512, 512, 512, 512, CRYPT_FLAG_SIGNING, S("SHA-512"), S("Secure Hash Algorithm (SHA-512)")},
248 {CALG_MD2, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD2"), S("Message Digest 2 (MD2)")},
249 {CALG_MD4, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD4"), S("Message Digest 4 (MD4)")},
250 {CALG_MD5, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD5"), S("Message Digest 5 (MD5)")},
251 {CALG_SSL3_SHAMD5, 288, 288, 288, 0, S("SSL3 SHAMD5"), S("SSL3 SHAMD5")},
252 {CALG_MAC, 0, 0, 0, 0, S("MAC"), S("Message Authentication Code")},
253 {CALG_RSA_SIGN, 1024, 384, 16384, CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC, S("RSA_SIGN"), S("RSA Signature")},
254 {CALG_RSA_KEYX, 1024, 384, 16384, CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC, S("RSA_KEYX"), S("RSA Key Exchange")},
255 {CALG_HMAC, 0, 0, 0, 0, S("HMAC"), S("Hugo's MAC (HMAC)")},
256 {0, 0, 0, 0, 0, S(""), S("")}
259 #undef S
261 /******************************************************************************
262 * API forward declarations
264 BOOL WINAPI
265 RSAENH_CPGetKeyParam(
266 HCRYPTPROV hProv,
267 HCRYPTKEY hKey,
268 DWORD dwParam,
269 BYTE *pbData,
270 DWORD *pdwDataLen,
271 DWORD dwFlags
274 BOOL WINAPI
275 RSAENH_CPEncrypt(
276 HCRYPTPROV hProv,
277 HCRYPTKEY hKey,
278 HCRYPTHASH hHash,
279 BOOL Final,
280 DWORD dwFlags,
281 BYTE *pbData,
282 DWORD *pdwDataLen,
283 DWORD dwBufLen
286 BOOL WINAPI
287 RSAENH_CPCreateHash(
288 HCRYPTPROV hProv,
289 ALG_ID Algid,
290 HCRYPTKEY hKey,
291 DWORD dwFlags,
292 HCRYPTHASH *phHash
295 BOOL WINAPI
296 RSAENH_CPSetHashParam(
297 HCRYPTPROV hProv,
298 HCRYPTHASH hHash,
299 DWORD dwParam,
300 BYTE *pbData, DWORD dwFlags
303 BOOL WINAPI
304 RSAENH_CPGetHashParam(
305 HCRYPTPROV hProv,
306 HCRYPTHASH hHash,
307 DWORD dwParam,
308 BYTE *pbData,
309 DWORD *pdwDataLen,
310 DWORD dwFlags
313 BOOL WINAPI
314 RSAENH_CPDestroyHash(
315 HCRYPTPROV hProv,
316 HCRYPTHASH hHash
319 static BOOL crypt_export_key(
320 CRYPTKEY *pCryptKey,
321 HCRYPTKEY hPubKey,
322 DWORD dwBlobType,
323 DWORD dwFlags,
324 BOOL force,
325 BYTE *pbData,
326 DWORD *pdwDataLen
329 static BOOL import_key(
330 HCRYPTPROV hProv,
331 const BYTE *pbData,
332 DWORD dwDataLen,
333 HCRYPTKEY hPubKey,
334 DWORD dwFlags,
335 BOOL fStoreKey,
336 HCRYPTKEY *phKey
339 BOOL WINAPI
340 RSAENH_CPHashData(
341 HCRYPTPROV hProv,
342 HCRYPTHASH hHash,
343 const BYTE *pbData,
344 DWORD dwDataLen,
345 DWORD dwFlags
348 /******************************************************************************
349 * CSP's handle table (used by all acquired key containers)
351 static struct handle_table handle_table;
353 /******************************************************************************
354 * DllMain (RSAENH.@)
356 * Initializes and destroys the handle table for the CSP's handles.
358 BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD fdwReason, PVOID reserved)
360 switch (fdwReason)
362 case DLL_PROCESS_ATTACH:
363 instance = hInstance;
364 DisableThreadLibraryCalls(hInstance);
365 init_handle_table(&handle_table);
366 break;
368 case DLL_PROCESS_DETACH:
369 if (reserved) break;
370 destroy_handle_table(&handle_table);
371 break;
373 return TRUE;
376 /******************************************************************************
377 * copy_param [Internal]
379 * Helper function that supports the standard WINAPI protocol for querying data
380 * of dynamic size.
382 * PARAMS
383 * pbBuffer [O] Buffer where the queried parameter is copied to, if it is large enough.
384 * May be NUL if the required buffer size is to be queried only.
385 * pdwBufferSize [I/O] In: Size of the buffer at pbBuffer
386 * Out: Size of parameter pbParam
387 * pbParam [I] Parameter value.
388 * dwParamSize [I] Size of pbParam
390 * RETURN
391 * Success: TRUE (pbParam was copied into pbBuffer or pbBuffer is NULL)
392 * Failure: FALSE (pbBuffer is not large enough to hold pbParam). Last error: ERROR_MORE_DATA
394 static inline BOOL copy_param(BYTE *pbBuffer, DWORD *pdwBufferSize, const BYTE *pbParam,
395 DWORD dwParamSize)
397 if (pbBuffer)
399 if (dwParamSize > *pdwBufferSize)
401 SetLastError(ERROR_MORE_DATA);
402 *pdwBufferSize = dwParamSize;
403 return FALSE;
405 memcpy(pbBuffer, pbParam, dwParamSize);
407 *pdwBufferSize = dwParamSize;
408 return TRUE;
411 static inline KEYCONTAINER* get_key_container(HCRYPTPROV hProv)
413 KEYCONTAINER *pKeyContainer;
415 if (!lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER,
416 (OBJECTHDR**)&pKeyContainer))
418 SetLastError(NTE_BAD_UID);
419 return NULL;
421 return pKeyContainer;
424 /******************************************************************************
425 * get_algid_info [Internal]
427 * Query CSP capabilities for a given crypto algorithm.
429 * PARAMS
430 * hProv [I] Handle to a key container of the CSP whose capabilities are to be queried.
431 * algid [I] Identifier of the crypto algorithm about which information is requested.
433 * RETURNS
434 * Success: Pointer to a PROV_ENUMALGS_EX struct containing information about the crypto algorithm.
435 * Failure: NULL (algid not supported)
437 static inline const PROV_ENUMALGS_EX* get_algid_info(HCRYPTPROV hProv, ALG_ID algid) {
438 const PROV_ENUMALGS_EX *iterator;
439 KEYCONTAINER *pKeyContainer;
441 if (!(pKeyContainer = get_key_container(hProv))) return NULL;
443 for (iterator = aProvEnumAlgsEx[pKeyContainer->dwPersonality]; iterator->aiAlgid; iterator++) {
444 if (iterator->aiAlgid == algid) return iterator;
447 SetLastError(NTE_BAD_ALGID);
448 return NULL;
451 /******************************************************************************
452 * copy_data_blob [Internal]
454 * deeply copies a DATA_BLOB
456 * PARAMS
457 * dst [O] That's where the blob will be copied to
458 * src [I] Source blob
460 * RETURNS
461 * Success: TRUE
462 * Failure: FALSE (GetLastError() == NTE_NO_MEMORY
464 * NOTES
465 * Use free_data_blob to release resources occupied by copy_data_blob.
467 static inline BOOL copy_data_blob(PCRYPT_DATA_BLOB dst, const PCRYPT_DATA_BLOB src)
469 dst->pbData = HeapAlloc(GetProcessHeap(), 0, src->cbData);
470 if (!dst->pbData) {
471 SetLastError(NTE_NO_MEMORY);
472 return FALSE;
474 dst->cbData = src->cbData;
475 memcpy(dst->pbData, src->pbData, src->cbData);
476 return TRUE;
479 /******************************************************************************
480 * concat_data_blobs [Internal]
482 * Concatenates two blobs
484 * PARAMS
485 * dst [O] The new blob will be copied here
486 * src1 [I] Prefix blob
487 * src2 [I] Appendix blob
489 * RETURNS
490 * Success: TRUE
491 * Failure: FALSE (GetLastError() == NTE_NO_MEMORY)
493 * NOTES
494 * Release resources occupied by concat_data_blobs with free_data_blobs
496 static inline BOOL concat_data_blobs(PCRYPT_DATA_BLOB dst, const PCRYPT_DATA_BLOB src1,
497 const PCRYPT_DATA_BLOB src2)
499 dst->cbData = src1->cbData + src2->cbData;
500 dst->pbData = HeapAlloc(GetProcessHeap(), 0, dst->cbData);
501 if (!dst->pbData) {
502 SetLastError(NTE_NO_MEMORY);
503 return FALSE;
505 memcpy(dst->pbData, src1->pbData, src1->cbData);
506 memcpy(dst->pbData + src1->cbData, src2->pbData, src2->cbData);
507 return TRUE;
510 /******************************************************************************
511 * free_data_blob [Internal]
513 * releases resource occupied by a dynamically allocated CRYPT_DATA_BLOB
515 * PARAMS
516 * pBlob [I] Heap space occupied by pBlob->pbData is released
518 static inline void free_data_blob(PCRYPT_DATA_BLOB pBlob) {
519 HeapFree(GetProcessHeap(), 0, pBlob->pbData);
522 /******************************************************************************
523 * init_data_blob [Internal]
525 static inline void init_data_blob(PCRYPT_DATA_BLOB pBlob) {
526 pBlob->pbData = NULL;
527 pBlob->cbData = 0;
530 /******************************************************************************
531 * free_hmac_info [Internal]
533 * Deeply free an HMAC_INFO struct.
535 * PARAMS
536 * hmac_info [I] Pointer to the HMAC_INFO struct to be freed.
538 * NOTES
539 * See Internet RFC 2104 for details on the HMAC algorithm.
541 static inline void free_hmac_info(PHMAC_INFO hmac_info) {
542 if (!hmac_info) return;
543 HeapFree(GetProcessHeap(), 0, hmac_info->pbInnerString);
544 HeapFree(GetProcessHeap(), 0, hmac_info->pbOuterString);
545 HeapFree(GetProcessHeap(), 0, hmac_info);
548 /******************************************************************************
549 * copy_hmac_info [Internal]
551 * Deeply copy an HMAC_INFO struct
553 * PARAMS
554 * dst [O] Pointer to a location where the pointer to the HMAC_INFO copy will be stored.
555 * src [I] Pointer to the HMAC_INFO struct to be copied.
557 * RETURNS
558 * Success: TRUE
559 * Failure: FALSE
561 * NOTES
562 * See Internet RFC 2104 for details on the HMAC algorithm.
564 static BOOL copy_hmac_info(PHMAC_INFO *dst, const HMAC_INFO *src) {
565 if (!src) return FALSE;
566 *dst = HeapAlloc(GetProcessHeap(), 0, sizeof(HMAC_INFO));
567 if (!*dst) return FALSE;
568 **dst = *src;
569 (*dst)->pbInnerString = NULL;
570 (*dst)->pbOuterString = NULL;
571 if ((*dst)->cbInnerString == 0) (*dst)->cbInnerString = RSAENH_HMAC_DEF_PAD_LEN;
572 (*dst)->pbInnerString = HeapAlloc(GetProcessHeap(), 0, (*dst)->cbInnerString);
573 if (!(*dst)->pbInnerString) {
574 free_hmac_info(*dst);
575 return FALSE;
577 if (src->cbInnerString)
578 memcpy((*dst)->pbInnerString, src->pbInnerString, src->cbInnerString);
579 else
580 memset((*dst)->pbInnerString, RSAENH_HMAC_DEF_IPAD_CHAR, RSAENH_HMAC_DEF_PAD_LEN);
581 if ((*dst)->cbOuterString == 0) (*dst)->cbOuterString = RSAENH_HMAC_DEF_PAD_LEN;
582 (*dst)->pbOuterString = HeapAlloc(GetProcessHeap(), 0, (*dst)->cbOuterString);
583 if (!(*dst)->pbOuterString) {
584 free_hmac_info(*dst);
585 return FALSE;
587 if (src->cbOuterString)
588 memcpy((*dst)->pbOuterString, src->pbOuterString, src->cbOuterString);
589 else
590 memset((*dst)->pbOuterString, RSAENH_HMAC_DEF_OPAD_CHAR, RSAENH_HMAC_DEF_PAD_LEN);
591 return TRUE;
594 /******************************************************************************
595 * destroy_hash [Internal]
597 * Destructor for hash objects
599 * PARAMS
600 * pCryptHash [I] Pointer to the hash object to be destroyed.
601 * Will be invalid after function returns!
603 static void destroy_hash(OBJECTHDR *pObject)
605 CRYPTHASH *pCryptHash = (CRYPTHASH*)pObject;
607 free_hmac_info(pCryptHash->pHMACInfo);
608 free_data_blob(&pCryptHash->tpPRFParams.blobLabel);
609 free_data_blob(&pCryptHash->tpPRFParams.blobSeed);
610 HeapFree(GetProcessHeap(), 0, pCryptHash);
613 /******************************************************************************
614 * init_hash [Internal]
616 * Initialize (or reset) a hash object
618 * PARAMS
619 * pCryptHash [I] The hash object to be initialized.
621 static inline BOOL init_hash(CRYPTHASH *pCryptHash) {
622 DWORD dwLen;
624 switch (pCryptHash->aiAlgid)
626 case CALG_HMAC:
627 if (pCryptHash->pHMACInfo) {
628 const PROV_ENUMALGS_EX *pAlgInfo;
630 pAlgInfo = get_algid_info(pCryptHash->hProv, pCryptHash->pHMACInfo->HashAlgid);
631 if (!pAlgInfo) return FALSE;
632 pCryptHash->dwHashSize = pAlgInfo->dwDefaultLen >> 3;
633 init_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context);
634 update_hash_impl(&pCryptHash->context,
635 pCryptHash->pHMACInfo->pbInnerString,
636 pCryptHash->pHMACInfo->cbInnerString);
638 return TRUE;
640 case CALG_MAC:
641 dwLen = sizeof(DWORD);
642 RSAENH_CPGetKeyParam(pCryptHash->hProv, pCryptHash->hKey, KP_BLOCKLEN,
643 (BYTE*)&pCryptHash->dwHashSize, &dwLen, 0);
644 pCryptHash->dwHashSize >>= 3;
645 return TRUE;
647 default:
648 return init_hash_impl(pCryptHash->aiAlgid, &pCryptHash->context);
652 /******************************************************************************
653 * update_hash [Internal]
655 * Hashes the given data and updates the hash object's state accordingly
657 * PARAMS
658 * pCryptHash [I] Hash object to be updated.
659 * pbData [I] Pointer to data stream to be hashed.
660 * dwDataLen [I] Length of data stream.
662 static inline void update_hash(CRYPTHASH *pCryptHash, const BYTE *pbData, DWORD dwDataLen)
664 BYTE *pbTemp;
666 switch (pCryptHash->aiAlgid)
668 case CALG_HMAC:
669 if (pCryptHash->pHMACInfo)
670 update_hash_impl(&pCryptHash->context, pbData, dwDataLen);
671 break;
673 case CALG_MAC:
674 pbTemp = HeapAlloc(GetProcessHeap(), 0, dwDataLen);
675 if (!pbTemp) return;
676 memcpy(pbTemp, pbData, dwDataLen);
677 RSAENH_CPEncrypt(pCryptHash->hProv, pCryptHash->hKey, 0, FALSE, 0,
678 pbTemp, &dwDataLen, dwDataLen);
679 HeapFree(GetProcessHeap(), 0, pbTemp);
680 break;
682 default:
683 update_hash_impl(&pCryptHash->context, pbData, dwDataLen);
687 /******************************************************************************
688 * finalize_hash [Internal]
690 * Finalizes the hash, after all data has been hashed with update_hash.
691 * No additional data can be hashed afterwards until the hash gets initialized again.
693 * PARAMS
694 * pCryptHash [I] Hash object to be finalized.
696 static inline void finalize_hash(CRYPTHASH *pCryptHash) {
697 DWORD dwDataLen;
699 switch (pCryptHash->aiAlgid)
701 case CALG_HMAC:
702 if (pCryptHash->pHMACInfo) {
703 BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
705 finalize_hash_impl(&pCryptHash->context, pCryptHash->abHashValue);
706 memcpy(abHashValue, pCryptHash->abHashValue, pCryptHash->dwHashSize);
707 init_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context);
708 update_hash_impl(&pCryptHash->context,
709 pCryptHash->pHMACInfo->pbOuterString,
710 pCryptHash->pHMACInfo->cbOuterString);
711 update_hash_impl(&pCryptHash->context,
712 abHashValue, pCryptHash->dwHashSize);
713 finalize_hash_impl(&pCryptHash->context, pCryptHash->abHashValue);
715 break;
717 case CALG_MAC:
718 dwDataLen = 0;
719 RSAENH_CPEncrypt(pCryptHash->hProv, pCryptHash->hKey, 0, TRUE, 0,
720 pCryptHash->abHashValue, &dwDataLen, pCryptHash->dwHashSize);
721 break;
723 default:
724 finalize_hash_impl(&pCryptHash->context, pCryptHash->abHashValue);
728 /******************************************************************************
729 * destroy_key [Internal]
731 * Destructor for key objects
733 * PARAMS
734 * pCryptKey [I] Pointer to the key object to be destroyed.
735 * Will be invalid after function returns!
737 static void destroy_key(OBJECTHDR *pObject)
739 CRYPTKEY *pCryptKey = (CRYPTKEY*)pObject;
741 free_key_impl(pCryptKey->aiAlgid, &pCryptKey->context);
742 free_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom);
743 free_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom);
744 free_data_blob(&pCryptKey->blobHmacKey);
745 HeapFree(GetProcessHeap(), 0, pCryptKey);
748 /******************************************************************************
749 * setup_key [Internal]
751 * Initialize (or reset) a key object
753 * PARAMS
754 * pCryptKey [I] The key object to be initialized.
756 static inline void setup_key(CRYPTKEY *pCryptKey) {
757 pCryptKey->dwState = RSAENH_KEYSTATE_IDLE;
758 memcpy(pCryptKey->abChainVector, pCryptKey->abInitVector, sizeof(pCryptKey->abChainVector));
759 setup_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen,
760 pCryptKey->dwEffectiveKeyLen, pCryptKey->dwSaltLen,
761 pCryptKey->abKeyValue);
764 /******************************************************************************
765 * new_key [Internal]
767 * Creates a new key object without assigning the actual binary key value.
768 * This is done by CPDeriveKey, CPGenKey or CPImportKey, which call this function.
770 * PARAMS
771 * hProv [I] Handle to the provider to which the created key will belong.
772 * aiAlgid [I] The new key shall use the crypto algorithm identified by aiAlgid.
773 * dwFlags [I] Upper 16 bits give the key length.
774 * Lower 16 bits: CRYPT_EXPORTABLE, CRYPT_CREATE_SALT,
775 * CRYPT_NO_SALT
776 * ppCryptKey [O] Pointer to the created key
778 * RETURNS
779 * Success: Handle to the created key.
780 * Failure: INVALID_HANDLE_VALUE
782 static HCRYPTKEY new_key(HCRYPTPROV hProv, ALG_ID aiAlgid, DWORD dwFlags, CRYPTKEY **ppCryptKey)
784 HCRYPTKEY hCryptKey;
785 CRYPTKEY *pCryptKey;
786 DWORD dwKeyLen = HIWORD(dwFlags);
787 const PROV_ENUMALGS_EX *peaAlgidInfo;
789 *ppCryptKey = NULL;
792 * Retrieve the CSP's capabilities for the given ALG_ID value
794 peaAlgidInfo = get_algid_info(hProv, aiAlgid);
795 if (!peaAlgidInfo) return (HCRYPTKEY)INVALID_HANDLE_VALUE;
797 TRACE("alg = %s, dwKeyLen = %d\n", debugstr_a(peaAlgidInfo->szName),
798 dwKeyLen);
800 * Assume the default key length, if none is specified explicitly
802 if (dwKeyLen == 0) dwKeyLen = peaAlgidInfo->dwDefaultLen;
805 * Check if the requested key length is supported by the current CSP.
806 * Adjust key length's for DES algorithms.
808 switch (aiAlgid) {
809 case CALG_DES:
810 if (dwKeyLen == RSAENH_DES_EFFECTIVE_KEYLEN) {
811 dwKeyLen = RSAENH_DES_STORAGE_KEYLEN;
813 if (dwKeyLen != RSAENH_DES_STORAGE_KEYLEN) {
814 SetLastError(NTE_BAD_FLAGS);
815 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
817 break;
819 case CALG_3DES_112:
820 if (dwKeyLen == RSAENH_3DES112_EFFECTIVE_KEYLEN) {
821 dwKeyLen = RSAENH_3DES112_STORAGE_KEYLEN;
823 if (dwKeyLen != RSAENH_3DES112_STORAGE_KEYLEN) {
824 SetLastError(NTE_BAD_FLAGS);
825 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
827 break;
829 case CALG_3DES:
830 if (dwKeyLen == RSAENH_3DES_EFFECTIVE_KEYLEN) {
831 dwKeyLen = RSAENH_3DES_STORAGE_KEYLEN;
833 if (dwKeyLen != RSAENH_3DES_STORAGE_KEYLEN) {
834 SetLastError(NTE_BAD_FLAGS);
835 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
837 break;
839 case CALG_HMAC:
840 /* Avoid the key length check for HMAC keys, which have unlimited
841 * length.
843 break;
845 default:
846 if (dwKeyLen % 8 ||
847 dwKeyLen > peaAlgidInfo->dwMaxLen ||
848 dwKeyLen < peaAlgidInfo->dwMinLen)
850 TRACE("key len %d out of bounds (%d, %d)\n", dwKeyLen,
851 peaAlgidInfo->dwMinLen, peaAlgidInfo->dwMaxLen);
852 SetLastError(NTE_BAD_DATA);
853 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
857 hCryptKey = new_object(&handle_table, sizeof(CRYPTKEY), RSAENH_MAGIC_KEY,
858 destroy_key, (OBJECTHDR**)&pCryptKey);
859 if (hCryptKey != (HCRYPTKEY)INVALID_HANDLE_VALUE)
861 KEYCONTAINER *pKeyContainer = get_key_container(hProv);
862 pCryptKey->aiAlgid = aiAlgid;
863 pCryptKey->hProv = hProv;
864 pCryptKey->dwModeBits = 0;
865 pCryptKey->dwPermissions = CRYPT_ENCRYPT | CRYPT_DECRYPT | CRYPT_READ | CRYPT_WRITE |
866 CRYPT_MAC;
867 if (dwFlags & CRYPT_EXPORTABLE)
868 pCryptKey->dwPermissions |= CRYPT_EXPORT;
869 pCryptKey->dwKeyLen = dwKeyLen >> 3;
870 pCryptKey->dwEffectiveKeyLen = 0;
873 * For compatibility reasons a 40 bit key on the Enhanced
874 * provider will not have salt
876 if (pKeyContainer->dwPersonality == RSAENH_PERSONALITY_ENHANCED
877 && (aiAlgid == CALG_RC2 || aiAlgid == CALG_RC4)
878 && (dwFlags & CRYPT_CREATE_SALT) && dwKeyLen == 40)
879 pCryptKey->dwSaltLen = 0;
880 else if ((dwFlags & CRYPT_CREATE_SALT) || (dwKeyLen == 40 && !(dwFlags & CRYPT_NO_SALT)))
881 pCryptKey->dwSaltLen = 16 /*FIXME*/ - pCryptKey->dwKeyLen;
882 else
883 pCryptKey->dwSaltLen = 0;
884 memset(pCryptKey->abKeyValue, 0, sizeof(pCryptKey->abKeyValue));
885 memset(pCryptKey->abInitVector, 0, sizeof(pCryptKey->abInitVector));
886 memset(&pCryptKey->siSChannelInfo.saEncAlg, 0, sizeof(pCryptKey->siSChannelInfo.saEncAlg));
887 memset(&pCryptKey->siSChannelInfo.saMACAlg, 0, sizeof(pCryptKey->siSChannelInfo.saMACAlg));
888 init_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom);
889 init_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom);
890 init_data_blob(&pCryptKey->blobHmacKey);
892 switch(aiAlgid)
894 case CALG_PCT1_MASTER:
895 case CALG_SSL2_MASTER:
896 case CALG_SSL3_MASTER:
897 case CALG_TLS1_MASTER:
898 case CALG_RC4:
899 pCryptKey->dwBlockLen = 0;
900 pCryptKey->dwMode = 0;
901 break;
903 case CALG_RC2:
904 case CALG_DES:
905 case CALG_3DES_112:
906 case CALG_3DES:
907 pCryptKey->dwBlockLen = 8;
908 pCryptKey->dwMode = CRYPT_MODE_CBC;
909 break;
911 case CALG_AES_128:
912 case CALG_AES_192:
913 case CALG_AES_256:
914 pCryptKey->dwBlockLen = 16;
915 pCryptKey->dwMode = CRYPT_MODE_CBC;
916 break;
918 case CALG_RSA_KEYX:
919 case CALG_RSA_SIGN:
920 pCryptKey->dwBlockLen = dwKeyLen >> 3;
921 pCryptKey->dwMode = 0;
922 break;
924 case CALG_HMAC:
925 pCryptKey->dwBlockLen = 0;
926 pCryptKey->dwMode = 0;
927 break;
930 *ppCryptKey = pCryptKey;
933 return hCryptKey;
936 /******************************************************************************
937 * map_key_spec_to_key_pair_name [Internal]
939 * Returns the name of the registry value associated with a key spec.
941 * PARAMS
942 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
944 * RETURNS
945 * Success: Name of registry value.
946 * Failure: NULL
948 static LPCSTR map_key_spec_to_key_pair_name(DWORD dwKeySpec)
950 LPCSTR szValueName;
952 switch (dwKeySpec)
954 case AT_KEYEXCHANGE:
955 szValueName = "KeyExchangeKeyPair";
956 break;
957 case AT_SIGNATURE:
958 szValueName = "SignatureKeyPair";
959 break;
960 default:
961 WARN("invalid key spec %d\n", dwKeySpec);
962 szValueName = NULL;
964 return szValueName;
967 /******************************************************************************
968 * store_key_pair [Internal]
970 * Stores a key pair to the registry
972 * PARAMS
973 * hCryptKey [I] Handle to the key to be stored
974 * hKey [I] Registry key where the key pair is to be stored
975 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
976 * dwFlags [I] Flags for protecting the key
978 static void store_key_pair(HCRYPTKEY hCryptKey, HKEY hKey, DWORD dwKeySpec, DWORD dwFlags)
980 LPCSTR szValueName;
981 DATA_BLOB blobIn, blobOut;
982 CRYPTKEY *pKey;
983 DWORD dwLen;
984 BYTE *pbKey;
986 if (!(szValueName = map_key_spec_to_key_pair_name(dwKeySpec)))
987 return;
988 if (lookup_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY,
989 (OBJECTHDR**)&pKey))
991 if (crypt_export_key(pKey, 0, PRIVATEKEYBLOB, 0, TRUE, 0, &dwLen))
993 pbKey = HeapAlloc(GetProcessHeap(), 0, dwLen);
994 if (pbKey)
996 if (crypt_export_key(pKey, 0, PRIVATEKEYBLOB, 0, TRUE, pbKey,
997 &dwLen))
999 blobIn.pbData = pbKey;
1000 blobIn.cbData = dwLen;
1002 if (CryptProtectData(&blobIn, NULL, NULL, NULL, NULL,
1003 dwFlags, &blobOut))
1005 RegSetValueExA(hKey, szValueName, 0, REG_BINARY,
1006 blobOut.pbData, blobOut.cbData);
1007 LocalFree(blobOut.pbData);
1010 HeapFree(GetProcessHeap(), 0, pbKey);
1016 /******************************************************************************
1017 * map_key_spec_to_permissions_name [Internal]
1019 * Returns the name of the registry value associated with the permissions for
1020 * a key spec.
1022 * PARAMS
1023 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
1025 * RETURNS
1026 * Success: Name of registry value.
1027 * Failure: NULL
1029 static LPCSTR map_key_spec_to_permissions_name(DWORD dwKeySpec)
1031 LPCSTR szValueName;
1033 switch (dwKeySpec)
1035 case AT_KEYEXCHANGE:
1036 szValueName = "KeyExchangePermissions";
1037 break;
1038 case AT_SIGNATURE:
1039 szValueName = "SignaturePermissions";
1040 break;
1041 default:
1042 WARN("invalid key spec %d\n", dwKeySpec);
1043 szValueName = NULL;
1045 return szValueName;
1048 /******************************************************************************
1049 * store_key_permissions [Internal]
1051 * Stores a key's permissions to the registry
1053 * PARAMS
1054 * hCryptKey [I] Handle to the key whose permissions are to be stored
1055 * hKey [I] Registry key where the key permissions are to be stored
1056 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
1058 static void store_key_permissions(HCRYPTKEY hCryptKey, HKEY hKey, DWORD dwKeySpec)
1060 LPCSTR szValueName;
1061 CRYPTKEY *pKey;
1063 if (!(szValueName = map_key_spec_to_permissions_name(dwKeySpec)))
1064 return;
1065 if (lookup_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY,
1066 (OBJECTHDR**)&pKey))
1067 RegSetValueExA(hKey, szValueName, 0, REG_DWORD,
1068 (BYTE *)&pKey->dwPermissions,
1069 sizeof(pKey->dwPermissions));
1072 /******************************************************************************
1073 * create_container_key [Internal]
1075 * Creates the registry key for a key container's persistent storage.
1077 * PARAMS
1078 * pKeyContainer [I] Pointer to the key container
1079 * sam [I] Desired registry access
1080 * phKey [O] Returned key
1082 static BOOL create_container_key(KEYCONTAINER *pKeyContainer, REGSAM sam, HKEY *phKey)
1084 CHAR szRSABase[sizeof(RSAENH_REGKEY) + MAX_PATH];
1085 HKEY hRootKey;
1087 sprintf(szRSABase, RSAENH_REGKEY, pKeyContainer->szName);
1089 if (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET)
1090 hRootKey = HKEY_LOCAL_MACHINE;
1091 else
1092 hRootKey = HKEY_CURRENT_USER;
1094 /* @@ Wine registry key: HKLM\Software\Wine\Crypto\RSA */
1095 /* @@ Wine registry key: HKCU\Software\Wine\Crypto\RSA */
1096 return RegCreateKeyExA(hRootKey, szRSABase, 0, NULL,
1097 REG_OPTION_NON_VOLATILE, sam, NULL, phKey, NULL)
1098 == ERROR_SUCCESS;
1101 /******************************************************************************
1102 * open_container_key [Internal]
1104 * Opens a key container's persistent storage for reading.
1106 * PARAMS
1107 * pszContainerName [I] Name of the container to be opened. May be the empty
1108 * string if the parent key of all containers is to be
1109 * opened.
1110 * dwFlags [I] Flags indicating which keyset to be opened.
1111 * phKey [O] Returned key
1113 static BOOL open_container_key(LPCSTR pszContainerName, DWORD dwFlags, REGSAM access, HKEY *phKey)
1115 CHAR szRSABase[sizeof(RSAENH_REGKEY) + MAX_PATH];
1116 HKEY hRootKey;
1118 sprintf(szRSABase, RSAENH_REGKEY, pszContainerName);
1120 if (dwFlags & CRYPT_MACHINE_KEYSET)
1121 hRootKey = HKEY_LOCAL_MACHINE;
1122 else
1123 hRootKey = HKEY_CURRENT_USER;
1125 /* @@ Wine registry key: HKLM\Software\Wine\Crypto\RSA */
1126 /* @@ Wine registry key: HKCU\Software\Wine\Crypto\RSA */
1127 return RegOpenKeyExA(hRootKey, szRSABase, 0, access, phKey) ==
1128 ERROR_SUCCESS;
1131 /******************************************************************************
1132 * delete_container_key [Internal]
1134 * Deletes a key container's persistent storage.
1136 * PARAMS
1137 * pszContainerName [I] Name of the container to be opened.
1138 * dwFlags [I] Flags indicating which keyset to be opened.
1140 static BOOL delete_container_key(LPCSTR pszContainerName, DWORD dwFlags)
1142 CHAR szRegKey[sizeof(RSAENH_REGKEY) + MAX_PATH];
1143 HKEY hRootKey;
1145 sprintf(szRegKey, RSAENH_REGKEY, pszContainerName);
1147 if (dwFlags & CRYPT_MACHINE_KEYSET)
1148 hRootKey = HKEY_LOCAL_MACHINE;
1149 else
1150 hRootKey = HKEY_CURRENT_USER;
1151 if (!RegDeleteKeyA(hRootKey, szRegKey)) {
1152 SetLastError(ERROR_SUCCESS);
1153 return TRUE;
1154 } else {
1155 SetLastError(NTE_BAD_KEYSET);
1156 return FALSE;
1160 /******************************************************************************
1161 * store_key_container_keys [Internal]
1163 * Stores key container's keys in a persistent location.
1165 * PARAMS
1166 * pKeyContainer [I] Pointer to the key container whose keys are to be saved
1168 static void store_key_container_keys(KEYCONTAINER *pKeyContainer)
1170 HKEY hKey;
1171 DWORD dwFlags;
1173 /* On WinXP, persistent keys are stored in a file located at:
1174 * $AppData$\\Microsoft\\Crypto\\RSA\\$SID$\\some_hex_string
1177 if (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET)
1178 dwFlags = CRYPTPROTECT_LOCAL_MACHINE;
1179 else
1180 dwFlags = 0;
1182 if (create_container_key(pKeyContainer, KEY_WRITE, &hKey))
1184 store_key_pair(pKeyContainer->hKeyExchangeKeyPair, hKey,
1185 AT_KEYEXCHANGE, dwFlags);
1186 store_key_pair(pKeyContainer->hSignatureKeyPair, hKey,
1187 AT_SIGNATURE, dwFlags);
1188 RegCloseKey(hKey);
1192 /******************************************************************************
1193 * store_key_container_permissions [Internal]
1195 * Stores key container's key permissions in a persistent location.
1197 * PARAMS
1198 * pKeyContainer [I] Pointer to the key container whose key permissions are to
1199 * be saved
1201 static void store_key_container_permissions(KEYCONTAINER *pKeyContainer)
1203 HKEY hKey;
1205 if (create_container_key(pKeyContainer, KEY_WRITE, &hKey))
1207 store_key_permissions(pKeyContainer->hKeyExchangeKeyPair, hKey,
1208 AT_KEYEXCHANGE);
1209 store_key_permissions(pKeyContainer->hSignatureKeyPair, hKey,
1210 AT_SIGNATURE);
1211 RegCloseKey(hKey);
1215 /******************************************************************************
1216 * release_key_container_keys [Internal]
1218 * Releases key container's keys.
1220 * PARAMS
1221 * pKeyContainer [I] Pointer to the key container whose keys are to be released.
1223 static void release_key_container_keys(KEYCONTAINER *pKeyContainer)
1225 release_handle(&handle_table, pKeyContainer->hKeyExchangeKeyPair,
1226 RSAENH_MAGIC_KEY);
1227 release_handle(&handle_table, pKeyContainer->hSignatureKeyPair,
1228 RSAENH_MAGIC_KEY);
1231 /******************************************************************************
1232 * destroy_key_container [Internal]
1234 * Destructor for key containers.
1236 * PARAMS
1237 * pObjectHdr [I] Pointer to the key container to be destroyed.
1239 static void destroy_key_container(OBJECTHDR *pObjectHdr)
1241 KEYCONTAINER *pKeyContainer = (KEYCONTAINER*)pObjectHdr;
1243 if (!(pKeyContainer->dwFlags & CRYPT_VERIFYCONTEXT))
1245 store_key_container_keys(pKeyContainer);
1246 store_key_container_permissions(pKeyContainer);
1247 release_key_container_keys(pKeyContainer);
1249 else
1250 release_key_container_keys(pKeyContainer);
1251 HeapFree( GetProcessHeap(), 0, pKeyContainer );
1254 /******************************************************************************
1255 * new_key_container [Internal]
1257 * Create a new key container. The personality (RSA Base, Strong or Enhanced CP)
1258 * of the CSP is determined via the pVTable->pszProvName string.
1260 * PARAMS
1261 * pszContainerName [I] Name of the key container.
1262 * pVTable [I] Callback functions and context info provided by the OS
1264 * RETURNS
1265 * Success: Handle to the new key container.
1266 * Failure: INVALID_HANDLE_VALUE
1268 static HCRYPTPROV new_key_container(PCCH pszContainerName, DWORD dwFlags, const VTableProvStruc *pVTable)
1270 KEYCONTAINER *pKeyContainer;
1271 HCRYPTPROV hKeyContainer;
1273 hKeyContainer = new_object(&handle_table, sizeof(KEYCONTAINER), RSAENH_MAGIC_CONTAINER,
1274 destroy_key_container, (OBJECTHDR**)&pKeyContainer);
1275 if (hKeyContainer != (HCRYPTPROV)INVALID_HANDLE_VALUE)
1277 lstrcpynA(pKeyContainer->szName, pszContainerName, MAX_PATH);
1278 pKeyContainer->dwFlags = dwFlags;
1279 pKeyContainer->dwEnumAlgsCtr = 0;
1280 pKeyContainer->hKeyExchangeKeyPair = (HCRYPTKEY)INVALID_HANDLE_VALUE;
1281 pKeyContainer->hSignatureKeyPair = (HCRYPTKEY)INVALID_HANDLE_VALUE;
1282 if (pVTable && pVTable->pszProvName) {
1283 lstrcpynA(pKeyContainer->szProvName, pVTable->pszProvName, MAX_PATH);
1284 if (!strcmp(pVTable->pszProvName, MS_DEF_PROV_A)) {
1285 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_BASE;
1286 } else if (!strcmp(pVTable->pszProvName, MS_ENHANCED_PROV_A)) {
1287 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_ENHANCED;
1288 } else if (!strcmp(pVTable->pszProvName, MS_DEF_RSA_SCHANNEL_PROV_A)) {
1289 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_SCHANNEL;
1290 } else if (!strcmp(pVTable->pszProvName, MS_ENH_RSA_AES_PROV_A) ||
1291 !strcmp(pVTable->pszProvName, MS_ENH_RSA_AES_PROV_XP_A)) {
1292 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_AES;
1293 } else {
1294 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_STRONG;
1298 /* The new key container has to be inserted into the CSP immediately
1299 * after creation to be available for CPGetProvParam's PP_ENUMCONTAINERS. */
1300 if (!(dwFlags & CRYPT_VERIFYCONTEXT)) {
1301 HKEY hKey;
1303 if (create_container_key(pKeyContainer, KEY_WRITE, &hKey))
1304 RegCloseKey(hKey);
1308 return hKeyContainer;
1311 /******************************************************************************
1312 * read_key_value [Internal]
1314 * Reads a key pair value from the registry
1316 * PARAMS
1317 * hKeyContainer [I] Crypt provider to use to import the key
1318 * hKey [I] Registry key from which to read the key pair
1319 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
1320 * dwFlags [I] Flags for unprotecting the key
1321 * phCryptKey [O] Returned key
1323 static BOOL read_key_value(HCRYPTPROV hKeyContainer, HKEY hKey, DWORD dwKeySpec, DWORD dwFlags, HCRYPTKEY *phCryptKey)
1325 LPCSTR szValueName;
1326 DWORD dwValueType, dwLen;
1327 BYTE *pbKey;
1328 DATA_BLOB blobIn, blobOut;
1329 BOOL ret = FALSE;
1331 if (!(szValueName = map_key_spec_to_key_pair_name(dwKeySpec)))
1332 return FALSE;
1333 if (RegQueryValueExA(hKey, szValueName, 0, &dwValueType, NULL, &dwLen) ==
1334 ERROR_SUCCESS)
1336 pbKey = HeapAlloc(GetProcessHeap(), 0, dwLen);
1337 if (pbKey)
1339 if (RegQueryValueExA(hKey, szValueName, 0, &dwValueType, pbKey, &dwLen) ==
1340 ERROR_SUCCESS)
1342 blobIn.pbData = pbKey;
1343 blobIn.cbData = dwLen;
1345 if (CryptUnprotectData(&blobIn, NULL, NULL, NULL, NULL,
1346 dwFlags, &blobOut))
1348 ret = import_key(hKeyContainer, blobOut.pbData, blobOut.cbData, 0, 0,
1349 FALSE, phCryptKey);
1350 LocalFree(blobOut.pbData);
1353 HeapFree(GetProcessHeap(), 0, pbKey);
1356 if (ret)
1358 CRYPTKEY *pKey;
1360 if (lookup_handle(&handle_table, *phCryptKey, RSAENH_MAGIC_KEY,
1361 (OBJECTHDR**)&pKey))
1363 if ((szValueName = map_key_spec_to_permissions_name(dwKeySpec)))
1365 dwLen = sizeof(pKey->dwPermissions);
1366 RegQueryValueExA(hKey, szValueName, 0, NULL,
1367 (BYTE *)&pKey->dwPermissions, &dwLen);
1371 return ret;
1374 /******************************************************************************
1375 * read_key_container [Internal]
1377 * Tries to read the persistent state of the key container (mainly the signature
1378 * and key exchange private keys) given by pszContainerName.
1380 * PARAMS
1381 * pszContainerName [I] Name of the key container to read from the registry
1382 * pVTable [I] Pointer to context data provided by the operating system
1384 * RETURNS
1385 * Success: Handle to the key container read from the registry
1386 * Failure: INVALID_HANDLE_VALUE
1388 static HCRYPTPROV read_key_container(PCHAR pszContainerName, DWORD dwFlags, const VTableProvStruc *pVTable)
1390 HKEY hKey;
1391 KEYCONTAINER *pKeyContainer;
1392 HCRYPTPROV hKeyContainer;
1393 HCRYPTKEY hCryptKey;
1395 if (!open_container_key(pszContainerName, dwFlags, KEY_READ, &hKey))
1397 SetLastError(NTE_BAD_KEYSET);
1398 return (HCRYPTPROV)INVALID_HANDLE_VALUE;
1401 hKeyContainer = new_key_container(pszContainerName, dwFlags, pVTable);
1402 if (hKeyContainer != (HCRYPTPROV)INVALID_HANDLE_VALUE)
1404 DWORD dwProtectFlags = (dwFlags & CRYPT_MACHINE_KEYSET) ?
1405 CRYPTPROTECT_LOCAL_MACHINE : 0;
1407 if (!lookup_handle(&handle_table, hKeyContainer, RSAENH_MAGIC_CONTAINER,
1408 (OBJECTHDR**)&pKeyContainer))
1409 return (HCRYPTPROV)INVALID_HANDLE_VALUE;
1411 /* read_key_value calls import_key, which calls import_private_key,
1412 * which implicitly installs the key value into the appropriate key
1413 * container key. Thus the ref count is incremented twice, once for
1414 * the output key value, and once for the implicit install, and needs
1415 * to be decremented to balance the two.
1417 if (read_key_value(hKeyContainer, hKey, AT_KEYEXCHANGE,
1418 dwProtectFlags, &hCryptKey))
1419 release_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY);
1420 if (read_key_value(hKeyContainer, hKey, AT_SIGNATURE,
1421 dwProtectFlags, &hCryptKey))
1422 release_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY);
1425 return hKeyContainer;
1428 /******************************************************************************
1429 * build_hash_signature [Internal]
1431 * Builds a padded version of a hash to match the length of the RSA key modulus.
1433 * PARAMS
1434 * pbSignature [O] The padded hash object is stored here.
1435 * dwLen [I] Length of the pbSignature buffer.
1436 * aiAlgid [I] Algorithm identifier of the hash to be padded.
1437 * abHashValue [I] The value of the hash object.
1438 * dwHashLen [I] Length of the hash value.
1439 * dwFlags [I] Selection of padding algorithm.
1441 * RETURNS
1442 * Success: TRUE
1443 * Failure: FALSE (NTE_BAD_ALGID)
1445 static BOOL build_hash_signature(BYTE *pbSignature, DWORD dwLen, ALG_ID aiAlgid,
1446 const BYTE *abHashValue, DWORD dwHashLen, DWORD dwFlags)
1448 /* These prefixes are meant to be concatenated with hash values of the
1449 * respective kind to form a PKCS #7 DigestInfo. */
1450 static const struct tagOIDDescriptor {
1451 ALG_ID aiAlgid;
1452 DWORD dwLen;
1453 const BYTE abOID[19];
1454 } aOIDDescriptor[] = {
1455 { CALG_MD2, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48,
1456 0x86, 0xf7, 0x0d, 0x02, 0x02, 0x05, 0x00, 0x04, 0x10 } },
1457 { CALG_MD4, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48,
1458 0x86, 0xf7, 0x0d, 0x02, 0x04, 0x05, 0x00, 0x04, 0x10 } },
1459 { CALG_MD5, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48,
1460 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10 } },
1461 { CALG_SHA, 15, { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
1462 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 } },
1463 { CALG_SHA_256, 19, { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
1464 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01,
1465 0x05, 0x00, 0x04, 0x20 } },
1466 { CALG_SHA_384, 19, { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
1467 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02,
1468 0x05, 0x00, 0x04, 0x30 } },
1469 { CALG_SHA_512, 19, { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
1470 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03,
1471 0x05, 0x00, 0x04, 0x40 } },
1472 { CALG_SSL3_SHAMD5, 0, { 0 } },
1473 { 0, 0, { 0 } }
1475 DWORD dwIdxOID, i, j;
1477 for (dwIdxOID = 0; aOIDDescriptor[dwIdxOID].aiAlgid; dwIdxOID++) {
1478 if (aOIDDescriptor[dwIdxOID].aiAlgid == aiAlgid) break;
1481 if (!aOIDDescriptor[dwIdxOID].aiAlgid) {
1482 SetLastError(NTE_BAD_ALGID);
1483 return FALSE;
1486 /* Build the padded signature */
1487 if (dwFlags & CRYPT_X931_FORMAT) {
1488 pbSignature[0] = 0x6b;
1489 for (i=1; i < dwLen - dwHashLen - 3; i++) {
1490 pbSignature[i] = 0xbb;
1492 pbSignature[i++] = 0xba;
1493 for (j=0; j < dwHashLen; j++, i++) {
1494 pbSignature[i] = abHashValue[j];
1496 pbSignature[i++] = 0x33;
1497 pbSignature[i++] = 0xcc;
1498 } else {
1499 pbSignature[0] = 0x00;
1500 pbSignature[1] = 0x01;
1501 if (dwFlags & CRYPT_NOHASHOID) {
1502 for (i=2; i < dwLen - 1 - dwHashLen; i++) {
1503 pbSignature[i] = 0xff;
1505 pbSignature[i++] = 0x00;
1506 } else {
1507 for (i=2; i < dwLen - 1 - aOIDDescriptor[dwIdxOID].dwLen - dwHashLen; i++) {
1508 pbSignature[i] = 0xff;
1510 pbSignature[i++] = 0x00;
1511 for (j=0; j < aOIDDescriptor[dwIdxOID].dwLen; j++) {
1512 pbSignature[i++] = aOIDDescriptor[dwIdxOID].abOID[j];
1515 for (j=0; j < dwHashLen; j++) {
1516 pbSignature[i++] = abHashValue[j];
1520 return TRUE;
1523 /******************************************************************************
1524 * tls1_p [Internal]
1526 * This is an implementation of the 'P_hash' helper function for TLS1's PRF.
1527 * It is used exclusively by tls1_prf. For details see RFC 2246, chapter 5.
1528 * The pseudo random stream generated by this function is exclusive or'ed with
1529 * the data in pbBuffer.
1531 * PARAMS
1532 * hHMAC [I] HMAC object, which will be used in pseudo random generation
1533 * pblobSeed [I] Seed value
1534 * pbBuffer [I/O] Pseudo random stream will be xor'ed to the provided data
1535 * dwBufferLen [I] Number of pseudo random bytes desired
1537 * RETURNS
1538 * Success: TRUE
1539 * Failure: FALSE
1541 static BOOL tls1_p(HCRYPTHASH hHMAC, const PCRYPT_DATA_BLOB pblobSeed, BYTE *pbBuffer,
1542 DWORD dwBufferLen)
1544 CRYPTHASH *pHMAC;
1545 BYTE abAi[RSAENH_MAX_HASH_SIZE];
1546 DWORD i = 0;
1548 if (!lookup_handle(&handle_table, hHMAC, RSAENH_MAGIC_HASH, (OBJECTHDR**)&pHMAC)) {
1549 SetLastError(NTE_BAD_HASH);
1550 return FALSE;
1553 /* compute A_1 = HMAC(seed) */
1554 init_hash(pHMAC);
1555 update_hash(pHMAC, pblobSeed->pbData, pblobSeed->cbData);
1556 finalize_hash(pHMAC);
1557 memcpy(abAi, pHMAC->abHashValue, pHMAC->dwHashSize);
1559 do {
1560 /* compute HMAC(A_i + seed) */
1561 init_hash(pHMAC);
1562 update_hash(pHMAC, abAi, pHMAC->dwHashSize);
1563 update_hash(pHMAC, pblobSeed->pbData, pblobSeed->cbData);
1564 finalize_hash(pHMAC);
1566 /* pseudo random stream := CONCAT_{i=1..n} ( HMAC(A_i + seed) ) */
1567 do {
1568 if (i >= dwBufferLen) break;
1569 pbBuffer[i] ^= pHMAC->abHashValue[i % pHMAC->dwHashSize];
1570 i++;
1571 } while (i % pHMAC->dwHashSize);
1573 /* compute A_{i+1} = HMAC(A_i) */
1574 init_hash(pHMAC);
1575 update_hash(pHMAC, abAi, pHMAC->dwHashSize);
1576 finalize_hash(pHMAC);
1577 memcpy(abAi, pHMAC->abHashValue, pHMAC->dwHashSize);
1578 } while (i < dwBufferLen);
1580 return TRUE;
1583 /******************************************************************************
1584 * tls1_prf [Internal]
1586 * TLS1 pseudo random function as specified in RFC 2246, chapter 5
1588 * PARAMS
1589 * hProv [I] Key container used to compute the pseudo random stream
1590 * hSecret [I] Key that holds the (pre-)master secret
1591 * pblobLabel [I] Descriptive label
1592 * pblobSeed [I] Seed value
1593 * pbBuffer [O] Pseudo random numbers will be stored here
1594 * dwBufferLen [I] Number of pseudo random bytes desired
1596 * RETURNS
1597 * Success: TRUE
1598 * Failure: FALSE
1600 static BOOL tls1_prf(HCRYPTPROV hProv, HCRYPTPROV hSecret, const PCRYPT_DATA_BLOB pblobLabel,
1601 const PCRYPT_DATA_BLOB pblobSeed, BYTE *pbBuffer, DWORD dwBufferLen)
1603 HMAC_INFO hmacInfo = { 0, NULL, 0, NULL, 0 };
1604 HCRYPTHASH hHMAC = (HCRYPTHASH)INVALID_HANDLE_VALUE;
1605 HCRYPTKEY hHalfSecret = (HCRYPTKEY)INVALID_HANDLE_VALUE;
1606 CRYPTKEY *pHalfSecret, *pSecret;
1607 DWORD dwHalfSecretLen;
1608 BOOL result = FALSE;
1609 CRYPT_DATA_BLOB blobLabelSeed;
1611 TRACE("(hProv=%08lx, hSecret=%08lx, pblobLabel=%p, pblobSeed=%p, pbBuffer=%p, dwBufferLen=%d)\n",
1612 hProv, hSecret, pblobLabel, pblobSeed, pbBuffer, dwBufferLen);
1614 if (!lookup_handle(&handle_table, hSecret, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pSecret)) {
1615 SetLastError(NTE_FAIL);
1616 return FALSE;
1619 dwHalfSecretLen = (pSecret->dwKeyLen+1)/2;
1621 /* concatenation of the label and the seed */
1622 if (!concat_data_blobs(&blobLabelSeed, pblobLabel, pblobSeed)) goto exit;
1624 /* zero out the buffer, since two random streams will be xor'ed into it. */
1625 memset(pbBuffer, 0, dwBufferLen);
1627 /* build a 'fake' key, to hold the secret. CALG_SSL2_MASTER is used since it provides
1628 * the biggest range of valid key lengths. */
1629 hHalfSecret = new_key(hProv, CALG_SSL2_MASTER, MAKELONG(0,dwHalfSecretLen*8), &pHalfSecret);
1630 if (hHalfSecret == (HCRYPTKEY)INVALID_HANDLE_VALUE) goto exit;
1632 /* Derive an HMAC_MD5 hash and call the helper function. */
1633 memcpy(pHalfSecret->abKeyValue, pSecret->abKeyValue, dwHalfSecretLen);
1634 if (!RSAENH_CPCreateHash(hProv, CALG_HMAC, hHalfSecret, 0, &hHMAC)) goto exit;
1635 hmacInfo.HashAlgid = CALG_MD5;
1636 if (!RSAENH_CPSetHashParam(hProv, hHMAC, HP_HMAC_INFO, (BYTE*)&hmacInfo, 0)) goto exit;
1637 if (!tls1_p(hHMAC, &blobLabelSeed, pbBuffer, dwBufferLen)) goto exit;
1639 /* Reconfigure to HMAC_SHA hash and call helper function again. */
1640 memcpy(pHalfSecret->abKeyValue, pSecret->abKeyValue + (pSecret->dwKeyLen/2), dwHalfSecretLen);
1641 hmacInfo.HashAlgid = CALG_SHA;
1642 if (!RSAENH_CPSetHashParam(hProv, hHMAC, HP_HMAC_INFO, (BYTE*)&hmacInfo, 0)) goto exit;
1643 if (!tls1_p(hHMAC, &blobLabelSeed, pbBuffer, dwBufferLen)) goto exit;
1645 result = TRUE;
1646 exit:
1647 release_handle(&handle_table, hHalfSecret, RSAENH_MAGIC_KEY);
1648 if (hHMAC != (HCRYPTHASH)INVALID_HANDLE_VALUE) RSAENH_CPDestroyHash(hProv, hHMAC);
1649 free_data_blob(&blobLabelSeed);
1650 return result;
1653 /******************************************************************************
1654 * pad_data_pkcs1 [Internal]
1656 * Helper function for data padding according to PKCS1 #2
1658 * PARAMS
1659 * abData [I] The data to be padded
1660 * dwDataLen [I] Length of the data
1661 * abBuffer [O] Padded data will be stored here
1662 * dwBufferLen [I] Length of the buffer (also length of padded data)
1663 * dwFlags [I] Padding format (CRYPT_SSL2_FALLBACK)
1665 * RETURN
1666 * Success: TRUE
1667 * Failure: FALSE (NTE_BAD_LEN, too much data to pad)
1669 static BOOL pad_data_pkcs1(const BYTE *abData, DWORD dwDataLen, BYTE *abBuffer, DWORD dwBufferLen, DWORD dwFlags)
1671 DWORD i;
1673 /* Ensure there is enough space for PKCS1 #2 padding */
1674 if (dwDataLen > dwBufferLen-11) {
1675 SetLastError(NTE_BAD_LEN);
1676 return FALSE;
1679 memmove(abBuffer + dwBufferLen - dwDataLen, abData, dwDataLen);
1681 abBuffer[0] = 0x00;
1682 abBuffer[1] = RSAENH_PKC_BLOCKTYPE;
1683 for (i=2; i < dwBufferLen - dwDataLen - 1; i++)
1684 do gen_rand_impl(&abBuffer[i], 1); while (!abBuffer[i]);
1685 if (dwFlags & CRYPT_SSL2_FALLBACK)
1686 for (i-=8; i < dwBufferLen - dwDataLen - 1; i++)
1687 abBuffer[i] = 0x03;
1688 abBuffer[i] = 0x00;
1690 return TRUE;
1693 /******************************************************************************
1694 * pkcs1_mgf1 [Internal]
1696 * MGF function for RSA EM-OAEP as specified in RFC 8017 PKCS #1 V2.2, Appendix B.2.1. MGF1
1698 * PARAMS
1699 * hProv [I] Cryptographic provider handle
1700 * pbSeed [I] Seed from which mask is generated
1701 * dwSeedLength [I] Length of pbSeed
1702 * dwLength [I] Intended length in octets of the mask
1703 * pbMask [O] Generated mask if success. Caller is responsible for freeing the mask when it's done
1705 * RETURNS
1706 * Success: TRUE
1707 * Failure: FALSE
1709 static BOOL pkcs1_mgf1(HCRYPTPROV hProv, const BYTE *pbSeed, DWORD dwSeedLength, DWORD dwLength, PCRYPT_DATA_BLOB pbMask)
1711 HCRYPTHASH hHash;
1712 BYTE *pbHashInput, *pbCounter;
1713 DWORD dwCounter;
1714 DWORD dwLen, dwHashLen;
1716 RSAENH_CPCreateHash(hProv, CALG_SHA1, 0, 0, &hHash);
1717 RSAENH_CPHashData(hProv, hHash, 0, 0, 0);
1718 dwLen = sizeof(dwHashLen);
1719 RSAENH_CPGetHashParam(hProv, hHash, HP_HASHSIZE, (BYTE *)&dwHashLen, &dwLen, 0);
1720 RSAENH_CPDestroyHash(hProv, hHash);
1722 /* Allocate multiples of hash value */
1723 pbMask->pbData = HeapAlloc(GetProcessHeap(), 0, (dwLength + dwHashLen - 1) / dwHashLen * dwHashLen);
1724 if (!pbMask->pbData)
1726 SetLastError(NTE_NO_MEMORY);
1727 return FALSE;
1729 pbMask->cbData = dwLength;
1731 pbHashInput = HeapAlloc(GetProcessHeap(), 0, dwSeedLength + sizeof(DWORD));
1732 if (!pbHashInput)
1734 free_data_blob(pbMask);
1735 SetLastError(NTE_NO_MEMORY);
1736 return FALSE;
1739 dwLen = dwHashLen;
1740 memcpy(pbHashInput, pbSeed, dwSeedLength);
1741 pbCounter = pbHashInput + dwSeedLength;
1742 for (dwCounter = 0; dwCounter < (dwLength + dwHashLen - 1) / dwHashLen; dwCounter++)
1744 *(pbCounter) = (BYTE)((dwCounter >> 24) & 0xff);
1745 *(pbCounter + 1) = (BYTE)((dwCounter >> 16) & 0xff);
1746 *(pbCounter + 2) = (BYTE)((dwCounter >> 8) & 0xff);
1747 *(pbCounter + 3) = (BYTE)(dwCounter & 0xff);
1748 RSAENH_CPCreateHash(hProv, CALG_SHA1, 0, 0, &hHash);
1749 RSAENH_CPHashData(hProv, hHash, pbHashInput, dwSeedLength + sizeof(DWORD), 0);
1750 /* pbMask->pbData = old pbMask->pbData || Hash(Seed || Counter) */
1751 RSAENH_CPGetHashParam(hProv, hHash, HP_HASHVAL, pbMask->pbData + dwCounter * dwHashLen, &dwLen, 0);
1752 RSAENH_CPDestroyHash(hProv, hHash);
1755 HeapFree(GetProcessHeap(), 0, pbHashInput);
1756 return TRUE;
1759 /******************************************************************************
1760 * pad_data_oaep [Internal]
1762 * Helper function for data OAEP padding scheme according to RFC 8017 PKCS #1 V2.2
1764 * PARAMS
1765 * hProv [I] Cryptographic provider handle
1766 * abData [I] The data to be padded
1767 * dwDataLen [I] Length of the data
1768 * abBuffer [O] Padded data will be stored here
1769 * dwBufferLen [I] Length of the buffer (also length of padded data)
1770 * dwFlags [I] Currently only CRYPT_OAEP is defined
1772 * RETURN
1773 * Success: TRUE
1774 * Failure: FALSE
1776 static BOOL pad_data_oaep(HCRYPTPROV hProv, const BYTE *abData, DWORD dwDataLen, BYTE *abBuffer, DWORD dwBufferLen,
1777 DWORD dwFlags)
1779 CRYPT_DATA_BLOB blobDbMask = {0}, blobSeedMask = {0};
1780 HCRYPTHASH hHash;
1781 BYTE *pbPadded = NULL, *pbDb, *pbSeed;
1782 DWORD dwLen, dwHashLen;
1783 DWORD dwDbLen, dwSeedLen;
1784 BOOL result, ret = FALSE;
1785 DWORD i;
1787 RSAENH_CPCreateHash(hProv, CALG_SHA1, 0, 0, &hHash);
1788 /* Empty label */
1789 RSAENH_CPHashData(hProv, hHash, 0, 0, 0);
1790 dwLen = sizeof(dwHashLen);
1791 RSAENH_CPGetHashParam(hProv, hHash, HP_HASHSIZE, (BYTE *)&dwHashLen, &dwLen, 0);
1793 if (dwDataLen > dwBufferLen - 2 * dwHashLen - 2)
1795 SetLastError(NTE_BAD_LEN);
1796 goto done;
1799 if (dwBufferLen < 2 * dwHashLen + 2)
1801 SetLastError(ERROR_MORE_DATA);
1802 goto done;
1805 pbPadded = HeapAlloc(GetProcessHeap(), 0, dwBufferLen);
1806 if (!pbPadded)
1808 SetLastError(NTE_NO_MEMORY);
1809 goto done;
1812 /* EM = 00 || maskedSeed || maskedDB */
1813 pbPadded[0] = 0;
1814 pbSeed = pbPadded + 1;
1815 dwSeedLen = dwHashLen;
1816 pbDb = pbPadded + 1 + dwHashLen;
1817 dwDbLen = dwBufferLen - dwSeedLen - 1;
1819 /* DB = pHash || PS || 01 || M */
1820 /* Set pHash in DB */
1821 dwLen = dwHashLen;
1822 RSAENH_CPGetHashParam(hProv, hHash, HP_HASHVAL, pbDb, &dwLen, 0);
1823 /* Set PS(zeros) in DB */
1824 memset(pbDb + dwHashLen, 0, dwDbLen - dwHashLen - 1 - dwDataLen);
1825 /* Set 01 in DB */
1826 pbDb[dwDbLen - dwDataLen - 1] = 1;
1827 /* Set M in DB */
1828 memcpy(pbDb + dwDbLen - dwDataLen, abData, dwDataLen);
1830 /* Get seed */
1831 gen_rand_impl(pbSeed, dwHashLen);
1832 /* Get masked DB */
1833 result = pkcs1_mgf1(hProv, pbSeed, dwHashLen, dwDbLen, &blobDbMask);
1834 if (!result) goto done;
1835 for (i = 0; i < dwDbLen; i++) pbDb[i] ^= blobDbMask.pbData[i];
1837 /* Get masked seed */
1838 result = pkcs1_mgf1(hProv, pbDb, dwDbLen, dwHashLen, &blobSeedMask);
1839 if (!result) goto done;
1840 for (i = 0; i < dwHashLen; i++) pbSeed[i] ^= blobSeedMask.pbData[i];
1842 memcpy(abBuffer, pbPadded, dwBufferLen);
1843 ret = TRUE;
1844 done:
1845 RSAENH_CPDestroyHash(hProv, hHash);
1846 HeapFree(GetProcessHeap(), 0, pbPadded);
1847 free_data_blob(&blobDbMask);
1848 free_data_blob(&blobSeedMask);
1849 return ret;
1852 /******************************************************************************
1853 * pad_data [Internal]
1855 * Helper function for data padding according to padding format
1857 * PARAMS
1858 * hProv [I] Cryptographic provider handle
1859 * abData [I] The data to be padded
1860 * dwDataLen [I] Length of the data
1861 * abBuffer [O] Padded data will be stored here
1862 * dwBufferLen [I] Length of the buffer (also length of padded data)
1863 * dwFlags [I] 0, CRYPT_SSL2_FALLBACK or CRYPT_OAEP
1865 * RETURN
1866 * Success: TRUE
1867 * Failure: FALSE
1869 static BOOL pad_data(HCRYPTPROV hProv, const BYTE *abData, DWORD dwDataLen, BYTE *abBuffer, DWORD dwBufferLen,
1870 DWORD dwFlags)
1872 if (dwFlags == CRYPT_OAEP)
1873 return pad_data_oaep(hProv, abData, dwDataLen, abBuffer, dwBufferLen, dwFlags);
1874 else
1875 return pad_data_pkcs1(abData, dwDataLen, abBuffer, dwBufferLen, dwFlags);
1878 /******************************************************************************
1879 * unpad_data_pkcs1 [Internal]
1881 * Remove the PKCS1 padding from RSA decrypted data
1883 * PARAMS
1884 * abData [I] The padded data
1885 * dwDataLen [I] Length of the padded data
1886 * abBuffer [O] Data without padding will be stored here
1887 * dwBufferLen [I/O] I: Length of the buffer, O: Length of unpadded data
1888 * dwFlags [I] Currently none defined
1890 * RETURNS
1891 * Success: TRUE
1892 * Failure: FALSE, (NTE_BAD_DATA, no valid PKCS1 padding or buffer too small)
1894 static BOOL unpad_data_pkcs1(const BYTE *abData, DWORD dwDataLen, BYTE *abBuffer, DWORD *dwBufferLen, DWORD dwFlags)
1896 DWORD i;
1898 if (dwDataLen < 3)
1900 SetLastError(NTE_BAD_DATA);
1901 return FALSE;
1903 for (i=2; i<dwDataLen; i++)
1904 if (!abData[i])
1905 break;
1907 if ((i == dwDataLen) || (*dwBufferLen < dwDataLen - i - 1) ||
1908 (abData[0] != 0x00) || (abData[1] != RSAENH_PKC_BLOCKTYPE))
1910 SetLastError(NTE_BAD_DATA);
1911 return FALSE;
1914 *dwBufferLen = dwDataLen - i - 1;
1915 memmove(abBuffer, abData + i + 1, *dwBufferLen);
1916 return TRUE;
1919 /******************************************************************************
1920 * unpad_data_oaep [Internal]
1922 * Remove the OAEP padding from RSA decrypted data
1924 * PARAMS
1925 * hProv [I] Cryptographic provider handle
1926 * abData [I] The padded data
1927 * dwDataLen [I] Length of the padded data
1928 * abBuffer [O] Data without padding will be stored here
1929 * dwBufferLen [I/O] I: Length of the buffer, O: Length of unpadded data
1930 * dwFlags [I] Currently only CRYPT_OAEP is defined
1932 * RETURNS
1933 * Success: TRUE
1934 * Failure: FALSE
1936 static BOOL unpad_data_oaep(HCRYPTPROV hProv, const BYTE *abData, DWORD dwDataLen, BYTE *abBuffer, DWORD *dwBufferLen,
1937 DWORD dwFlags)
1939 CRYPT_DATA_BLOB blobDbMask = {0}, blobSeedMask = {0};
1940 HCRYPTHASH hHash;
1941 BYTE *pbBuffer = NULL, *pbHashValue = NULL;
1942 const BYTE *pbPaddedSeed, *pbPaddedDb;
1943 BYTE *pbUnpaddedSeed, *pbUnpaddedDb;
1944 DWORD dwLen, dwHashLen;
1945 DWORD dwSeedLen, dwDbLen;
1946 DWORD dwZeroCount, dwMsgCount;
1947 BOOL result, ret = FALSE;
1948 DWORD i;
1950 RSAENH_CPCreateHash(hProv, CALG_SHA1, 0, 0, &hHash);
1951 RSAENH_CPHashData(hProv, hHash, 0, 0, 0);
1952 dwLen = sizeof(dwHashLen);
1953 RSAENH_CPGetHashParam(hProv, hHash, HP_HASHSIZE, (BYTE *)&dwHashLen, &dwLen, 0);
1954 if (dwDataLen < 2 * dwHashLen + 2)
1956 SetLastError(NTE_BAD_DATA);
1957 goto done;
1960 /* Get default hash value */
1961 pbHashValue = HeapAlloc(GetProcessHeap(), 0, dwHashLen);
1962 if (!pbHashValue)
1964 SetLastError(NTE_NO_MEMORY);
1965 goto done;
1967 dwLen = dwHashLen;
1968 RSAENH_CPGetHashParam(hProv, hHash, HP_HASHVAL, pbHashValue, &dwLen, 0);
1970 /* Store seed and DB */
1971 pbBuffer = HeapAlloc(GetProcessHeap(), 0, dwDataLen - 1);
1972 if (!pbBuffer)
1974 SetLastError(NTE_NO_MEMORY);
1975 goto done;
1978 pbPaddedSeed = abData + 1;
1979 pbPaddedDb = abData + 1 + dwHashLen;
1980 pbUnpaddedSeed = pbBuffer;
1981 pbUnpaddedDb = pbBuffer + dwHashLen;
1982 dwSeedLen = dwHashLen;
1983 dwDbLen = dwDataLen - dwHashLen - 1;
1985 /* Get unpadded seed */
1986 result = pkcs1_mgf1(hProv, pbPaddedDb, dwDbLen, dwSeedLen, &blobSeedMask);
1987 if (!result) goto done;
1988 for (i = 0; i < dwSeedLen; i++) pbUnpaddedSeed[i] = pbPaddedSeed[i] ^ blobSeedMask.pbData[i];
1990 /* Get unpadded DB */
1991 result = pkcs1_mgf1(hProv, pbUnpaddedSeed, dwSeedLen, dwDbLen, &blobDbMask);
1992 if (!result) goto done;
1993 for (i = 0; i < dwDbLen; i++) pbUnpaddedDb[i] = pbPaddedDb[i] ^ blobDbMask.pbData[i];
1995 /* Compare hash in DB */
1996 result = memcmp(pbUnpaddedDb, pbHashValue, dwHashLen);
1998 /* Get count of zero paddings(PS) */
1999 dwZeroCount = 0;
2000 while (dwHashLen + dwZeroCount + 1 <= dwDbLen && pbUnpaddedDb[dwHashLen + dwZeroCount] == 0) dwZeroCount++;
2001 dwMsgCount = dwDbLen - dwHashLen - dwZeroCount - 1;
2003 if (dwHashLen + dwZeroCount + 1 > dwDbLen || abData[0] || result || pbUnpaddedDb[dwHashLen + dwZeroCount] != 1
2004 || *dwBufferLen < dwMsgCount)
2006 SetLastError(NTE_BAD_DATA);
2007 goto done;
2010 *dwBufferLen = dwMsgCount;
2011 memcpy(abBuffer, pbUnpaddedDb + dwHashLen + dwZeroCount + 1, dwMsgCount);
2012 ret = TRUE;
2013 done:
2014 RSAENH_CPDestroyHash(hProv, hHash);
2015 HeapFree(GetProcessHeap(), 0, pbHashValue);
2016 HeapFree(GetProcessHeap(), 0, pbBuffer);
2017 free_data_blob(&blobDbMask);
2018 free_data_blob(&blobSeedMask);
2019 return ret;
2022 /******************************************************************************
2023 * unpad_data [Internal]
2025 * Remove the padding from RSA decrypted data according to padding format
2027 * PARAMS
2028 * hProv [I] Cryptographic provider handle
2029 * abData [I] The padded data
2030 * dwDataLen [I] Length of the padded data
2031 * abBuffer [O] Data without padding will be stored here
2032 * dwBufferLen [I/O] I: Length of the buffer, O: Length of unpadded data
2033 * dwFlags [I] 0 or CRYPT_OAEP
2035 * RETURNS
2036 * Success: TRUE
2037 * Failure: FALSE
2039 static BOOL unpad_data(HCRYPTPROV hProv, const BYTE *abData, DWORD dwDataLen, BYTE *abBuffer, DWORD *dwBufferLen,
2040 DWORD dwFlags)
2042 if (dwFlags == CRYPT_OAEP)
2043 return unpad_data_oaep(hProv, abData, dwDataLen, abBuffer, dwBufferLen, dwFlags);
2044 else
2045 return unpad_data_pkcs1(abData, dwDataLen, abBuffer, dwBufferLen, dwFlags);
2048 /******************************************************************************
2049 * CPAcquireContext (RSAENH.@)
2051 * Acquire a handle to the key container specified by pszContainer
2053 * PARAMS
2054 * phProv [O] Pointer to the location the acquired handle will be written to.
2055 * pszContainer [I] Name of the desired key container. See Notes
2056 * dwFlags [I] Flags. See Notes.
2057 * pVTable [I] Pointer to a PVTableProvStruct containing callbacks.
2059 * RETURNS
2060 * Success: TRUE
2061 * Failure: FALSE
2063 * NOTES
2064 * If pszContainer is NULL or points to a zero length string the user's login
2065 * name will be used as the key container name.
2067 * If the CRYPT_NEW_KEYSET flag is set in dwFlags a new keyset will be created.
2068 * If a keyset with the given name already exists, the function fails and sets
2069 * last error to NTE_EXISTS. If CRYPT_NEW_KEYSET is not set and the specified
2070 * key container does not exist, function fails and sets last error to
2071 * NTE_BAD_KEYSET.
2073 BOOL WINAPI RSAENH_CPAcquireContext(HCRYPTPROV *phProv, LPSTR pszContainer,
2074 DWORD dwFlags, PVTableProvStruc pVTable)
2076 CHAR szKeyContainerName[MAX_PATH];
2078 TRACE("(phProv=%p, pszContainer=%s, dwFlags=%08x, pVTable=%p)\n", phProv,
2079 debugstr_a(pszContainer), dwFlags, pVTable);
2081 if (pszContainer && *pszContainer)
2083 lstrcpynA(szKeyContainerName, pszContainer, MAX_PATH);
2085 else
2087 DWORD dwLen = sizeof(szKeyContainerName);
2088 if (!GetUserNameA(szKeyContainerName, &dwLen)) return FALSE;
2091 switch (dwFlags & (CRYPT_NEWKEYSET|CRYPT_VERIFYCONTEXT|CRYPT_DELETEKEYSET))
2093 case 0:
2094 *phProv = read_key_container(szKeyContainerName, dwFlags, pVTable);
2095 break;
2097 case CRYPT_DELETEKEYSET:
2098 return delete_container_key(szKeyContainerName, dwFlags);
2100 case CRYPT_NEWKEYSET:
2101 *phProv = read_key_container(szKeyContainerName, dwFlags, pVTable);
2102 if (*phProv != (HCRYPTPROV)INVALID_HANDLE_VALUE)
2104 release_handle(&handle_table, *phProv, RSAENH_MAGIC_CONTAINER);
2105 TRACE("Can't create new keyset, already exists\n");
2106 SetLastError(NTE_EXISTS);
2107 return FALSE;
2109 *phProv = new_key_container(szKeyContainerName, dwFlags, pVTable);
2110 break;
2112 case CRYPT_VERIFYCONTEXT|CRYPT_NEWKEYSET:
2113 case CRYPT_VERIFYCONTEXT:
2114 if (pszContainer && *pszContainer) {
2115 TRACE("pszContainer should be empty\n");
2116 SetLastError(NTE_BAD_FLAGS);
2117 return FALSE;
2119 *phProv = new_key_container("", dwFlags, pVTable);
2120 break;
2122 default:
2123 *phProv = (HCRYPTPROV)INVALID_HANDLE_VALUE;
2124 SetLastError(NTE_BAD_FLAGS);
2125 return FALSE;
2128 if (*phProv != (HCRYPTPROV)INVALID_HANDLE_VALUE) {
2129 SetLastError(ERROR_SUCCESS);
2130 return TRUE;
2131 } else {
2132 return FALSE;
2136 /******************************************************************************
2137 * CPCreateHash (RSAENH.@)
2139 * CPCreateHash creates and initializes a new hash object.
2141 * PARAMS
2142 * hProv [I] Handle to the key container to which the new hash will belong.
2143 * Algid [I] Identifies the hash algorithm, which will be used for the hash.
2144 * hKey [I] Handle to a session key applied for keyed hashes.
2145 * dwFlags [I] Currently no flags defined. Must be zero.
2146 * phHash [O] Points to the location where a handle to the new hash will be stored.
2148 * RETURNS
2149 * Success: TRUE
2150 * Failure: FALSE
2152 * NOTES
2153 * hKey is a handle to a session key applied in keyed hashes like MAC and HMAC.
2154 * If a normal hash object is to be created (like e.g. MD2 or SHA1) hKey must be zero.
2156 BOOL WINAPI RSAENH_CPCreateHash(HCRYPTPROV hProv, ALG_ID Algid, HCRYPTKEY hKey, DWORD dwFlags,
2157 HCRYPTHASH *phHash)
2159 CRYPTKEY *pCryptKey;
2160 CRYPTHASH *pCryptHash;
2161 const PROV_ENUMALGS_EX *peaAlgidInfo;
2163 TRACE("(hProv=%08lx, Algid=%08x, hKey=%08lx, dwFlags=%08x, phHash=%p)\n", hProv, Algid, hKey,
2164 dwFlags, phHash);
2166 peaAlgidInfo = get_algid_info(hProv, Algid);
2167 if (!peaAlgidInfo) return FALSE;
2169 if (dwFlags)
2171 SetLastError(NTE_BAD_FLAGS);
2172 return FALSE;
2175 if (Algid == CALG_MAC || Algid == CALG_HMAC || Algid == CALG_SCHANNEL_MASTER_HASH ||
2176 Algid == CALG_TLS1PRF)
2178 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey)) {
2179 SetLastError(NTE_BAD_KEY);
2180 return FALSE;
2183 if ((Algid == CALG_MAC) && (GET_ALG_TYPE(pCryptKey->aiAlgid) != ALG_TYPE_BLOCK)) {
2184 SetLastError(NTE_BAD_KEY);
2185 return FALSE;
2188 if ((Algid == CALG_SCHANNEL_MASTER_HASH || Algid == CALG_TLS1PRF) &&
2189 (pCryptKey->aiAlgid != CALG_TLS1_MASTER))
2191 SetLastError(NTE_BAD_KEY);
2192 return FALSE;
2194 if (Algid == CALG_SCHANNEL_MASTER_HASH &&
2195 ((!pCryptKey->siSChannelInfo.blobClientRandom.cbData) ||
2196 (!pCryptKey->siSChannelInfo.blobServerRandom.cbData)))
2198 SetLastError(ERROR_INVALID_PARAMETER);
2199 return FALSE;
2202 if ((Algid == CALG_TLS1PRF) && (pCryptKey->dwState != RSAENH_KEYSTATE_MASTERKEY)) {
2203 SetLastError(NTE_BAD_KEY_STATE);
2204 return FALSE;
2208 *phHash = new_object(&handle_table, sizeof(CRYPTHASH), RSAENH_MAGIC_HASH,
2209 destroy_hash, (OBJECTHDR**)&pCryptHash);
2210 if (!pCryptHash) return FALSE;
2212 pCryptHash->aiAlgid = Algid;
2213 pCryptHash->hKey = hKey;
2214 pCryptHash->hProv = hProv;
2215 pCryptHash->dwState = RSAENH_HASHSTATE_HASHING;
2216 pCryptHash->pHMACInfo = NULL;
2217 pCryptHash->dwHashSize = peaAlgidInfo->dwDefaultLen >> 3;
2218 init_data_blob(&pCryptHash->tpPRFParams.blobLabel);
2219 init_data_blob(&pCryptHash->tpPRFParams.blobSeed);
2221 if (Algid == CALG_SCHANNEL_MASTER_HASH) {
2222 static const char keyex[] = "key expansion";
2223 BYTE key_expansion[sizeof keyex];
2224 CRYPT_DATA_BLOB blobRandom, blobKeyExpansion = { 13, key_expansion };
2226 memcpy( key_expansion, keyex, sizeof keyex );
2228 if (pCryptKey->dwState != RSAENH_KEYSTATE_MASTERKEY) {
2229 static const char msec[] = "master secret";
2230 BYTE master_secret[sizeof msec];
2231 CRYPT_DATA_BLOB blobLabel = { 13, master_secret };
2232 BYTE abKeyValue[48];
2234 memcpy( master_secret, msec, sizeof msec );
2236 /* See RFC 2246, chapter 8.1 */
2237 if (!concat_data_blobs(&blobRandom,
2238 &pCryptKey->siSChannelInfo.blobClientRandom,
2239 &pCryptKey->siSChannelInfo.blobServerRandom))
2241 return FALSE;
2243 tls1_prf(hProv, hKey, &blobLabel, &blobRandom, abKeyValue, 48);
2244 pCryptKey->dwState = RSAENH_KEYSTATE_MASTERKEY;
2245 memcpy(pCryptKey->abKeyValue, abKeyValue, 48);
2246 free_data_blob(&blobRandom);
2249 /* See RFC 2246, chapter 6.3 */
2250 if (!concat_data_blobs(&blobRandom,
2251 &pCryptKey->siSChannelInfo.blobServerRandom,
2252 &pCryptKey->siSChannelInfo.blobClientRandom))
2254 return FALSE;
2256 tls1_prf(hProv, hKey, &blobKeyExpansion, &blobRandom, pCryptHash->abHashValue,
2257 RSAENH_MAX_HASH_SIZE);
2258 free_data_blob(&blobRandom);
2261 return init_hash(pCryptHash);
2264 /******************************************************************************
2265 * CPDestroyHash (RSAENH.@)
2267 * Releases the handle to a hash object. The object is destroyed if its reference
2268 * count reaches zero.
2270 * PARAMS
2271 * hProv [I] Handle to the key container to which the hash object belongs.
2272 * hHash [I] Handle to the hash object to be released.
2274 * RETURNS
2275 * Success: TRUE
2276 * Failure: FALSE
2278 BOOL WINAPI RSAENH_CPDestroyHash(HCRYPTPROV hProv, HCRYPTHASH hHash)
2280 TRACE("(hProv=%08lx, hHash=%08lx)\n", hProv, hHash);
2282 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2284 SetLastError(NTE_BAD_UID);
2285 return FALSE;
2288 if (!release_handle(&handle_table, hHash, RSAENH_MAGIC_HASH))
2290 SetLastError(NTE_BAD_HASH);
2291 return FALSE;
2294 return TRUE;
2297 /******************************************************************************
2298 * CPDestroyKey (RSAENH.@)
2300 * Releases the handle to a key object. The object is destroyed if its reference
2301 * count reaches zero.
2303 * PARAMS
2304 * hProv [I] Handle to the key container to which the key object belongs.
2305 * hKey [I] Handle to the key object to be released.
2307 * RETURNS
2308 * Success: TRUE
2309 * Failure: FALSE
2311 BOOL WINAPI RSAENH_CPDestroyKey(HCRYPTPROV hProv, HCRYPTKEY hKey)
2313 TRACE("(hProv=%08lx, hKey=%08lx)\n", hProv, hKey);
2315 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2317 SetLastError(NTE_BAD_UID);
2318 return FALSE;
2321 if (!release_handle(&handle_table, hKey, RSAENH_MAGIC_KEY))
2323 SetLastError(NTE_BAD_KEY);
2324 return FALSE;
2327 return TRUE;
2330 /******************************************************************************
2331 * CPDuplicateHash (RSAENH.@)
2333 * Clones a hash object including its current state.
2335 * PARAMS
2336 * hUID [I] Handle to the key container the hash belongs to.
2337 * hHash [I] Handle to the hash object to be cloned.
2338 * pdwReserved [I] Reserved. Must be NULL.
2339 * dwFlags [I] No flags are currently defined. Must be 0.
2340 * phHash [O] Handle to the cloned hash object.
2342 * RETURNS
2343 * Success: TRUE.
2344 * Failure: FALSE.
2346 BOOL WINAPI RSAENH_CPDuplicateHash(HCRYPTPROV hUID, HCRYPTHASH hHash, DWORD *pdwReserved,
2347 DWORD dwFlags, HCRYPTHASH *phHash)
2349 CRYPTHASH *pSrcHash, *pDestHash;
2351 TRACE("(hUID=%08lx, hHash=%08lx, pdwReserved=%p, dwFlags=%08x, phHash=%p)\n", hUID, hHash,
2352 pdwReserved, dwFlags, phHash);
2354 if (!is_valid_handle(&handle_table, hUID, RSAENH_MAGIC_CONTAINER))
2356 SetLastError(NTE_BAD_UID);
2357 return FALSE;
2360 if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH, (OBJECTHDR**)&pSrcHash))
2362 SetLastError(NTE_BAD_HASH);
2363 return FALSE;
2366 if (!phHash || pdwReserved || dwFlags)
2368 SetLastError(ERROR_INVALID_PARAMETER);
2369 return FALSE;
2372 *phHash = new_object(&handle_table, sizeof(CRYPTHASH), RSAENH_MAGIC_HASH,
2373 destroy_hash, (OBJECTHDR**)&pDestHash);
2374 if (*phHash != (HCRYPTHASH)INVALID_HANDLE_VALUE)
2376 *pDestHash = *pSrcHash;
2377 duplicate_hash_impl(&pSrcHash->context, &pDestHash->context);
2378 copy_hmac_info(&pDestHash->pHMACInfo, pSrcHash->pHMACInfo);
2379 copy_data_blob(&pDestHash->tpPRFParams.blobLabel, &pSrcHash->tpPRFParams.blobLabel);
2380 copy_data_blob(&pDestHash->tpPRFParams.blobSeed, &pSrcHash->tpPRFParams.blobSeed);
2383 return *phHash != (HCRYPTHASH)INVALID_HANDLE_VALUE;
2386 /******************************************************************************
2387 * CPDuplicateKey (RSAENH.@)
2389 * Clones a key object including its current state.
2391 * PARAMS
2392 * hUID [I] Handle to the key container the hash belongs to.
2393 * hKey [I] Handle to the key object to be cloned.
2394 * pdwReserved [I] Reserved. Must be NULL.
2395 * dwFlags [I] No flags are currently defined. Must be 0.
2396 * phHash [O] Handle to the cloned key object.
2398 * RETURNS
2399 * Success: TRUE.
2400 * Failure: FALSE.
2402 BOOL WINAPI RSAENH_CPDuplicateKey(HCRYPTPROV hUID, HCRYPTKEY hKey, DWORD *pdwReserved,
2403 DWORD dwFlags, HCRYPTKEY *phKey)
2405 CRYPTKEY *pSrcKey, *pDestKey;
2407 TRACE("(hUID=%08lx, hKey=%08lx, pdwReserved=%p, dwFlags=%08x, phKey=%p)\n", hUID, hKey,
2408 pdwReserved, dwFlags, phKey);
2410 if (!is_valid_handle(&handle_table, hUID, RSAENH_MAGIC_CONTAINER))
2412 SetLastError(NTE_BAD_UID);
2413 return FALSE;
2416 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pSrcKey))
2418 SetLastError(NTE_BAD_KEY);
2419 return FALSE;
2422 if (!phKey || pdwReserved || dwFlags)
2424 SetLastError(ERROR_INVALID_PARAMETER);
2425 return FALSE;
2428 *phKey = new_object(&handle_table, sizeof(CRYPTKEY), RSAENH_MAGIC_KEY, destroy_key,
2429 (OBJECTHDR**)&pDestKey);
2430 if (*phKey != (HCRYPTKEY)INVALID_HANDLE_VALUE)
2432 *pDestKey = *pSrcKey;
2433 copy_data_blob(&pDestKey->siSChannelInfo.blobServerRandom,
2434 &pSrcKey->siSChannelInfo.blobServerRandom);
2435 copy_data_blob(&pDestKey->siSChannelInfo.blobClientRandom,
2436 &pSrcKey->siSChannelInfo.blobClientRandom);
2437 duplicate_key_impl(pSrcKey->aiAlgid, &pSrcKey->context, &pDestKey->context);
2438 return TRUE;
2440 else
2442 return FALSE;
2446 /******************************************************************************
2447 * CPEncrypt (RSAENH.@)
2449 * Encrypt data.
2451 * PARAMS
2452 * hProv [I] The key container hKey and hHash belong to.
2453 * hKey [I] The key used to encrypt the data.
2454 * hHash [I] An optional hash object for parallel hashing. See notes.
2455 * Final [I] Indicates if this is the last block of data to encrypt.
2456 * dwFlags [I] Must be zero or CRYPT_OAEP
2457 * pbData [I/O] Pointer to the data to encrypt. Encrypted data will also be stored there.
2458 * pdwDataLen [I/O] I: Length of data to encrypt, O: Length of encrypted data.
2459 * dwBufLen [I] Size of the buffer at pbData.
2461 * RETURNS
2462 * Success: TRUE.
2463 * Failure: FALSE.
2465 * NOTES
2466 * If a hash object handle is provided in hHash, it will be updated with the plaintext.
2467 * This is useful for message signatures.
2469 * This function uses the standard WINAPI protocol for querying data of dynamic length.
2471 BOOL WINAPI RSAENH_CPEncrypt(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final,
2472 DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen, DWORD dwBufLen)
2474 CRYPTKEY *pCryptKey;
2475 BYTE *in, out[RSAENH_MAX_BLOCK_SIZE], o[RSAENH_MAX_BLOCK_SIZE];
2476 DWORD dwEncryptedLen, i, j, k;
2478 TRACE("(hProv=%08lx, hKey=%08lx, hHash=%08lx, Final=%d, dwFlags=%08x, pbData=%p, "
2479 "pdwDataLen=%p, dwBufLen=%d)\n", hProv, hKey, hHash, Final, dwFlags, pbData, pdwDataLen,
2480 dwBufLen);
2482 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2484 SetLastError(NTE_BAD_UID);
2485 return FALSE;
2488 if (dwFlags != 0 && dwFlags != CRYPT_OAEP)
2490 SetLastError(NTE_BAD_FLAGS);
2491 return FALSE;
2494 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2496 SetLastError(NTE_BAD_KEY);
2497 return FALSE;
2500 if (pCryptKey->dwState == RSAENH_KEYSTATE_IDLE)
2501 pCryptKey->dwState = RSAENH_KEYSTATE_ENCRYPTING;
2503 if (pCryptKey->dwState != RSAENH_KEYSTATE_ENCRYPTING)
2505 SetLastError(NTE_BAD_DATA);
2506 return FALSE;
2509 if (is_valid_handle(&handle_table, hHash, RSAENH_MAGIC_HASH)) {
2510 if (!RSAENH_CPHashData(hProv, hHash, pbData, *pdwDataLen, 0)) return FALSE;
2513 if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_BLOCK) {
2514 if (!Final && (*pdwDataLen % pCryptKey->dwBlockLen)) {
2515 SetLastError(NTE_BAD_DATA);
2516 return FALSE;
2519 dwEncryptedLen = (*pdwDataLen/pCryptKey->dwBlockLen+(Final?1:0))*pCryptKey->dwBlockLen;
2521 if (pbData == NULL) {
2522 *pdwDataLen = dwEncryptedLen;
2523 return TRUE;
2525 else if (dwEncryptedLen > dwBufLen) {
2526 *pdwDataLen = dwEncryptedLen;
2527 SetLastError(ERROR_MORE_DATA);
2528 return FALSE;
2531 /* Pad final block with length bytes */
2532 for (i=*pdwDataLen; i<dwEncryptedLen; i++) pbData[i] = dwEncryptedLen - *pdwDataLen;
2533 *pdwDataLen = dwEncryptedLen;
2535 for (i=0, in=pbData; i<*pdwDataLen; i+=pCryptKey->dwBlockLen, in+=pCryptKey->dwBlockLen) {
2536 switch (pCryptKey->dwMode) {
2537 case CRYPT_MODE_ECB:
2538 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out,
2539 RSAENH_ENCRYPT);
2540 break;
2542 case CRYPT_MODE_CBC:
2543 for (j=0; j<pCryptKey->dwBlockLen; j++) in[j] ^= pCryptKey->abChainVector[j];
2544 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out,
2545 RSAENH_ENCRYPT);
2546 memcpy(pCryptKey->abChainVector, out, pCryptKey->dwBlockLen);
2547 break;
2549 case CRYPT_MODE_CFB:
2550 for (j=0; j<pCryptKey->dwBlockLen; j++) {
2551 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context,
2552 pCryptKey->abChainVector, o, RSAENH_ENCRYPT);
2553 out[j] = in[j] ^ o[0];
2554 for (k=0; k<pCryptKey->dwBlockLen-1; k++)
2555 pCryptKey->abChainVector[k] = pCryptKey->abChainVector[k+1];
2556 pCryptKey->abChainVector[k] = out[j];
2558 break;
2560 default:
2561 SetLastError(NTE_BAD_ALGID);
2562 return FALSE;
2564 memcpy(in, out, pCryptKey->dwBlockLen);
2566 } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_STREAM) {
2567 if (pbData == NULL) {
2568 *pdwDataLen = dwBufLen;
2569 return TRUE;
2571 encrypt_stream_impl(pCryptKey->aiAlgid, &pCryptKey->context, pbData, *pdwDataLen);
2572 } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_RSA) {
2573 if (pCryptKey->aiAlgid == CALG_RSA_SIGN) {
2574 SetLastError(NTE_BAD_KEY);
2575 return FALSE;
2577 if (!pbData) {
2578 *pdwDataLen = pCryptKey->dwBlockLen;
2579 return TRUE;
2581 if (dwBufLen < pCryptKey->dwBlockLen) {
2582 SetLastError(ERROR_MORE_DATA);
2583 return FALSE;
2585 if (!pad_data(hProv, pbData, *pdwDataLen, pbData, pCryptKey->dwBlockLen, dwFlags)) return FALSE;
2586 encrypt_block_impl(pCryptKey->aiAlgid, PK_PUBLIC, &pCryptKey->context, pbData, pbData, RSAENH_ENCRYPT);
2587 *pdwDataLen = pCryptKey->dwBlockLen;
2588 Final = TRUE;
2589 } else {
2590 SetLastError(NTE_BAD_TYPE);
2591 return FALSE;
2594 if (Final) setup_key(pCryptKey);
2596 return TRUE;
2599 /******************************************************************************
2600 * CPDecrypt (RSAENH.@)
2602 * Decrypt data.
2604 * PARAMS
2605 * hProv [I] The key container hKey and hHash belong to.
2606 * hKey [I] The key used to decrypt the data.
2607 * hHash [I] An optional hash object for parallel hashing. See notes.
2608 * Final [I] Indicates if this is the last block of data to decrypt.
2609 * dwFlags [I] Must be zero or CRYPT_OAEP
2610 * pbData [I/O] Pointer to the data to decrypt. Plaintext will also be stored there.
2611 * pdwDataLen [I/O] I: Length of ciphertext, O: Length of plaintext.
2613 * RETURNS
2614 * Success: TRUE.
2615 * Failure: FALSE.
2617 * NOTES
2618 * If a hash object handle is provided in hHash, it will be updated with the plaintext.
2619 * This is useful for message signatures.
2621 * This function uses the standard WINAPI protocol for querying data of dynamic length.
2623 BOOL WINAPI RSAENH_CPDecrypt(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final,
2624 DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2626 CRYPTKEY *pCryptKey;
2627 BYTE *in, out[RSAENH_MAX_BLOCK_SIZE], o[RSAENH_MAX_BLOCK_SIZE];
2628 DWORD i, j, k;
2629 DWORD dwMax;
2631 TRACE("(hProv=%08lx, hKey=%08lx, hHash=%08lx, Final=%d, dwFlags=%08x, pbData=%p, "
2632 "pdwDataLen=%p)\n", hProv, hKey, hHash, Final, dwFlags, pbData, pdwDataLen);
2634 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2636 SetLastError(NTE_BAD_UID);
2637 return FALSE;
2640 if (dwFlags != 0 && dwFlags != CRYPT_OAEP)
2642 SetLastError(NTE_BAD_FLAGS);
2643 return FALSE;
2646 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2648 SetLastError(NTE_BAD_KEY);
2649 return FALSE;
2652 if (pCryptKey->dwState == RSAENH_KEYSTATE_IDLE)
2653 pCryptKey->dwState = RSAENH_KEYSTATE_ENCRYPTING;
2655 if (pCryptKey->dwState != RSAENH_KEYSTATE_ENCRYPTING)
2657 SetLastError(NTE_BAD_DATA);
2658 return FALSE;
2661 dwMax=*pdwDataLen;
2663 if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_BLOCK) {
2664 for (i=0, in=pbData; i<*pdwDataLen; i+=pCryptKey->dwBlockLen, in+=pCryptKey->dwBlockLen) {
2665 switch (pCryptKey->dwMode) {
2666 case CRYPT_MODE_ECB:
2667 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out,
2668 RSAENH_DECRYPT);
2669 break;
2671 case CRYPT_MODE_CBC:
2672 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out,
2673 RSAENH_DECRYPT);
2674 for (j=0; j<pCryptKey->dwBlockLen; j++) out[j] ^= pCryptKey->abChainVector[j];
2675 memcpy(pCryptKey->abChainVector, in, pCryptKey->dwBlockLen);
2676 break;
2678 case CRYPT_MODE_CFB:
2679 for (j=0; j<pCryptKey->dwBlockLen; j++) {
2680 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context,
2681 pCryptKey->abChainVector, o, RSAENH_ENCRYPT);
2682 out[j] = in[j] ^ o[0];
2683 for (k=0; k<pCryptKey->dwBlockLen-1; k++)
2684 pCryptKey->abChainVector[k] = pCryptKey->abChainVector[k+1];
2685 pCryptKey->abChainVector[k] = in[j];
2687 break;
2689 default:
2690 SetLastError(NTE_BAD_ALGID);
2691 return FALSE;
2693 memcpy(in, out, pCryptKey->dwBlockLen);
2695 if (Final) {
2696 if (pbData[*pdwDataLen-1] &&
2697 pbData[*pdwDataLen-1] <= pCryptKey->dwBlockLen &&
2698 pbData[*pdwDataLen-1] <= *pdwDataLen) {
2699 BOOL padOkay = TRUE;
2701 /* check that every bad byte has the same value */
2702 for (i = 1; padOkay && i < pbData[*pdwDataLen-1]; i++)
2703 if (pbData[*pdwDataLen - i - 1] != pbData[*pdwDataLen - 1])
2704 padOkay = FALSE;
2705 if (padOkay)
2706 *pdwDataLen -= pbData[*pdwDataLen-1];
2707 else {
2708 SetLastError(NTE_BAD_DATA);
2709 setup_key(pCryptKey);
2710 return FALSE;
2713 else {
2714 SetLastError(NTE_BAD_DATA);
2715 setup_key(pCryptKey);
2716 return FALSE;
2720 } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_STREAM) {
2721 encrypt_stream_impl(pCryptKey->aiAlgid, &pCryptKey->context, pbData, *pdwDataLen);
2722 } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_RSA) {
2723 if (pCryptKey->aiAlgid == CALG_RSA_SIGN) {
2724 SetLastError(NTE_BAD_KEY);
2725 return FALSE;
2727 encrypt_block_impl(pCryptKey->aiAlgid, PK_PRIVATE, &pCryptKey->context, pbData, pbData, RSAENH_DECRYPT);
2728 if (!unpad_data(hProv, pbData, pCryptKey->dwBlockLen, pbData, pdwDataLen, dwFlags)) return FALSE;
2729 Final = TRUE;
2730 } else {
2731 SetLastError(NTE_BAD_TYPE);
2732 return FALSE;
2735 if (Final) setup_key(pCryptKey);
2737 if (is_valid_handle(&handle_table, hHash, RSAENH_MAGIC_HASH)) {
2738 if (*pdwDataLen>dwMax ||
2739 !RSAENH_CPHashData(hProv, hHash, pbData, *pdwDataLen, 0)) return FALSE;
2742 return TRUE;
2745 static BOOL crypt_export_simple(CRYPTKEY *pCryptKey, CRYPTKEY *pPubKey,
2746 DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2748 BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2749 ALG_ID *pAlgid = (ALG_ID*)(pBlobHeader+1);
2750 DWORD dwDataLen;
2752 if (!(GET_ALG_CLASS(pCryptKey->aiAlgid)&(ALG_CLASS_DATA_ENCRYPT|ALG_CLASS_MSG_ENCRYPT))) {
2753 SetLastError(NTE_BAD_KEY); /* FIXME: error code? */
2754 return FALSE;
2757 dwDataLen = sizeof(BLOBHEADER) + sizeof(ALG_ID) + pPubKey->dwBlockLen;
2758 if (pbData) {
2759 if (*pdwDataLen < dwDataLen) {
2760 SetLastError(ERROR_MORE_DATA);
2761 *pdwDataLen = dwDataLen;
2762 return FALSE;
2765 pBlobHeader->bType = SIMPLEBLOB;
2766 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2767 pBlobHeader->reserved = 0;
2768 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2770 *pAlgid = pPubKey->aiAlgid;
2772 if (!pad_data(pCryptKey->hProv, pCryptKey->abKeyValue, pCryptKey->dwKeyLen, (BYTE*)(pAlgid+1),
2773 pPubKey->dwBlockLen, dwFlags))
2775 return FALSE;
2778 encrypt_block_impl(pPubKey->aiAlgid, PK_PUBLIC, &pPubKey->context, (BYTE*)(pAlgid+1),
2779 (BYTE*)(pAlgid+1), RSAENH_ENCRYPT);
2781 *pdwDataLen = dwDataLen;
2782 return TRUE;
2785 static BOOL crypt_export_public_key(CRYPTKEY *pCryptKey, BYTE *pbData,
2786 DWORD *pdwDataLen)
2788 BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2789 RSAPUBKEY *pRSAPubKey = (RSAPUBKEY*)(pBlobHeader+1);
2790 DWORD dwDataLen;
2792 if ((pCryptKey->aiAlgid != CALG_RSA_KEYX) && (pCryptKey->aiAlgid != CALG_RSA_SIGN)) {
2793 SetLastError(NTE_BAD_KEY);
2794 return FALSE;
2797 dwDataLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) + pCryptKey->dwKeyLen;
2798 if (pbData) {
2799 if (*pdwDataLen < dwDataLen) {
2800 SetLastError(ERROR_MORE_DATA);
2801 *pdwDataLen = dwDataLen;
2802 return FALSE;
2805 pBlobHeader->bType = PUBLICKEYBLOB;
2806 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2807 pBlobHeader->reserved = 0;
2808 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2810 pRSAPubKey->magic = RSAENH_MAGIC_RSA1;
2811 pRSAPubKey->bitlen = pCryptKey->dwKeyLen << 3;
2813 export_public_key_impl((BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2814 pCryptKey->dwKeyLen, &pRSAPubKey->pubexp);
2816 *pdwDataLen = dwDataLen;
2817 return TRUE;
2820 static BOOL crypt_export_private_key(CRYPTKEY *pCryptKey, BOOL force,
2821 BYTE *pbData, DWORD *pdwDataLen)
2823 BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2824 RSAPUBKEY *pRSAPubKey = (RSAPUBKEY*)(pBlobHeader+1);
2825 DWORD dwDataLen;
2827 if ((pCryptKey->aiAlgid != CALG_RSA_KEYX) && (pCryptKey->aiAlgid != CALG_RSA_SIGN)) {
2828 SetLastError(NTE_BAD_KEY);
2829 return FALSE;
2831 if (!force && !(pCryptKey->dwPermissions & CRYPT_EXPORT))
2833 SetLastError(NTE_BAD_KEY_STATE);
2834 return FALSE;
2837 dwDataLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) +
2838 2 * pCryptKey->dwKeyLen + 5 * ((pCryptKey->dwKeyLen + 1) >> 1);
2839 if (pbData) {
2840 if (*pdwDataLen < dwDataLen) {
2841 SetLastError(ERROR_MORE_DATA);
2842 *pdwDataLen = dwDataLen;
2843 return FALSE;
2846 pBlobHeader->bType = PRIVATEKEYBLOB;
2847 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2848 pBlobHeader->reserved = 0;
2849 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2851 pRSAPubKey->magic = RSAENH_MAGIC_RSA2;
2852 pRSAPubKey->bitlen = pCryptKey->dwKeyLen << 3;
2854 export_private_key_impl((BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2855 pCryptKey->dwKeyLen, &pRSAPubKey->pubexp);
2857 *pdwDataLen = dwDataLen;
2858 return TRUE;
2861 static BOOL crypt_export_plaintext_key(CRYPTKEY *pCryptKey, BYTE *pbData,
2862 DWORD *pdwDataLen)
2864 BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2865 DWORD *pKeyLen = (DWORD*)(pBlobHeader+1);
2866 BYTE *pbKey = (BYTE*)(pKeyLen+1);
2867 DWORD dwDataLen;
2869 dwDataLen = sizeof(BLOBHEADER) + sizeof(DWORD) + pCryptKey->dwKeyLen;
2870 if (pbData) {
2871 if (*pdwDataLen < dwDataLen) {
2872 SetLastError(ERROR_MORE_DATA);
2873 *pdwDataLen = dwDataLen;
2874 return FALSE;
2877 pBlobHeader->bType = PLAINTEXTKEYBLOB;
2878 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2879 pBlobHeader->reserved = 0;
2880 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2882 *pKeyLen = pCryptKey->dwKeyLen;
2883 memcpy(pbKey, pCryptKey->abKeyValue, pCryptKey->dwKeyLen);
2885 *pdwDataLen = dwDataLen;
2886 return TRUE;
2888 /******************************************************************************
2889 * crypt_export_key [Internal]
2891 * Export a key into a binary large object (BLOB). Called by CPExportKey and
2892 * by store_key_pair.
2894 * PARAMS
2895 * pCryptKey [I] Key to be exported.
2896 * hPubKey [I] Key used to encrypt sensitive BLOB data.
2897 * dwBlobType [I] SIMPLEBLOB, PUBLICKEYBLOB or PRIVATEKEYBLOB.
2898 * dwFlags [I] Currently none defined.
2899 * force [I] If TRUE, the key is written no matter what the key's
2900 * permissions are. Otherwise the key's permissions are
2901 * checked before exporting.
2902 * pbData [O] Pointer to a buffer where the BLOB will be written to.
2903 * pdwDataLen [I/O] I: Size of buffer at pbData, O: Size of BLOB
2905 * RETURNS
2906 * Success: TRUE.
2907 * Failure: FALSE.
2909 static BOOL crypt_export_key(CRYPTKEY *pCryptKey, HCRYPTKEY hPubKey,
2910 DWORD dwBlobType, DWORD dwFlags, BOOL force,
2911 BYTE *pbData, DWORD *pdwDataLen)
2913 CRYPTKEY *pPubKey;
2915 if (dwFlags & CRYPT_SSL2_FALLBACK) {
2916 if (pCryptKey->aiAlgid != CALG_SSL2_MASTER) {
2917 SetLastError(NTE_BAD_KEY);
2918 return FALSE;
2922 switch ((BYTE)dwBlobType)
2924 case SIMPLEBLOB:
2925 if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pPubKey)){
2926 SetLastError(NTE_BAD_PUBLIC_KEY); /* FIXME: error_code? */
2927 return FALSE;
2929 return crypt_export_simple(pCryptKey, pPubKey, dwFlags, pbData,
2930 pdwDataLen);
2932 case PUBLICKEYBLOB:
2933 if (is_valid_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY)) {
2934 SetLastError(NTE_BAD_KEY); /* FIXME: error code? */
2935 return FALSE;
2938 return crypt_export_public_key(pCryptKey, pbData, pdwDataLen);
2940 case PRIVATEKEYBLOB:
2941 return crypt_export_private_key(pCryptKey, force, pbData, pdwDataLen);
2943 case PLAINTEXTKEYBLOB:
2944 return crypt_export_plaintext_key(pCryptKey, pbData, pdwDataLen);
2946 default:
2947 SetLastError(NTE_BAD_TYPE); /* FIXME: error code? */
2948 return FALSE;
2952 /******************************************************************************
2953 * CPExportKey (RSAENH.@)
2955 * Export a key into a binary large object (BLOB).
2957 * PARAMS
2958 * hProv [I] Key container from which a key is to be exported.
2959 * hKey [I] Key to be exported.
2960 * hPubKey [I] Key used to encrypt sensitive BLOB data.
2961 * dwBlobType [I] SIMPLEBLOB, PUBLICKEYBLOB or PRIVATEKEYBLOB.
2962 * dwFlags [I] Currently none defined.
2963 * pbData [O] Pointer to a buffer where the BLOB will be written to.
2964 * pdwDataLen [I/O] I: Size of buffer at pbData, O: Size of BLOB
2966 * RETURNS
2967 * Success: TRUE.
2968 * Failure: FALSE.
2970 BOOL WINAPI RSAENH_CPExportKey(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTKEY hPubKey,
2971 DWORD dwBlobType, DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2973 CRYPTKEY *pCryptKey;
2975 TRACE("(hProv=%08lx, hKey=%08lx, hPubKey=%08lx, dwBlobType=%08x, dwFlags=%08x, pbData=%p,"
2976 "pdwDataLen=%p)\n", hProv, hKey, hPubKey, dwBlobType, dwFlags, pbData, pdwDataLen);
2978 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2980 SetLastError(NTE_BAD_UID);
2981 return FALSE;
2984 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2986 SetLastError(NTE_BAD_KEY);
2987 return FALSE;
2990 return crypt_export_key(pCryptKey, hPubKey, dwBlobType, dwFlags, FALSE,
2991 pbData, pdwDataLen);
2994 /******************************************************************************
2995 * release_and_install_key [Internal]
2997 * Release an existing key, if present, and replaces it with a new one.
2999 * PARAMS
3000 * hProv [I] Key container into which the key is to be imported.
3001 * src [I] Key which will replace *dest
3002 * dest [I] Points to key to be released and replaced with src
3003 * fStoreKey [I] If TRUE, the newly installed key is stored to the registry.
3005 static void release_and_install_key(HCRYPTPROV hProv, HCRYPTKEY src,
3006 HCRYPTKEY *dest, DWORD fStoreKey)
3008 RSAENH_CPDestroyKey(hProv, *dest);
3009 copy_handle(&handle_table, src, RSAENH_MAGIC_KEY, dest);
3010 if (fStoreKey)
3012 KEYCONTAINER *pKeyContainer;
3014 if ((pKeyContainer = get_key_container(hProv)))
3016 store_key_container_keys(pKeyContainer);
3017 store_key_container_permissions(pKeyContainer);
3022 /******************************************************************************
3023 * import_private_key [Internal]
3025 * Import a BLOB'ed private key into a key container.
3027 * PARAMS
3028 * hProv [I] Key container into which the private key is to be imported.
3029 * pbData [I] Pointer to a buffer which holds the private key BLOB.
3030 * dwDataLen [I] Length of data in buffer at pbData.
3031 * dwFlags [I] One of:
3032 * CRYPT_EXPORTABLE: the imported key is marked exportable
3033 * fStoreKey [I] If TRUE, the imported key is stored to the registry.
3034 * phKey [O] Handle to the imported key.
3037 * NOTES
3038 * Assumes the caller has already checked the BLOBHEADER at pbData to ensure
3039 * it's a PRIVATEKEYBLOB.
3041 * RETURNS
3042 * Success: TRUE.
3043 * Failure: FALSE.
3045 static BOOL import_private_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
3046 DWORD dwFlags, BOOL fStoreKey, HCRYPTKEY *phKey)
3048 KEYCONTAINER *pKeyContainer;
3049 CRYPTKEY *pCryptKey;
3050 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
3051 const RSAPUBKEY *pRSAPubKey = (const RSAPUBKEY*)(pBlobHeader+1);
3052 BOOL ret;
3054 if (dwFlags & CRYPT_IPSEC_HMAC_KEY)
3056 FIXME("unimplemented for CRYPT_IPSEC_HMAC_KEY\n");
3057 SetLastError(NTE_BAD_FLAGS);
3058 return FALSE;
3060 if (!(pKeyContainer = get_key_container(hProv)))
3061 return FALSE;
3063 if ((dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY)))
3065 ERR("datalen %d not long enough for a BLOBHEADER + RSAPUBKEY\n",
3066 dwDataLen);
3067 SetLastError(NTE_BAD_DATA);
3068 return FALSE;
3070 if (pRSAPubKey->magic != RSAENH_MAGIC_RSA2)
3072 ERR("unexpected magic %08x\n", pRSAPubKey->magic);
3073 SetLastError(NTE_BAD_DATA);
3074 return FALSE;
3076 if ((dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) +
3077 (pRSAPubKey->bitlen >> 3) + (5 * ((pRSAPubKey->bitlen+8)>>4))))
3079 DWORD expectedLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) +
3080 (pRSAPubKey->bitlen >> 3) + (5 * ((pRSAPubKey->bitlen+8)>>4));
3082 ERR("blob too short for pub key: expect %d, got %d\n",
3083 expectedLen, dwDataLen);
3084 SetLastError(NTE_BAD_DATA);
3085 return FALSE;
3088 *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, MAKELONG(0,pRSAPubKey->bitlen), &pCryptKey);
3089 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
3090 setup_key(pCryptKey);
3091 ret = import_private_key_impl((const BYTE*)(pRSAPubKey+1), &pCryptKey->context,
3092 pRSAPubKey->bitlen/8, dwDataLen, pRSAPubKey->pubexp);
3093 if (ret) {
3094 if (dwFlags & CRYPT_EXPORTABLE)
3095 pCryptKey->dwPermissions |= CRYPT_EXPORT;
3096 switch (pBlobHeader->aiKeyAlg)
3098 case AT_SIGNATURE:
3099 case CALG_RSA_SIGN:
3100 TRACE("installing signing key\n");
3101 release_and_install_key(hProv, *phKey, &pKeyContainer->hSignatureKeyPair,
3102 fStoreKey);
3103 break;
3104 case AT_KEYEXCHANGE:
3105 case CALG_RSA_KEYX:
3106 TRACE("installing key exchange key\n");
3107 release_and_install_key(hProv, *phKey, &pKeyContainer->hKeyExchangeKeyPair,
3108 fStoreKey);
3109 break;
3112 return ret;
3115 /******************************************************************************
3116 * import_public_key [Internal]
3118 * Import a BLOB'ed public key.
3120 * PARAMS
3121 * hProv [I] A CSP.
3122 * pbData [I] Pointer to a buffer which holds the public key BLOB.
3123 * dwDataLen [I] Length of data in buffer at pbData.
3124 * dwFlags [I] One of:
3125 * CRYPT_EXPORTABLE: the imported key is marked exportable
3126 * phKey [O] Handle to the imported key.
3129 * NOTES
3130 * Assumes the caller has already checked the BLOBHEADER at pbData to ensure
3131 * it's a PUBLICKEYBLOB.
3133 * RETURNS
3134 * Success: TRUE.
3135 * Failure: FALSE.
3137 static BOOL import_public_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
3138 DWORD dwFlags, HCRYPTKEY *phKey)
3140 CRYPTKEY *pCryptKey;
3141 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
3142 const RSAPUBKEY *pRSAPubKey = (const RSAPUBKEY*)(pBlobHeader+1);
3143 ALG_ID algID;
3144 BOOL ret;
3146 if (dwFlags & CRYPT_IPSEC_HMAC_KEY)
3148 FIXME("unimplemented for CRYPT_IPSEC_HMAC_KEY\n");
3149 SetLastError(NTE_BAD_FLAGS);
3150 return FALSE;
3153 if ((dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY)) ||
3154 (pRSAPubKey->magic != RSAENH_MAGIC_RSA1) ||
3155 (dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) + (pRSAPubKey->bitlen >> 3)))
3157 SetLastError(NTE_BAD_DATA);
3158 return FALSE;
3161 /* Since this is a public key blob, only the public key is
3162 * available, so only signature verification is possible.
3164 algID = pBlobHeader->aiKeyAlg;
3165 *phKey = new_key(hProv, algID, MAKELONG(0,pRSAPubKey->bitlen), &pCryptKey);
3166 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
3167 setup_key(pCryptKey);
3168 ret = import_public_key_impl((const BYTE*)(pRSAPubKey+1), &pCryptKey->context,
3169 pRSAPubKey->bitlen >> 3, pRSAPubKey->pubexp);
3170 if (ret) {
3171 if (dwFlags & CRYPT_EXPORTABLE)
3172 pCryptKey->dwPermissions |= CRYPT_EXPORT;
3174 return ret;
3177 /******************************************************************************
3178 * import_symmetric_key [Internal]
3180 * Import a BLOB'ed symmetric key into a key container.
3182 * PARAMS
3183 * hProv [I] Key container into which the symmetric key is to be imported.
3184 * pbData [I] Pointer to a buffer which holds the symmetric key BLOB.
3185 * dwDataLen [I] Length of data in buffer at pbData.
3186 * hPubKey [I] Key used to decrypt sensitive BLOB data.
3187 * dwFlags [I] One of:
3188 * CRYPT_EXPORTABLE: the imported key is marked exportable
3189 * phKey [O] Handle to the imported key.
3192 * NOTES
3193 * Assumes the caller has already checked the BLOBHEADER at pbData to ensure
3194 * it's a SIMPLEBLOB.
3196 * RETURNS
3197 * Success: TRUE.
3198 * Failure: FALSE.
3200 static BOOL import_symmetric_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
3201 HCRYPTKEY hPubKey, DWORD dwFlags, HCRYPTKEY *phKey)
3203 CRYPTKEY *pCryptKey, *pPubKey;
3204 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
3205 const ALG_ID *pAlgid = (const ALG_ID*)(pBlobHeader+1);
3206 const BYTE *pbKeyStream = (const BYTE*)(pAlgid + 1);
3207 BYTE *pbDecrypted;
3208 DWORD dwKeyLen;
3210 if (dwFlags & CRYPT_IPSEC_HMAC_KEY)
3212 FIXME("unimplemented for CRYPT_IPSEC_HMAC_KEY\n");
3213 SetLastError(NTE_BAD_FLAGS);
3214 return FALSE;
3216 if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pPubKey) ||
3217 pPubKey->aiAlgid != CALG_RSA_KEYX)
3219 SetLastError(NTE_BAD_PUBLIC_KEY); /* FIXME: error code? */
3220 return FALSE;
3223 if (dwDataLen < sizeof(BLOBHEADER)+sizeof(ALG_ID)+pPubKey->dwBlockLen)
3225 SetLastError(NTE_BAD_DATA); /* FIXME: error code */
3226 return FALSE;
3229 pbDecrypted = HeapAlloc(GetProcessHeap(), 0, pPubKey->dwBlockLen);
3230 if (!pbDecrypted) return FALSE;
3231 encrypt_block_impl(pPubKey->aiAlgid, PK_PRIVATE, &pPubKey->context, pbKeyStream, pbDecrypted,
3232 RSAENH_DECRYPT);
3234 dwKeyLen = RSAENH_MAX_KEY_SIZE;
3235 if (!unpad_data(hProv, pbDecrypted, pPubKey->dwBlockLen, pbDecrypted, &dwKeyLen, dwFlags)) {
3236 HeapFree(GetProcessHeap(), 0, pbDecrypted);
3237 return FALSE;
3240 *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, dwKeyLen<<19, &pCryptKey);
3241 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
3243 HeapFree(GetProcessHeap(), 0, pbDecrypted);
3244 return FALSE;
3246 memcpy(pCryptKey->abKeyValue, pbDecrypted, dwKeyLen);
3247 HeapFree(GetProcessHeap(), 0, pbDecrypted);
3248 setup_key(pCryptKey);
3249 if (dwFlags & CRYPT_EXPORTABLE)
3250 pCryptKey->dwPermissions |= CRYPT_EXPORT;
3251 return TRUE;
3254 /******************************************************************************
3255 * import_plaintext_key [Internal]
3257 * Import a plaintext key into a key container.
3259 * PARAMS
3260 * hProv [I] Key container into which the symmetric key is to be imported.
3261 * pbData [I] Pointer to a buffer which holds the plaintext key BLOB.
3262 * dwDataLen [I] Length of data in buffer at pbData.
3263 * dwFlags [I] One of:
3264 * CRYPT_EXPORTABLE: the imported key is marked exportable
3265 * phKey [O] Handle to the imported key.
3268 * NOTES
3269 * Assumes the caller has already checked the BLOBHEADER at pbData to ensure
3270 * it's a PLAINTEXTKEYBLOB.
3272 * RETURNS
3273 * Success: TRUE.
3274 * Failure: FALSE.
3276 static BOOL import_plaintext_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
3277 DWORD dwFlags, HCRYPTKEY *phKey)
3279 CRYPTKEY *pCryptKey;
3280 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
3281 const DWORD *pKeyLen = (const DWORD *)(pBlobHeader + 1);
3282 const BYTE *pbKeyStream = (const BYTE*)(pKeyLen + 1);
3284 if (dwDataLen < sizeof(BLOBHEADER)+sizeof(DWORD)+*pKeyLen)
3286 SetLastError(NTE_BAD_DATA); /* FIXME: error code */
3287 return FALSE;
3290 if (dwFlags & CRYPT_IPSEC_HMAC_KEY)
3292 *phKey = new_key(hProv, CALG_HMAC, 0, &pCryptKey);
3293 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
3294 return FALSE;
3295 if (*pKeyLen <= RSAENH_MIN(sizeof(pCryptKey->abKeyValue), RSAENH_HMAC_BLOCK_LEN))
3297 memcpy(pCryptKey->abKeyValue, pbKeyStream, *pKeyLen);
3298 pCryptKey->dwKeyLen = *pKeyLen;
3300 else
3302 CRYPT_DATA_BLOB blobHmacKey = { *pKeyLen, (BYTE *)pbKeyStream };
3304 /* In order to initialize an HMAC key, the key material is hashed,
3305 * and the output of the hash function is used as the key material.
3306 * Unfortunately, the way the Crypto API is designed, we don't know
3307 * the hash algorithm yet, so we have to copy the entire key
3308 * material.
3310 if (!copy_data_blob(&pCryptKey->blobHmacKey, &blobHmacKey))
3312 release_handle(&handle_table, *phKey, RSAENH_MAGIC_KEY);
3313 *phKey = (HCRYPTKEY)INVALID_HANDLE_VALUE;
3314 return FALSE;
3317 setup_key(pCryptKey);
3318 if (dwFlags & CRYPT_EXPORTABLE)
3319 pCryptKey->dwPermissions |= CRYPT_EXPORT;
3321 else
3323 *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, *pKeyLen<<19, &pCryptKey);
3324 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
3325 return FALSE;
3326 memcpy(pCryptKey->abKeyValue, pbKeyStream, *pKeyLen);
3327 setup_key(pCryptKey);
3328 if (dwFlags & CRYPT_EXPORTABLE)
3329 pCryptKey->dwPermissions |= CRYPT_EXPORT;
3331 return TRUE;
3334 /******************************************************************************
3335 * import_key [Internal]
3337 * Import a BLOB'ed key into a key container, optionally storing the key's
3338 * value to the registry.
3340 * PARAMS
3341 * hProv [I] Key container into which the key is to be imported.
3342 * pbData [I] Pointer to a buffer which holds the BLOB.
3343 * dwDataLen [I] Length of data in buffer at pbData.
3344 * hPubKey [I] Key used to decrypt sensitive BLOB data.
3345 * dwFlags [I] One of:
3346 * CRYPT_EXPORTABLE: the imported key is marked exportable
3347 * fStoreKey [I] If TRUE, the imported key is stored to the registry.
3348 * phKey [O] Handle to the imported key.
3350 * RETURNS
3351 * Success: TRUE.
3352 * Failure: FALSE.
3354 static BOOL import_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen, HCRYPTKEY hPubKey,
3355 DWORD dwFlags, BOOL fStoreKey, HCRYPTKEY *phKey)
3357 KEYCONTAINER *pKeyContainer;
3358 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
3360 if (!(pKeyContainer = get_key_container(hProv)))
3361 return FALSE;
3363 if (dwDataLen < sizeof(BLOBHEADER) ||
3364 pBlobHeader->bVersion != CUR_BLOB_VERSION ||
3365 pBlobHeader->reserved != 0)
3367 TRACE("bVersion = %d, reserved = %d\n", pBlobHeader->bVersion,
3368 pBlobHeader->reserved);
3369 SetLastError(NTE_BAD_DATA);
3370 return FALSE;
3373 /* If this is a verify-only context, the key is not persisted regardless of
3374 * fStoreKey's original value.
3376 fStoreKey = fStoreKey && !(dwFlags & CRYPT_VERIFYCONTEXT);
3377 TRACE("blob type: %x\n", pBlobHeader->bType);
3378 switch (pBlobHeader->bType)
3380 case PRIVATEKEYBLOB:
3381 return import_private_key(hProv, pbData, dwDataLen, dwFlags,
3382 fStoreKey, phKey);
3384 case PUBLICKEYBLOB:
3385 return import_public_key(hProv, pbData, dwDataLen, dwFlags,
3386 phKey);
3388 case SIMPLEBLOB:
3389 return import_symmetric_key(hProv, pbData, dwDataLen, hPubKey,
3390 dwFlags, phKey);
3392 case PLAINTEXTKEYBLOB:
3393 return import_plaintext_key(hProv, pbData, dwDataLen, dwFlags,
3394 phKey);
3396 default:
3397 SetLastError(NTE_BAD_TYPE); /* FIXME: error code? */
3398 return FALSE;
3402 /******************************************************************************
3403 * CPImportKey (RSAENH.@)
3405 * Import a BLOB'ed key into a key container.
3407 * PARAMS
3408 * hProv [I] Key container into which the key is to be imported.
3409 * pbData [I] Pointer to a buffer which holds the BLOB.
3410 * dwDataLen [I] Length of data in buffer at pbData.
3411 * hPubKey [I] Key used to decrypt sensitive BLOB data.
3412 * dwFlags [I] One of:
3413 * CRYPT_EXPORTABLE: the imported key is marked exportable
3414 * phKey [O] Handle to the imported key.
3416 * RETURNS
3417 * Success: TRUE.
3418 * Failure: FALSE.
3420 BOOL WINAPI RSAENH_CPImportKey(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
3421 HCRYPTKEY hPubKey, DWORD dwFlags, HCRYPTKEY *phKey)
3423 TRACE("(hProv=%08lx, pbData=%p, dwDataLen=%d, hPubKey=%08lx, dwFlags=%08x, phKey=%p)\n",
3424 hProv, pbData, dwDataLen, hPubKey, dwFlags, phKey);
3426 return import_key(hProv, pbData, dwDataLen, hPubKey, dwFlags, TRUE, phKey);
3429 /******************************************************************************
3430 * CPGenKey (RSAENH.@)
3432 * Generate a key in the key container
3434 * PARAMS
3435 * hProv [I] Key container for which a key is to be generated.
3436 * Algid [I] Crypto algorithm identifier for the key to be generated.
3437 * dwFlags [I] Upper 16 bits: Binary length of key. Lower 16 bits: Flags. See Notes
3438 * phKey [O] Handle to the generated key.
3440 * RETURNS
3441 * Success: TRUE.
3442 * Failure: FALSE.
3444 * FIXME
3445 * Flags currently not considered.
3447 * NOTES
3448 * Private key-exchange- and signature-keys can be generated with Algid AT_KEYEXCHANGE
3449 * and AT_SIGNATURE values.
3451 BOOL WINAPI RSAENH_CPGenKey(HCRYPTPROV hProv, ALG_ID Algid, DWORD dwFlags, HCRYPTKEY *phKey)
3453 KEYCONTAINER *pKeyContainer;
3454 CRYPTKEY *pCryptKey;
3456 TRACE("(hProv=%08lx, aiAlgid=%d, dwFlags=%08x, phKey=%p)\n", hProv, Algid, dwFlags, phKey);
3458 if (!(pKeyContainer = get_key_container(hProv)))
3460 /* MSDN: hProv not containing valid context handle */
3461 return FALSE;
3464 switch (Algid)
3466 case AT_SIGNATURE:
3467 case CALG_RSA_SIGN:
3468 *phKey = new_key(hProv, CALG_RSA_SIGN, dwFlags, &pCryptKey);
3469 if (pCryptKey) {
3470 new_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen);
3471 setup_key(pCryptKey);
3472 release_and_install_key(hProv, *phKey,
3473 &pKeyContainer->hSignatureKeyPair,
3474 FALSE);
3476 break;
3478 case AT_KEYEXCHANGE:
3479 case CALG_RSA_KEYX:
3480 *phKey = new_key(hProv, CALG_RSA_KEYX, dwFlags, &pCryptKey);
3481 if (pCryptKey) {
3482 new_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen);
3483 setup_key(pCryptKey);
3484 release_and_install_key(hProv, *phKey,
3485 &pKeyContainer->hKeyExchangeKeyPair,
3486 FALSE);
3488 break;
3490 case CALG_RC2:
3491 case CALG_RC4:
3492 case CALG_DES:
3493 case CALG_3DES_112:
3494 case CALG_3DES:
3495 case CALG_AES_128:
3496 case CALG_AES_192:
3497 case CALG_AES_256:
3498 case CALG_PCT1_MASTER:
3499 case CALG_SSL2_MASTER:
3500 case CALG_SSL3_MASTER:
3501 case CALG_TLS1_MASTER:
3502 *phKey = new_key(hProv, Algid, dwFlags, &pCryptKey);
3503 if (pCryptKey) {
3504 gen_rand_impl(pCryptKey->abKeyValue, RSAENH_MAX_KEY_SIZE);
3505 switch (Algid) {
3506 case CALG_SSL3_MASTER:
3507 pCryptKey->abKeyValue[0] = RSAENH_SSL3_VERSION_MAJOR;
3508 pCryptKey->abKeyValue[1] = RSAENH_SSL3_VERSION_MINOR;
3509 break;
3511 case CALG_TLS1_MASTER:
3512 pCryptKey->abKeyValue[0] = RSAENH_TLS1_VERSION_MAJOR;
3513 pCryptKey->abKeyValue[1] = RSAENH_TLS1_VERSION_MINOR;
3514 break;
3516 setup_key(pCryptKey);
3518 break;
3520 default:
3521 /* MSDN: Algorithm not supported specified by Algid */
3522 SetLastError(NTE_BAD_ALGID);
3523 return FALSE;
3526 return *phKey != (HCRYPTKEY)INVALID_HANDLE_VALUE;
3529 /******************************************************************************
3530 * CPGenRandom (RSAENH.@)
3532 * Generate a random byte stream.
3534 * PARAMS
3535 * hProv [I] Key container that is used to generate random bytes.
3536 * dwLen [I] Specifies the number of requested random data bytes.
3537 * pbBuffer [O] Random bytes will be stored here.
3539 * RETURNS
3540 * Success: TRUE
3541 * Failure: FALSE
3543 BOOL WINAPI RSAENH_CPGenRandom(HCRYPTPROV hProv, DWORD dwLen, BYTE *pbBuffer)
3545 TRACE("(hProv=%08lx, dwLen=%d, pbBuffer=%p)\n", hProv, dwLen, pbBuffer);
3547 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3549 /* MSDN: hProv not containing valid context handle */
3550 SetLastError(NTE_BAD_UID);
3551 return FALSE;
3554 return gen_rand_impl(pbBuffer, dwLen);
3557 /******************************************************************************
3558 * CPGetHashParam (RSAENH.@)
3560 * Query parameters of an hash object.
3562 * PARAMS
3563 * hProv [I] The kea container, which the hash belongs to.
3564 * hHash [I] The hash object that is to be queried.
3565 * dwParam [I] Specifies the parameter that is to be queried.
3566 * pbData [I] Pointer to the buffer where the parameter value will be stored.
3567 * pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
3568 * dwFlags [I] None currently defined.
3570 * RETURNS
3571 * Success: TRUE
3572 * Failure: FALSE
3574 * NOTES
3575 * Valid dwParams are: HP_ALGID, HP_HASHSIZE, HP_HASHVALUE. The hash will be
3576 * finalized if HP_HASHVALUE is queried.
3578 BOOL WINAPI RSAENH_CPGetHashParam(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwParam, BYTE *pbData,
3579 DWORD *pdwDataLen, DWORD dwFlags)
3581 CRYPTHASH *pCryptHash;
3583 TRACE("(hProv=%08lx, hHash=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p, dwFlags=%08x)\n",
3584 hProv, hHash, dwParam, pbData, pdwDataLen, dwFlags);
3586 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3588 SetLastError(NTE_BAD_UID);
3589 return FALSE;
3592 if (dwFlags)
3594 SetLastError(NTE_BAD_FLAGS);
3595 return FALSE;
3598 if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH,
3599 (OBJECTHDR**)&pCryptHash))
3601 SetLastError(NTE_BAD_HASH);
3602 return FALSE;
3605 if (!pdwDataLen)
3607 SetLastError(ERROR_INVALID_PARAMETER);
3608 return FALSE;
3611 switch (dwParam)
3613 case HP_ALGID:
3614 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptHash->aiAlgid,
3615 sizeof(ALG_ID));
3617 case HP_HASHSIZE:
3618 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptHash->dwHashSize,
3619 sizeof(DWORD));
3621 case HP_HASHVAL:
3622 if (pCryptHash->aiAlgid == CALG_TLS1PRF) {
3623 return tls1_prf(hProv, pCryptHash->hKey, &pCryptHash->tpPRFParams.blobLabel,
3624 &pCryptHash->tpPRFParams.blobSeed, pbData, *pdwDataLen);
3627 if (pCryptHash->dwState != RSAENH_HASHSTATE_FINISHED)
3629 finalize_hash(pCryptHash);
3630 pCryptHash->dwState = RSAENH_HASHSTATE_FINISHED;
3633 if (!pbData)
3635 *pdwDataLen = pCryptHash->dwHashSize;
3636 return TRUE;
3639 return copy_param(pbData, pdwDataLen, pCryptHash->abHashValue,
3640 pCryptHash->dwHashSize);
3642 default:
3643 SetLastError(NTE_BAD_TYPE);
3644 return FALSE;
3648 /******************************************************************************
3649 * CPSetKeyParam (RSAENH.@)
3651 * Set a parameter of a key object
3653 * PARAMS
3654 * hProv [I] The key container to which the key belongs.
3655 * hKey [I] The key for which a parameter is to be set.
3656 * dwParam [I] Parameter type. See Notes.
3657 * pbData [I] Pointer to the parameter value.
3658 * dwFlags [I] Currently none defined.
3660 * RETURNS
3661 * Success: TRUE.
3662 * Failure: FALSE.
3664 * NOTES:
3665 * Defined dwParam types are:
3666 * - KP_MODE: Values MODE_CBC, MODE_ECB, MODE_CFB.
3667 * - KP_MODE_BITS: Shift width for cipher feedback mode. (Currently ignored by MS CSP's)
3668 * - KP_PERMISSIONS: Or'ed combination of CRYPT_ENCRYPT, CRYPT_DECRYPT,
3669 * CRYPT_EXPORT, CRYPT_READ, CRYPT_WRITE, CRYPT_MAC
3670 * - KP_IV: Initialization vector
3672 BOOL WINAPI RSAENH_CPSetKeyParam(HCRYPTPROV hProv, HCRYPTKEY hKey, DWORD dwParam, BYTE *pbData,
3673 DWORD dwFlags)
3675 CRYPTKEY *pCryptKey;
3677 TRACE("(hProv=%08lx, hKey=%08lx, dwParam=%08x, pbData=%p, dwFlags=%08x)\n", hProv, hKey,
3678 dwParam, pbData, dwFlags);
3680 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3682 SetLastError(NTE_BAD_UID);
3683 return FALSE;
3686 if (dwFlags) {
3687 SetLastError(NTE_BAD_FLAGS);
3688 return FALSE;
3691 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
3693 SetLastError(NTE_BAD_KEY);
3694 return FALSE;
3697 switch (dwParam) {
3698 case KP_PADDING:
3699 /* The MS providers only support PKCS5_PADDING */
3700 if (*(DWORD *)pbData != PKCS5_PADDING) {
3701 SetLastError(NTE_BAD_DATA);
3702 return FALSE;
3704 return TRUE;
3706 case KP_MODE:
3707 pCryptKey->dwMode = *(DWORD*)pbData;
3708 return TRUE;
3710 case KP_MODE_BITS:
3711 pCryptKey->dwModeBits = *(DWORD*)pbData;
3712 return TRUE;
3714 case KP_PERMISSIONS:
3716 DWORD perms = *(DWORD *)pbData;
3718 if ((perms & CRYPT_EXPORT) &&
3719 !(pCryptKey->dwPermissions & CRYPT_EXPORT))
3721 SetLastError(NTE_BAD_DATA);
3722 return FALSE;
3724 else if (!(perms & CRYPT_EXPORT) &&
3725 (pCryptKey->dwPermissions & CRYPT_EXPORT))
3727 /* Clearing the export permission appears to be ignored,
3728 * see tests.
3730 perms |= CRYPT_EXPORT;
3732 pCryptKey->dwPermissions = perms;
3733 return TRUE;
3736 case KP_IV:
3737 memcpy(pCryptKey->abInitVector, pbData, pCryptKey->dwBlockLen);
3738 setup_key(pCryptKey);
3739 return TRUE;
3741 case KP_SALT:
3742 switch (pCryptKey->aiAlgid) {
3743 case CALG_RC2:
3744 case CALG_RC4:
3746 KEYCONTAINER *pKeyContainer = get_key_container(pCryptKey->hProv);
3747 if (!pbData)
3749 SetLastError(ERROR_INVALID_PARAMETER);
3750 return FALSE;
3752 /* MSDN: the base provider always sets eleven bytes of
3753 * salt value.
3755 memcpy(pCryptKey->abKeyValue + pCryptKey->dwKeyLen,
3756 pbData, 11);
3757 pCryptKey->dwSaltLen = 11;
3758 setup_key(pCryptKey);
3759 /* After setting the salt value if the provider is not base or
3760 * strong the salt length will be reset. */
3761 if (pKeyContainer->dwPersonality != RSAENH_PERSONALITY_BASE &&
3762 pKeyContainer->dwPersonality != RSAENH_PERSONALITY_STRONG)
3763 pCryptKey->dwSaltLen = 0;
3764 break;
3766 default:
3767 SetLastError(NTE_BAD_KEY);
3768 return FALSE;
3770 return TRUE;
3772 case KP_SALT_EX:
3774 CRYPT_INTEGER_BLOB *blob = (CRYPT_INTEGER_BLOB *)pbData;
3776 /* salt length can't be greater than 184 bits = 24 bytes */
3777 if (blob->cbData > 24)
3779 SetLastError(NTE_BAD_DATA);
3780 return FALSE;
3782 memcpy(pCryptKey->abKeyValue + pCryptKey->dwKeyLen, blob->pbData,
3783 blob->cbData);
3784 pCryptKey->dwSaltLen = blob->cbData;
3785 setup_key(pCryptKey);
3786 return TRUE;
3789 case KP_EFFECTIVE_KEYLEN:
3790 switch (pCryptKey->aiAlgid) {
3791 case CALG_RC2:
3793 DWORD keylen, deflen;
3794 BOOL ret = TRUE;
3795 KEYCONTAINER *pKeyContainer = get_key_container(pCryptKey->hProv);
3797 if (!pbData)
3799 SetLastError(ERROR_INVALID_PARAMETER);
3800 return FALSE;
3802 keylen = *(DWORD *)pbData;
3803 if (!keylen || keylen > 1024)
3805 SetLastError(NTE_BAD_DATA);
3806 return FALSE;
3810 * The Base provider will force the key length to default
3811 * and set an error state if a key length different from
3812 * the default is tried.
3814 deflen = aProvEnumAlgsEx[pKeyContainer->dwPersonality]->dwDefaultLen;
3815 if (pKeyContainer->dwPersonality == RSAENH_PERSONALITY_BASE
3816 && keylen != deflen)
3818 keylen = deflen;
3819 SetLastError(NTE_BAD_DATA);
3820 ret = FALSE;
3822 pCryptKey->dwEffectiveKeyLen = keylen;
3823 setup_key(pCryptKey);
3824 return ret;
3826 default:
3827 SetLastError(NTE_BAD_TYPE);
3828 return FALSE;
3830 return TRUE;
3832 case KP_SCHANNEL_ALG:
3833 switch (((PSCHANNEL_ALG)pbData)->dwUse) {
3834 case SCHANNEL_ENC_KEY:
3835 memcpy(&pCryptKey->siSChannelInfo.saEncAlg, pbData, sizeof(SCHANNEL_ALG));
3836 break;
3838 case SCHANNEL_MAC_KEY:
3839 memcpy(&pCryptKey->siSChannelInfo.saMACAlg, pbData, sizeof(SCHANNEL_ALG));
3840 break;
3842 default:
3843 SetLastError(NTE_FAIL); /* FIXME: error code */
3844 return FALSE;
3846 return TRUE;
3848 case KP_CLIENT_RANDOM:
3849 return copy_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom, (PCRYPT_DATA_BLOB)pbData);
3851 case KP_SERVER_RANDOM:
3852 return copy_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom, (PCRYPT_DATA_BLOB)pbData);
3854 default:
3855 SetLastError(NTE_BAD_TYPE);
3856 return FALSE;
3860 /******************************************************************************
3861 * CPGetKeyParam (RSAENH.@)
3863 * Query a key parameter.
3865 * PARAMS
3866 * hProv [I] The key container, which the key belongs to.
3867 * hHash [I] The key object that is to be queried.
3868 * dwParam [I] Specifies the parameter that is to be queried.
3869 * pbData [I] Pointer to the buffer where the parameter value will be stored.
3870 * pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
3871 * dwFlags [I] None currently defined.
3873 * RETURNS
3874 * Success: TRUE
3875 * Failure: FALSE
3877 * NOTES
3878 * Defined dwParam types are:
3879 * - KP_MODE: Values MODE_CBC, MODE_ECB, MODE_CFB.
3880 * - KP_MODE_BITS: Shift width for cipher feedback mode.
3881 * (Currently ignored by MS CSP's - always eight)
3882 * - KP_PERMISSIONS: Or'ed combination of CRYPT_ENCRYPT, CRYPT_DECRYPT,
3883 * CRYPT_EXPORT, CRYPT_READ, CRYPT_WRITE, CRYPT_MAC
3884 * - KP_IV: Initialization vector.
3885 * - KP_KEYLEN: Bitwidth of the key.
3886 * - KP_BLOCKLEN: Size of a block cipher block.
3887 * - KP_SALT: Salt value.
3889 BOOL WINAPI RSAENH_CPGetKeyParam(HCRYPTPROV hProv, HCRYPTKEY hKey, DWORD dwParam, BYTE *pbData,
3890 DWORD *pdwDataLen, DWORD dwFlags)
3892 CRYPTKEY *pCryptKey;
3893 DWORD dwValue;
3895 TRACE("(hProv=%08lx, hKey=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p dwFlags=%08x)\n",
3896 hProv, hKey, dwParam, pbData, pdwDataLen, dwFlags);
3898 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3900 SetLastError(NTE_BAD_UID);
3901 return FALSE;
3904 if (dwFlags) {
3905 SetLastError(NTE_BAD_FLAGS);
3906 return FALSE;
3909 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
3911 SetLastError(NTE_BAD_KEY);
3912 return FALSE;
3915 switch (dwParam)
3917 case KP_IV:
3918 return copy_param(pbData, pdwDataLen, pCryptKey->abInitVector,
3919 pCryptKey->dwBlockLen);
3921 case KP_SALT:
3922 switch (pCryptKey->aiAlgid) {
3923 case CALG_RC2:
3924 case CALG_RC4:
3925 return copy_param(pbData, pdwDataLen,
3926 &pCryptKey->abKeyValue[pCryptKey->dwKeyLen],
3927 pCryptKey->dwSaltLen);
3928 default:
3929 SetLastError(NTE_BAD_KEY);
3930 return FALSE;
3933 case KP_PADDING:
3934 dwValue = PKCS5_PADDING;
3935 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwValue, sizeof(DWORD));
3937 case KP_KEYLEN:
3938 dwValue = pCryptKey->dwKeyLen << 3;
3939 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwValue, sizeof(DWORD));
3941 case KP_EFFECTIVE_KEYLEN:
3942 if (pCryptKey->dwEffectiveKeyLen)
3943 dwValue = pCryptKey->dwEffectiveKeyLen;
3944 else
3945 dwValue = pCryptKey->dwKeyLen << 3;
3946 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwValue, sizeof(DWORD));
3948 case KP_BLOCKLEN:
3949 dwValue = pCryptKey->dwBlockLen << 3;
3950 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwValue, sizeof(DWORD));
3952 case KP_MODE:
3953 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptKey->dwMode, sizeof(DWORD));
3955 case KP_MODE_BITS:
3956 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptKey->dwModeBits,
3957 sizeof(DWORD));
3959 case KP_PERMISSIONS:
3960 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptKey->dwPermissions,
3961 sizeof(DWORD));
3963 case KP_ALGID:
3964 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptKey->aiAlgid, sizeof(DWORD));
3966 default:
3967 SetLastError(NTE_BAD_TYPE);
3968 return FALSE;
3972 /******************************************************************************
3973 * CPGetProvParam (RSAENH.@)
3975 * Query a CSP parameter.
3977 * PARAMS
3978 * hProv [I] The key container that is to be queried.
3979 * dwParam [I] Specifies the parameter that is to be queried.
3980 * pbData [I] Pointer to the buffer where the parameter value will be stored.
3981 * pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
3982 * dwFlags [I] CRYPT_FIRST: Start enumeration (for PP_ENUMALGS{_EX}).
3984 * RETURNS
3985 * Success: TRUE
3986 * Failure: FALSE
3987 * NOTES:
3988 * Defined dwParam types:
3989 * - PP_CONTAINER: Name of the key container.
3990 * - PP_NAME: Name of the cryptographic service provider.
3991 * - PP_SIG_KEYSIZE_INC: RSA signature keywidth granularity in bits.
3992 * - PP_KEYX_KEYSIZE_INC: RSA key-exchange keywidth granularity in bits.
3993 * - PP_ENUMALGS{_EX}: Query provider capabilities.
3994 * - PP_KEYSET_SEC_DESCR: Retrieve security descriptor on container.
3996 BOOL WINAPI RSAENH_CPGetProvParam(HCRYPTPROV hProv, DWORD dwParam, BYTE *pbData,
3997 DWORD *pdwDataLen, DWORD dwFlags)
3999 KEYCONTAINER *pKeyContainer;
4000 PROV_ENUMALGS provEnumalgs;
4001 DWORD dwTemp;
4002 HKEY hKey;
4004 /* This is for dwParam PP_CRYPT_COUNT_KEY_USE.
4005 * IE6 SP1 asks for it in the 'About' dialog.
4006 * Returning this BLOB seems to satisfy IE. The marked 0x00 seem
4007 * to be 'don't care's. If you know anything more specific about
4008 * this provider parameter, please contact the Wine developers */
4009 static const BYTE abWTF[96] = {
4010 0xb0, 0x25, 0x63, 0x86, 0x9c, 0xab, 0xb6, 0x37,
4011 0xe8, 0x82, /**/0x00,/**/ 0x72, 0x06, 0xb2, /**/0x00,/**/ 0x3b,
4012 0x60, 0x35, /**/0x00,/**/ 0x3b, 0x88, 0xce, /**/0x00,/**/ 0x82,
4013 0xbc, 0x7a, /**/0x00,/**/ 0xb7, 0x4f, 0x7e, /**/0x00,/**/ 0xde,
4014 0x92, 0xf1, /**/0x00,/**/ 0x83, 0xea, 0x5e, /**/0x00,/**/ 0xc8,
4015 0x12, 0x1e, 0xd4, 0x06, 0xf7, 0x66, /**/0x00,/**/ 0x01,
4016 0x29, 0xa4, /**/0x00,/**/ 0xf8, 0x24, 0x0c, /**/0x00,/**/ 0x33,
4017 0x06, 0x80, /**/0x00,/**/ 0x02, 0x46, 0x0b, /**/0x00,/**/ 0x6d,
4018 0x5b, 0xca, /**/0x00,/**/ 0x9a, 0x10, 0xf0, /**/0x00,/**/ 0x05,
4019 0x19, 0xd0, /**/0x00,/**/ 0x2c, 0xf6, 0x27, /**/0x00,/**/ 0xaa,
4020 0x7c, 0x6f, /**/0x00,/**/ 0xb9, 0xd8, 0x72, /**/0x00,/**/ 0x03,
4021 0xf3, 0x81, /**/0x00,/**/ 0xfa, 0xe8, 0x26, /**/0x00,/**/ 0xca
4024 TRACE("(hProv=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p, dwFlags=%08x)\n",
4025 hProv, dwParam, pbData, pdwDataLen, dwFlags);
4027 if (!pdwDataLen) {
4028 SetLastError(ERROR_INVALID_PARAMETER);
4029 return FALSE;
4032 if (!(pKeyContainer = get_key_container(hProv)))
4034 /* MSDN: hProv not containing valid context handle */
4035 return FALSE;
4038 switch (dwParam)
4040 case PP_CONTAINER:
4041 case PP_UNIQUE_CONTAINER:/* MSDN says we can return the same value as PP_CONTAINER */
4042 return copy_param(pbData, pdwDataLen, (const BYTE*)pKeyContainer->szName,
4043 strlen(pKeyContainer->szName)+1);
4045 case PP_NAME:
4046 return copy_param(pbData, pdwDataLen, (const BYTE*)pKeyContainer->szProvName,
4047 strlen(pKeyContainer->szProvName)+1);
4049 case PP_PROVTYPE:
4050 dwTemp = PROV_RSA_FULL;
4051 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
4053 case PP_KEYSPEC:
4054 dwTemp = AT_SIGNATURE | AT_KEYEXCHANGE;
4055 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
4057 case PP_KEYSET_TYPE:
4058 dwTemp = pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET;
4059 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
4061 case PP_KEYSTORAGE:
4062 dwTemp = CRYPT_SEC_DESCR;
4063 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
4065 case PP_SIG_KEYSIZE_INC:
4066 case PP_KEYX_KEYSIZE_INC:
4067 dwTemp = 8;
4068 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
4070 case PP_IMPTYPE:
4071 dwTemp = CRYPT_IMPL_SOFTWARE;
4072 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
4074 case PP_VERSION:
4075 dwTemp = 0x00000200;
4076 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
4078 case PP_ENUMCONTAINERS:
4079 if ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) pKeyContainer->dwEnumContainersCtr = 0;
4081 if (!pbData) {
4082 *pdwDataLen = (DWORD)MAX_PATH + 1;
4083 return TRUE;
4086 if (!open_container_key("", dwFlags, KEY_READ, &hKey))
4088 SetLastError(ERROR_NO_MORE_ITEMS);
4089 return FALSE;
4092 dwTemp = *pdwDataLen;
4093 switch (RegEnumKeyExA(hKey, pKeyContainer->dwEnumContainersCtr, (LPSTR)pbData, &dwTemp,
4094 NULL, NULL, NULL, NULL))
4096 case ERROR_MORE_DATA:
4097 *pdwDataLen = (DWORD)MAX_PATH + 1;
4099 case ERROR_SUCCESS:
4100 pKeyContainer->dwEnumContainersCtr++;
4101 RegCloseKey(hKey);
4102 return TRUE;
4104 case ERROR_NO_MORE_ITEMS:
4105 default:
4106 SetLastError(ERROR_NO_MORE_ITEMS);
4107 RegCloseKey(hKey);
4108 return FALSE;
4111 case PP_ENUMALGS:
4112 case PP_ENUMALGS_EX:
4113 if (((pKeyContainer->dwEnumAlgsCtr >= RSAENH_MAX_ENUMALGS-1) ||
4114 (!aProvEnumAlgsEx[pKeyContainer->dwPersonality]
4115 [pKeyContainer->dwEnumAlgsCtr+1].aiAlgid)) &&
4116 ((dwFlags & CRYPT_FIRST) != CRYPT_FIRST))
4118 SetLastError(ERROR_NO_MORE_ITEMS);
4119 return FALSE;
4122 if (dwParam == PP_ENUMALGS) {
4123 if (pbData && (*pdwDataLen >= sizeof(PROV_ENUMALGS)))
4124 pKeyContainer->dwEnumAlgsCtr = ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) ?
4125 0 : pKeyContainer->dwEnumAlgsCtr+1;
4127 provEnumalgs.aiAlgid = aProvEnumAlgsEx
4128 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].aiAlgid;
4129 provEnumalgs.dwBitLen = aProvEnumAlgsEx
4130 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].dwDefaultLen;
4131 provEnumalgs.dwNameLen = aProvEnumAlgsEx
4132 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].dwNameLen;
4133 memcpy(provEnumalgs.szName, aProvEnumAlgsEx
4134 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].szName,
4135 20*sizeof(CHAR));
4137 return copy_param(pbData, pdwDataLen, (const BYTE*)&provEnumalgs,
4138 sizeof(PROV_ENUMALGS));
4139 } else {
4140 if (pbData && (*pdwDataLen >= sizeof(PROV_ENUMALGS_EX)))
4141 pKeyContainer->dwEnumAlgsCtr = ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) ?
4142 0 : pKeyContainer->dwEnumAlgsCtr+1;
4144 return copy_param(pbData, pdwDataLen,
4145 (const BYTE*)&aProvEnumAlgsEx
4146 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr],
4147 sizeof(PROV_ENUMALGS_EX));
4150 case PP_CRYPT_COUNT_KEY_USE: /* Asked for by IE About dialog */
4151 return copy_param(pbData, pdwDataLen, abWTF, sizeof(abWTF));
4153 case PP_KEYSET_SEC_DESCR:
4155 SECURITY_DESCRIPTOR *sd;
4156 DWORD err, len, flags = (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET);
4158 if (!open_container_key(pKeyContainer->szName, flags, KEY_READ, &hKey))
4160 SetLastError(NTE_BAD_KEYSET);
4161 return FALSE;
4164 err = GetSecurityInfo(hKey, SE_REGISTRY_KEY, dwFlags, NULL, NULL, NULL, NULL, (void **)&sd);
4165 RegCloseKey(hKey);
4166 if (err)
4168 SetLastError(err);
4169 return FALSE;
4172 len = GetSecurityDescriptorLength(sd);
4173 if (*pdwDataLen >= len) memcpy(pbData, sd, len);
4174 else SetLastError(ERROR_INSUFFICIENT_BUFFER);
4175 *pdwDataLen = len;
4177 LocalFree(sd);
4178 return TRUE;
4181 default:
4182 /* MSDN: Unknown parameter number in dwParam */
4183 SetLastError(NTE_BAD_TYPE);
4184 return FALSE;
4188 /******************************************************************************
4189 * CPDeriveKey (RSAENH.@)
4191 * Derives a key from a hash value.
4193 * PARAMS
4194 * hProv [I] Key container for which a key is to be generated.
4195 * Algid [I] Crypto algorithm identifier for the key to be generated.
4196 * hBaseData [I] Hash from whose value the key will be derived.
4197 * dwFlags [I] See Notes.
4198 * phKey [O] The generated key.
4200 * RETURNS
4201 * Success: TRUE
4202 * Failure: FALSE
4204 * NOTES
4205 * Defined flags:
4206 * - CRYPT_EXPORTABLE: Key can be exported.
4207 * - CRYPT_NO_SALT: No salt is used for 40 bit keys.
4208 * - CRYPT_CREATE_SALT: Use remaining bits as salt value.
4210 BOOL WINAPI RSAENH_CPDeriveKey(HCRYPTPROV hProv, ALG_ID Algid, HCRYPTHASH hBaseData,
4211 DWORD dwFlags, HCRYPTKEY *phKey)
4213 CRYPTKEY *pCryptKey, *pMasterKey;
4214 CRYPTHASH *pCryptHash;
4215 BYTE abHashValue[RSAENH_MAX_HASH_SIZE*2];
4216 DWORD dwLen;
4218 TRACE("(hProv=%08lx, Algid=%d, hBaseData=%08lx, dwFlags=%08x phKey=%p)\n", hProv, Algid,
4219 hBaseData, dwFlags, phKey);
4221 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
4223 SetLastError(NTE_BAD_UID);
4224 return FALSE;
4227 if (!lookup_handle(&handle_table, hBaseData, RSAENH_MAGIC_HASH,
4228 (OBJECTHDR**)&pCryptHash))
4230 SetLastError(NTE_BAD_HASH);
4231 return FALSE;
4234 if (!phKey)
4236 SetLastError(ERROR_INVALID_PARAMETER);
4237 return FALSE;
4240 switch (GET_ALG_CLASS(Algid))
4242 case ALG_CLASS_DATA_ENCRYPT:
4244 int need_padding, copy_len;
4245 *phKey = new_key(hProv, Algid, dwFlags, &pCryptKey);
4246 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
4249 * We derive the key material from the hash.
4250 * If the hash value is not large enough for the claimed key, we have to construct
4251 * a larger binary value based on the hash. This is documented in MSDN: CryptDeriveKey.
4253 dwLen = RSAENH_MAX_HASH_SIZE;
4254 RSAENH_CPGetHashParam(pCryptHash->hProv, hBaseData, HP_HASHVAL, abHashValue, &dwLen, 0);
4257 * The usage of padding seems to vary from algorithm to algorithm.
4258 * For now the only different case found was for AES with 128 bit key.
4260 switch(Algid)
4262 case CALG_AES_128:
4263 /* To reduce the chance of regressions we will only deviate
4264 * from the old behavior for the tested hash lengths */
4265 if (dwLen == 16 || dwLen == 20)
4267 need_padding = 1;
4268 break;
4270 default:
4271 need_padding = dwLen < pCryptKey->dwKeyLen;
4274 copy_len = pCryptKey->dwKeyLen;
4275 if (need_padding)
4277 BYTE pad1[RSAENH_HMAC_DEF_PAD_LEN], pad2[RSAENH_HMAC_DEF_PAD_LEN];
4278 BYTE old_hashval[RSAENH_MAX_HASH_SIZE];
4279 DWORD i;
4281 memcpy(old_hashval, pCryptHash->abHashValue, RSAENH_MAX_HASH_SIZE);
4283 for (i=0; i<RSAENH_HMAC_DEF_PAD_LEN; i++) {
4284 pad1[i] = RSAENH_HMAC_DEF_IPAD_CHAR ^ (i<dwLen ? abHashValue[i] : 0);
4285 pad2[i] = RSAENH_HMAC_DEF_OPAD_CHAR ^ (i<dwLen ? abHashValue[i] : 0);
4288 init_hash(pCryptHash);
4289 update_hash(pCryptHash, pad1, RSAENH_HMAC_DEF_PAD_LEN);
4290 finalize_hash(pCryptHash);
4291 memcpy(abHashValue, pCryptHash->abHashValue, pCryptHash->dwHashSize);
4293 init_hash(pCryptHash);
4294 update_hash(pCryptHash, pad2, RSAENH_HMAC_DEF_PAD_LEN);
4295 finalize_hash(pCryptHash);
4296 memcpy(abHashValue+pCryptHash->dwHashSize, pCryptHash->abHashValue,
4297 pCryptHash->dwHashSize);
4299 memcpy(pCryptHash->abHashValue, old_hashval, RSAENH_MAX_HASH_SIZE);
4302 * Padding was not required, we have more hash than needed.
4303 * Do we need to use the remaining hash as salt?
4305 else if((dwFlags & CRYPT_CREATE_SALT) &&
4306 (Algid == CALG_RC2 || Algid == CALG_RC4))
4308 copy_len += pCryptKey->dwSaltLen;
4311 memcpy(pCryptKey->abKeyValue, abHashValue,
4312 RSAENH_MIN(copy_len, sizeof(pCryptKey->abKeyValue)));
4313 break;
4315 case ALG_CLASS_MSG_ENCRYPT:
4316 if (!lookup_handle(&handle_table, pCryptHash->hKey, RSAENH_MAGIC_KEY,
4317 (OBJECTHDR**)&pMasterKey))
4319 SetLastError(NTE_FAIL); /* FIXME error code */
4320 return FALSE;
4323 switch (Algid)
4325 /* See RFC 2246, chapter 6.3 Key calculation */
4326 case CALG_SCHANNEL_ENC_KEY:
4327 if (!pMasterKey->siSChannelInfo.saEncAlg.Algid ||
4328 !pMasterKey->siSChannelInfo.saEncAlg.cBits)
4330 SetLastError(NTE_BAD_FLAGS);
4331 return FALSE;
4333 *phKey = new_key(hProv, pMasterKey->siSChannelInfo.saEncAlg.Algid,
4334 MAKELONG(LOWORD(dwFlags),pMasterKey->siSChannelInfo.saEncAlg.cBits),
4335 &pCryptKey);
4336 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
4337 memcpy(pCryptKey->abKeyValue,
4338 pCryptHash->abHashValue + (
4339 2 * (pMasterKey->siSChannelInfo.saMACAlg.cBits / 8) +
4340 ((dwFlags & CRYPT_SERVER) ?
4341 (pMasterKey->siSChannelInfo.saEncAlg.cBits / 8) : 0)),
4342 pMasterKey->siSChannelInfo.saEncAlg.cBits / 8);
4343 memcpy(pCryptKey->abInitVector,
4344 pCryptHash->abHashValue + (
4345 2 * (pMasterKey->siSChannelInfo.saMACAlg.cBits / 8) +
4346 2 * (pMasterKey->siSChannelInfo.saEncAlg.cBits / 8) +
4347 ((dwFlags & CRYPT_SERVER) ? pCryptKey->dwBlockLen : 0)),
4348 pCryptKey->dwBlockLen);
4349 break;
4351 case CALG_SCHANNEL_MAC_KEY:
4352 *phKey = new_key(hProv, Algid,
4353 MAKELONG(LOWORD(dwFlags),pMasterKey->siSChannelInfo.saMACAlg.cBits),
4354 &pCryptKey);
4355 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
4356 memcpy(pCryptKey->abKeyValue,
4357 pCryptHash->abHashValue + ((dwFlags & CRYPT_SERVER) ?
4358 pMasterKey->siSChannelInfo.saMACAlg.cBits / 8 : 0),
4359 pMasterKey->siSChannelInfo.saMACAlg.cBits / 8);
4360 break;
4362 default:
4363 SetLastError(NTE_BAD_ALGID);
4364 return FALSE;
4366 break;
4368 default:
4369 SetLastError(NTE_BAD_ALGID);
4370 return FALSE;
4373 setup_key(pCryptKey);
4374 return TRUE;
4377 /******************************************************************************
4378 * CPGetUserKey (RSAENH.@)
4380 * Returns a handle to the user's private key-exchange- or signature-key.
4382 * PARAMS
4383 * hProv [I] The key container from which a user key is requested.
4384 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
4385 * phUserKey [O] Handle to the requested key or INVALID_HANDLE_VALUE in case of failure.
4387 * RETURNS
4388 * Success: TRUE.
4389 * Failure: FALSE.
4391 * NOTE
4392 * A newly created key container does not contain private user key. Create them with CPGenKey.
4394 BOOL WINAPI RSAENH_CPGetUserKey(HCRYPTPROV hProv, DWORD dwKeySpec, HCRYPTKEY *phUserKey)
4396 KEYCONTAINER *pKeyContainer;
4398 TRACE("(hProv=%08lx, dwKeySpec=%08x, phUserKey=%p)\n", hProv, dwKeySpec, phUserKey);
4400 if (!(pKeyContainer = get_key_container(hProv)))
4402 /* MSDN: hProv not containing valid context handle */
4403 return FALSE;
4406 switch (dwKeySpec)
4408 case AT_KEYEXCHANGE:
4409 copy_handle(&handle_table, pKeyContainer->hKeyExchangeKeyPair, RSAENH_MAGIC_KEY,
4410 phUserKey);
4411 break;
4413 case AT_SIGNATURE:
4414 copy_handle(&handle_table, pKeyContainer->hSignatureKeyPair, RSAENH_MAGIC_KEY,
4415 phUserKey);
4416 break;
4418 default:
4419 *phUserKey = (HCRYPTKEY)INVALID_HANDLE_VALUE;
4422 if (*phUserKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
4424 /* MSDN: dwKeySpec parameter specifies nonexistent key */
4425 SetLastError(NTE_NO_KEY);
4426 return FALSE;
4429 return TRUE;
4432 /******************************************************************************
4433 * CPHashData (RSAENH.@)
4435 * Updates a hash object with the given data.
4437 * PARAMS
4438 * hProv [I] Key container to which the hash object belongs.
4439 * hHash [I] Hash object which is to be updated.
4440 * pbData [I] Pointer to data with which the hash object is to be updated.
4441 * dwDataLen [I] Length of the data.
4442 * dwFlags [I] Currently none defined.
4444 * RETURNS
4445 * Success: TRUE.
4446 * Failure: FALSE.
4448 * NOTES
4449 * The actual hash value is queried with CPGetHashParam, which will finalize
4450 * the hash. Updating a finalized hash will fail with a last error NTE_BAD_HASH_STATE.
4452 BOOL WINAPI RSAENH_CPHashData(HCRYPTPROV hProv, HCRYPTHASH hHash, const BYTE *pbData,
4453 DWORD dwDataLen, DWORD dwFlags)
4455 CRYPTHASH *pCryptHash;
4457 TRACE("(hProv=%08lx, hHash=%08lx, pbData=%p, dwDataLen=%d, dwFlags=%08x)\n",
4458 hProv, hHash, pbData, dwDataLen, dwFlags);
4460 if (dwFlags & ~CRYPT_USERDATA)
4462 SetLastError(NTE_BAD_FLAGS);
4463 return FALSE;
4466 if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH,
4467 (OBJECTHDR**)&pCryptHash))
4469 SetLastError(NTE_BAD_HASH);
4470 return FALSE;
4473 if (!get_algid_info(hProv, pCryptHash->aiAlgid) || pCryptHash->aiAlgid == CALG_SSL3_SHAMD5)
4475 SetLastError(NTE_BAD_ALGID);
4476 return FALSE;
4479 if (pCryptHash->dwState != RSAENH_HASHSTATE_HASHING)
4481 SetLastError(NTE_BAD_HASH_STATE);
4482 return FALSE;
4485 update_hash(pCryptHash, pbData, dwDataLen);
4486 return TRUE;
4489 /******************************************************************************
4490 * CPHashSessionKey (RSAENH.@)
4492 * Updates a hash object with the binary representation of a symmetric key.
4494 * PARAMS
4495 * hProv [I] Key container to which the hash object belongs.
4496 * hHash [I] Hash object which is to be updated.
4497 * hKey [I] The symmetric key, whose binary value will be added to the hash.
4498 * dwFlags [I] CRYPT_LITTLE_ENDIAN, if the binary key value shall be interpreted as little endian.
4500 * RETURNS
4501 * Success: TRUE.
4502 * Failure: FALSE.
4504 BOOL WINAPI RSAENH_CPHashSessionKey(HCRYPTPROV hProv, HCRYPTHASH hHash, HCRYPTKEY hKey,
4505 DWORD dwFlags)
4507 BYTE abKeyValue[RSAENH_MAX_KEY_SIZE], bTemp;
4508 CRYPTKEY *pKey;
4509 DWORD i;
4511 TRACE("(hProv=%08lx, hHash=%08lx, hKey=%08lx, dwFlags=%08x)\n", hProv, hHash, hKey, dwFlags);
4513 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pKey) ||
4514 (GET_ALG_CLASS(pKey->aiAlgid) != ALG_CLASS_DATA_ENCRYPT))
4516 SetLastError(NTE_BAD_KEY);
4517 return FALSE;
4520 if (dwFlags & ~CRYPT_LITTLE_ENDIAN) {
4521 SetLastError(NTE_BAD_FLAGS);
4522 return FALSE;
4525 memcpy(abKeyValue, pKey->abKeyValue, pKey->dwKeyLen);
4526 if (!(dwFlags & CRYPT_LITTLE_ENDIAN)) {
4527 for (i=0; i<pKey->dwKeyLen/2; i++) {
4528 bTemp = abKeyValue[i];
4529 abKeyValue[i] = abKeyValue[pKey->dwKeyLen-i-1];
4530 abKeyValue[pKey->dwKeyLen-i-1] = bTemp;
4534 return RSAENH_CPHashData(hProv, hHash, abKeyValue, pKey->dwKeyLen, 0);
4537 /******************************************************************************
4538 * CPReleaseContext (RSAENH.@)
4540 * Release a key container.
4542 * PARAMS
4543 * hProv [I] Key container to be released.
4544 * dwFlags [I] Currently none defined.
4546 * RETURNS
4547 * Success: TRUE
4548 * Failure: FALSE
4550 BOOL WINAPI RSAENH_CPReleaseContext(HCRYPTPROV hProv, DWORD dwFlags)
4552 TRACE("(hProv=%08lx, dwFlags=%08x)\n", hProv, dwFlags);
4554 if (!release_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
4556 /* MSDN: hProv not containing valid context handle */
4557 SetLastError(NTE_BAD_UID);
4558 return FALSE;
4561 if (dwFlags) {
4562 SetLastError(NTE_BAD_FLAGS);
4563 return FALSE;
4566 return TRUE;
4569 /******************************************************************************
4570 * CPSetHashParam (RSAENH.@)
4572 * Set a parameter of a hash object
4574 * PARAMS
4575 * hProv [I] The key container to which the key belongs.
4576 * hHash [I] The hash object for which a parameter is to be set.
4577 * dwParam [I] Parameter type. See Notes.
4578 * pbData [I] Pointer to the parameter value.
4579 * dwFlags [I] Currently none defined.
4581 * RETURNS
4582 * Success: TRUE.
4583 * Failure: FALSE.
4585 * NOTES
4586 * Currently only the HP_HMAC_INFO dwParam type is defined.
4587 * The HMAC_INFO struct will be deep copied into the hash object.
4588 * See Internet RFC 2104 for details on the HMAC algorithm.
4590 BOOL WINAPI RSAENH_CPSetHashParam(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwParam,
4591 BYTE *pbData, DWORD dwFlags)
4593 CRYPTHASH *pCryptHash;
4594 CRYPTKEY *pCryptKey;
4595 DWORD i;
4597 TRACE("(hProv=%08lx, hHash=%08lx, dwParam=%08x, pbData=%p, dwFlags=%08x)\n",
4598 hProv, hHash, dwParam, pbData, dwFlags);
4600 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
4602 SetLastError(NTE_BAD_UID);
4603 return FALSE;
4606 if (dwFlags) {
4607 SetLastError(NTE_BAD_FLAGS);
4608 return FALSE;
4611 if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH,
4612 (OBJECTHDR**)&pCryptHash))
4614 SetLastError(NTE_BAD_HASH);
4615 return FALSE;
4618 switch (dwParam) {
4619 case HP_HMAC_INFO:
4620 free_hmac_info(pCryptHash->pHMACInfo);
4621 if (!copy_hmac_info(&pCryptHash->pHMACInfo, (PHMAC_INFO)pbData)) return FALSE;
4623 if (!lookup_handle(&handle_table, pCryptHash->hKey, RSAENH_MAGIC_KEY,
4624 (OBJECTHDR**)&pCryptKey))
4626 SetLastError(NTE_FAIL); /* FIXME: correct error code? */
4627 return FALSE;
4630 if (pCryptKey->aiAlgid == CALG_HMAC && !pCryptKey->dwKeyLen) {
4631 HCRYPTHASH hKeyHash;
4632 DWORD keyLen;
4634 if (!RSAENH_CPCreateHash(hProv, ((PHMAC_INFO)pbData)->HashAlgid, 0, 0,
4635 &hKeyHash))
4636 return FALSE;
4637 if (!RSAENH_CPHashData(hProv, hKeyHash, pCryptKey->blobHmacKey.pbData,
4638 pCryptKey->blobHmacKey.cbData, 0))
4640 RSAENH_CPDestroyHash(hProv, hKeyHash);
4641 return FALSE;
4643 keyLen = sizeof(pCryptKey->abKeyValue);
4644 if (!RSAENH_CPGetHashParam(hProv, hKeyHash, HP_HASHVAL, pCryptKey->abKeyValue,
4645 &keyLen, 0))
4647 RSAENH_CPDestroyHash(hProv, hKeyHash);
4648 return FALSE;
4650 pCryptKey->dwKeyLen = keyLen;
4651 RSAENH_CPDestroyHash(hProv, hKeyHash);
4653 for (i=0; i<RSAENH_MIN(pCryptKey->dwKeyLen,pCryptHash->pHMACInfo->cbInnerString); i++) {
4654 pCryptHash->pHMACInfo->pbInnerString[i] ^= pCryptKey->abKeyValue[i];
4656 for (i=0; i<RSAENH_MIN(pCryptKey->dwKeyLen,pCryptHash->pHMACInfo->cbOuterString); i++) {
4657 pCryptHash->pHMACInfo->pbOuterString[i] ^= pCryptKey->abKeyValue[i];
4660 init_hash(pCryptHash);
4661 return TRUE;
4663 case HP_HASHVAL:
4664 memcpy(pCryptHash->abHashValue, pbData, pCryptHash->dwHashSize);
4665 pCryptHash->dwState = RSAENH_HASHSTATE_FINISHED;
4666 return TRUE;
4668 case HP_TLS1PRF_SEED:
4669 return copy_data_blob(&pCryptHash->tpPRFParams.blobSeed, (PCRYPT_DATA_BLOB)pbData);
4671 case HP_TLS1PRF_LABEL:
4672 return copy_data_blob(&pCryptHash->tpPRFParams.blobLabel, (PCRYPT_DATA_BLOB)pbData);
4674 default:
4675 SetLastError(NTE_BAD_TYPE);
4676 return FALSE;
4680 /******************************************************************************
4681 * CPSetProvParam (RSAENH.@)
4683 BOOL WINAPI RSAENH_CPSetProvParam(HCRYPTPROV hProv, DWORD dwParam, BYTE *pbData, DWORD dwFlags)
4685 KEYCONTAINER *pKeyContainer;
4686 HKEY hKey;
4688 TRACE("(hProv=%08lx, dwParam=%08x, pbData=%p, dwFlags=%08x)\n", hProv, dwParam, pbData, dwFlags);
4690 if (!(pKeyContainer = get_key_container(hProv)))
4691 return FALSE;
4693 switch (dwParam)
4695 case PP_KEYSET_SEC_DESCR:
4697 SECURITY_DESCRIPTOR *sd = (SECURITY_DESCRIPTOR *)pbData;
4698 DWORD err, flags = (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET);
4699 BOOL def, present;
4700 REGSAM access = WRITE_DAC | WRITE_OWNER | ACCESS_SYSTEM_SECURITY;
4701 PSID owner = NULL, group = NULL;
4702 PACL dacl = NULL, sacl = NULL;
4704 if (!open_container_key(pKeyContainer->szName, flags, access, &hKey))
4706 SetLastError(NTE_BAD_KEYSET);
4707 return FALSE;
4710 if ((dwFlags & OWNER_SECURITY_INFORMATION && !GetSecurityDescriptorOwner(sd, &owner, &def)) ||
4711 (dwFlags & GROUP_SECURITY_INFORMATION && !GetSecurityDescriptorGroup(sd, &group, &def)) ||
4712 (dwFlags & DACL_SECURITY_INFORMATION && !GetSecurityDescriptorDacl(sd, &present, &dacl, &def)) ||
4713 (dwFlags & SACL_SECURITY_INFORMATION && !GetSecurityDescriptorSacl(sd, &present, &sacl, &def)))
4715 RegCloseKey(hKey);
4716 return FALSE;
4719 err = SetSecurityInfo(hKey, SE_REGISTRY_KEY, dwFlags, owner, group, dacl, sacl);
4720 RegCloseKey(hKey);
4721 if (err)
4723 SetLastError(err);
4724 return FALSE;
4726 return TRUE;
4728 default:
4729 FIXME("unimplemented parameter %08x\n", dwParam);
4730 return FALSE;
4734 /******************************************************************************
4735 * CPSignHash (RSAENH.@)
4737 * Sign a hash object
4739 * PARAMS
4740 * hProv [I] The key container, to which the hash object belongs.
4741 * hHash [I] The hash object to be signed.
4742 * dwKeySpec [I] AT_SIGNATURE or AT_KEYEXCHANGE: Key used to generate the signature.
4743 * sDescription [I] Should be NULL for security reasons.
4744 * dwFlags [I] 0, CRYPT_NOHASHOID or CRYPT_X931_FORMAT: Format of the signature.
4745 * pbSignature [O] Buffer, to which the signature will be stored. May be NULL to query SigLen.
4746 * pdwSigLen [I/O] Size of the buffer (in), Length of the signature (out)
4748 * RETURNS
4749 * Success: TRUE
4750 * Failure: FALSE
4752 BOOL WINAPI RSAENH_CPSignHash(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwKeySpec,
4753 LPCWSTR sDescription, DWORD dwFlags, BYTE *pbSignature,
4754 DWORD *pdwSigLen)
4756 HCRYPTKEY hCryptKey = (HCRYPTKEY)INVALID_HANDLE_VALUE;
4757 CRYPTKEY *pCryptKey;
4758 DWORD dwHashLen;
4759 BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
4760 ALG_ID aiAlgid;
4761 BOOL ret = FALSE;
4763 TRACE("(hProv=%08lx, hHash=%08lx, dwKeySpec=%08x, sDescription=%s, dwFlags=%08x, "
4764 "pbSignature=%p, pdwSigLen=%p)\n", hProv, hHash, dwKeySpec, debugstr_w(sDescription),
4765 dwFlags, pbSignature, pdwSigLen);
4767 if (dwFlags & ~(CRYPT_NOHASHOID|CRYPT_X931_FORMAT)) {
4768 SetLastError(NTE_BAD_FLAGS);
4769 return FALSE;
4772 if (!RSAENH_CPGetUserKey(hProv, dwKeySpec, &hCryptKey)) return FALSE;
4774 if (!lookup_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY,
4775 (OBJECTHDR**)&pCryptKey))
4777 SetLastError(NTE_NO_KEY);
4778 goto out;
4781 if (!pbSignature) {
4782 *pdwSigLen = pCryptKey->dwKeyLen;
4783 ret = TRUE;
4784 goto out;
4786 if (pCryptKey->dwKeyLen > *pdwSigLen)
4788 SetLastError(ERROR_MORE_DATA);
4789 *pdwSigLen = pCryptKey->dwKeyLen;
4790 goto out;
4792 *pdwSigLen = pCryptKey->dwKeyLen;
4794 if (sDescription) {
4795 if (!RSAENH_CPHashData(hProv, hHash, (const BYTE*)sDescription,
4796 (DWORD)lstrlenW(sDescription)*sizeof(WCHAR), 0))
4798 goto out;
4802 dwHashLen = sizeof(DWORD);
4803 if (!RSAENH_CPGetHashParam(hProv, hHash, HP_ALGID, (BYTE*)&aiAlgid, &dwHashLen, 0)) goto out;
4805 dwHashLen = RSAENH_MAX_HASH_SIZE;
4806 if (!RSAENH_CPGetHashParam(hProv, hHash, HP_HASHVAL, abHashValue, &dwHashLen, 0)) goto out;
4809 if (!build_hash_signature(pbSignature, *pdwSigLen, aiAlgid, abHashValue, dwHashLen, dwFlags)) {
4810 goto out;
4813 ret = encrypt_block_impl(pCryptKey->aiAlgid, PK_PRIVATE, &pCryptKey->context, pbSignature, pbSignature, RSAENH_ENCRYPT);
4814 out:
4815 RSAENH_CPDestroyKey(hProv, hCryptKey);
4816 return ret;
4819 /******************************************************************************
4820 * CPVerifySignature (RSAENH.@)
4822 * Verify the signature of a hash object.
4824 * PARAMS
4825 * hProv [I] The key container, to which the hash belongs.
4826 * hHash [I] The hash for which the signature is verified.
4827 * pbSignature [I] The binary signature.
4828 * dwSigLen [I] Length of the signature BLOB.
4829 * hPubKey [I] Public key used to verify the signature.
4830 * sDescription [I] Should be NULL for security reasons.
4831 * dwFlags [I] 0, CRYPT_NOHASHOID or CRYPT_X931_FORMAT: Format of the signature.
4833 * RETURNS
4834 * Success: TRUE (Signature is valid)
4835 * Failure: FALSE (GetLastError() == NTE_BAD_SIGNATURE, if signature is invalid)
4837 BOOL WINAPI RSAENH_CPVerifySignature(HCRYPTPROV hProv, HCRYPTHASH hHash, const BYTE *pbSignature,
4838 DWORD dwSigLen, HCRYPTKEY hPubKey, LPCWSTR sDescription,
4839 DWORD dwFlags)
4841 BYTE *pbConstructed = NULL, *pbDecrypted = NULL;
4842 CRYPTKEY *pCryptKey;
4843 DWORD dwHashLen;
4844 ALG_ID aiAlgid;
4845 BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
4846 BOOL res = FALSE;
4848 TRACE("(hProv=%08lx, hHash=%08lx, pbSignature=%p, dwSigLen=%d, hPubKey=%08lx, sDescription=%s, "
4849 "dwFlags=%08x)\n", hProv, hHash, pbSignature, dwSigLen, hPubKey, debugstr_w(sDescription),
4850 dwFlags);
4852 if (dwFlags & ~(CRYPT_NOHASHOID|CRYPT_X931_FORMAT)) {
4853 SetLastError(NTE_BAD_FLAGS);
4854 return FALSE;
4857 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
4859 SetLastError(NTE_BAD_UID);
4860 return FALSE;
4863 if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY,
4864 (OBJECTHDR**)&pCryptKey))
4866 SetLastError(NTE_BAD_KEY);
4867 return FALSE;
4870 /* in Microsoft implementation, the signature length is checked before
4871 * the signature pointer.
4873 if (dwSigLen != pCryptKey->dwKeyLen)
4875 SetLastError(NTE_BAD_SIGNATURE);
4876 return FALSE;
4879 if (!hHash || !pbSignature)
4881 SetLastError(ERROR_INVALID_PARAMETER);
4882 return FALSE;
4885 if (sDescription) {
4886 if (!RSAENH_CPHashData(hProv, hHash, (const BYTE*)sDescription,
4887 (DWORD)lstrlenW(sDescription)*sizeof(WCHAR), 0))
4889 return FALSE;
4893 dwHashLen = sizeof(DWORD);
4894 if (!RSAENH_CPGetHashParam(hProv, hHash, HP_ALGID, (BYTE*)&aiAlgid, &dwHashLen, 0)) return FALSE;
4896 dwHashLen = RSAENH_MAX_HASH_SIZE;
4897 if (!RSAENH_CPGetHashParam(hProv, hHash, HP_HASHVAL, abHashValue, &dwHashLen, 0)) return FALSE;
4899 pbConstructed = HeapAlloc(GetProcessHeap(), 0, dwSigLen);
4900 if (!pbConstructed) {
4901 SetLastError(NTE_NO_MEMORY);
4902 goto cleanup;
4905 pbDecrypted = HeapAlloc(GetProcessHeap(), 0, dwSigLen);
4906 if (!pbDecrypted) {
4907 SetLastError(NTE_NO_MEMORY);
4908 goto cleanup;
4911 if (!encrypt_block_impl(pCryptKey->aiAlgid, PK_PUBLIC, &pCryptKey->context, pbSignature, pbDecrypted,
4912 RSAENH_DECRYPT))
4914 goto cleanup;
4917 if (build_hash_signature(pbConstructed, dwSigLen, aiAlgid, abHashValue, dwHashLen, dwFlags) &&
4918 !memcmp(pbDecrypted, pbConstructed, dwSigLen)) {
4919 res = TRUE;
4920 goto cleanup;
4923 if (!(dwFlags & CRYPT_NOHASHOID) &&
4924 build_hash_signature(pbConstructed, dwSigLen, aiAlgid, abHashValue, dwHashLen, dwFlags|CRYPT_NOHASHOID) &&
4925 !memcmp(pbDecrypted, pbConstructed, dwSigLen)) {
4926 res = TRUE;
4927 goto cleanup;
4930 SetLastError(NTE_BAD_SIGNATURE);
4932 cleanup:
4933 HeapFree(GetProcessHeap(), 0, pbConstructed);
4934 HeapFree(GetProcessHeap(), 0, pbDecrypted);
4935 return res;
4938 /******************************************************************************
4939 * DllRegisterServer (RSAENH.@)
4941 HRESULT WINAPI DllRegisterServer(void)
4943 return __wine_register_resources( instance );
4946 /******************************************************************************
4947 * DllUnregisterServer (RSAENH.@)
4949 HRESULT WINAPI DllUnregisterServer(void)
4951 return __wine_unregister_resources( instance );