msvcp140: Added _Winerror_message implementation.
[wine.git] / dlls / rsaenh / rsaenh.c
blob1332073bb7168747acce019cdc7a608410e62103
1 /*
2 * dlls/rsaenh/rsaenh.c
3 * RSAENH - RSA encryption for Wine
5 * Copyright 2002 TransGaming Technologies (David Hammerton)
6 * Copyright 2004 Mike McCormack for CodeWeavers
7 * Copyright 2004, 2005 Michael Jung
8 * Copyright 2007 Vijay Kiran Kamuju
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
25 #include "config.h"
26 #include "wine/port.h"
27 #include "wine/library.h"
28 #include "wine/debug.h"
30 #include <stdarg.h>
31 #include <stdio.h>
33 #include "windef.h"
34 #include "winbase.h"
35 #include "winreg.h"
36 #include "wincrypt.h"
37 #include "handle.h"
38 #include "implglue.h"
39 #include "objbase.h"
40 #include "rpcproxy.h"
41 #include "aclapi.h"
43 WINE_DEFAULT_DEBUG_CHANNEL(crypt);
45 static HINSTANCE instance;
47 /******************************************************************************
48 * CRYPTHASH - hash objects
50 #define RSAENH_MAGIC_HASH 0x85938417u
51 #define RSAENH_HASHSTATE_HASHING 1
52 #define RSAENH_HASHSTATE_FINISHED 2
53 typedef struct _RSAENH_TLS1PRF_PARAMS
55 CRYPT_DATA_BLOB blobLabel;
56 CRYPT_DATA_BLOB blobSeed;
57 } RSAENH_TLS1PRF_PARAMS;
59 typedef struct tagCRYPTHASH
61 OBJECTHDR header;
62 ALG_ID aiAlgid;
63 HCRYPTKEY hKey;
64 HCRYPTPROV hProv;
65 DWORD dwHashSize;
66 DWORD dwState;
67 HASH_CONTEXT context;
68 BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
69 PHMAC_INFO pHMACInfo;
70 RSAENH_TLS1PRF_PARAMS tpPRFParams;
71 } CRYPTHASH;
73 /******************************************************************************
74 * CRYPTKEY - key objects
76 #define RSAENH_MAGIC_KEY 0x73620457u
77 #define RSAENH_MAX_KEY_SIZE 64
78 #define RSAENH_MAX_BLOCK_SIZE 24
79 #define RSAENH_KEYSTATE_IDLE 0
80 #define RSAENH_KEYSTATE_ENCRYPTING 1
81 #define RSAENH_KEYSTATE_MASTERKEY 2
82 typedef struct _RSAENH_SCHANNEL_INFO
84 SCHANNEL_ALG saEncAlg;
85 SCHANNEL_ALG saMACAlg;
86 CRYPT_DATA_BLOB blobClientRandom;
87 CRYPT_DATA_BLOB blobServerRandom;
88 } RSAENH_SCHANNEL_INFO;
90 typedef struct tagCRYPTKEY
92 OBJECTHDR header;
93 ALG_ID aiAlgid;
94 HCRYPTPROV hProv;
95 DWORD dwMode;
96 DWORD dwModeBits;
97 DWORD dwPermissions;
98 DWORD dwKeyLen;
99 DWORD dwEffectiveKeyLen;
100 DWORD dwSaltLen;
101 DWORD dwBlockLen;
102 DWORD dwState;
103 KEY_CONTEXT context;
104 BYTE abKeyValue[RSAENH_MAX_KEY_SIZE];
105 BYTE abInitVector[RSAENH_MAX_BLOCK_SIZE];
106 BYTE abChainVector[RSAENH_MAX_BLOCK_SIZE];
107 RSAENH_SCHANNEL_INFO siSChannelInfo;
108 CRYPT_DATA_BLOB blobHmacKey;
109 } CRYPTKEY;
111 /******************************************************************************
112 * KEYCONTAINER - key containers
114 #define RSAENH_PERSONALITY_BASE 0u
115 #define RSAENH_PERSONALITY_STRONG 1u
116 #define RSAENH_PERSONALITY_ENHANCED 2u
117 #define RSAENH_PERSONALITY_SCHANNEL 3u
118 #define RSAENH_PERSONALITY_AES 4u
120 #define RSAENH_MAGIC_CONTAINER 0x26384993u
121 typedef struct tagKEYCONTAINER
123 OBJECTHDR header;
124 DWORD dwFlags;
125 DWORD dwPersonality;
126 DWORD dwEnumAlgsCtr;
127 DWORD dwEnumContainersCtr;
128 CHAR szName[MAX_PATH];
129 CHAR szProvName[MAX_PATH];
130 HCRYPTKEY hKeyExchangeKeyPair;
131 HCRYPTKEY hSignatureKeyPair;
132 } KEYCONTAINER;
134 /******************************************************************************
135 * Some magic constants
137 #define RSAENH_ENCRYPT 1
138 #define RSAENH_DECRYPT 0
139 #define RSAENH_HMAC_DEF_IPAD_CHAR 0x36
140 #define RSAENH_HMAC_DEF_OPAD_CHAR 0x5c
141 #define RSAENH_HMAC_DEF_PAD_LEN 64
142 #define RSAENH_HMAC_BLOCK_LEN 64
143 #define RSAENH_DES_EFFECTIVE_KEYLEN 56
144 #define RSAENH_DES_STORAGE_KEYLEN 64
145 #define RSAENH_3DES112_EFFECTIVE_KEYLEN 112
146 #define RSAENH_3DES112_STORAGE_KEYLEN 128
147 #define RSAENH_3DES_EFFECTIVE_KEYLEN 168
148 #define RSAENH_3DES_STORAGE_KEYLEN 192
149 #define RSAENH_MAGIC_RSA2 0x32415352
150 #define RSAENH_MAGIC_RSA1 0x31415352
151 #define RSAENH_PKC_BLOCKTYPE 0x02
152 #define RSAENH_SSL3_VERSION_MAJOR 3
153 #define RSAENH_SSL3_VERSION_MINOR 0
154 #define RSAENH_TLS1_VERSION_MAJOR 3
155 #define RSAENH_TLS1_VERSION_MINOR 1
156 #define RSAENH_REGKEY "Software\\Wine\\Crypto\\RSA\\%s"
158 #define RSAENH_MIN(a,b) ((a)<(b)?(a):(b))
159 /******************************************************************************
160 * aProvEnumAlgsEx - Defines the capabilities of the CSP personalities.
162 #define RSAENH_MAX_ENUMALGS 24
163 #define RSAENH_PCT1_SSL2_SSL3_TLS1 (CRYPT_FLAG_PCT1|CRYPT_FLAG_SSL2|CRYPT_FLAG_SSL3|CRYPT_FLAG_TLS1)
164 #define S(s) sizeof(s), s
165 static const PROV_ENUMALGS_EX aProvEnumAlgsEx[5][RSAENH_MAX_ENUMALGS+1] =
168 {CALG_RC2, 40, 40, 56, 0, S("RC2"), S("RSA Data Security's RC2")},
169 {CALG_RC4, 40, 40, 56, 0, S("RC4"), S("RSA Data Security's RC4")},
170 {CALG_DES, 56, 56, 56, 0, S("DES"), S("Data Encryption Standard (DES)")},
171 {CALG_SHA, 160, 160, 160, CRYPT_FLAG_SIGNING, S("SHA-1"), S("Secure Hash Algorithm (SHA-1)")},
172 {CALG_MD2, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD2"), S("Message Digest 2 (MD2)")},
173 {CALG_MD4, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD4"), S("Message Digest 4 (MD4)")},
174 {CALG_MD5, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD5"), S("Message Digest 5 (MD5)")},
175 {CALG_SSL3_SHAMD5, 288, 288, 288, 0, S("SSL3 SHAMD5"), S("SSL3 SHAMD5")},
176 {CALG_MAC, 0, 0, 0, 0, S("MAC"), S("Message Authentication Code")},
177 {CALG_RSA_SIGN, 512, 384, 16384, CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC, S("RSA_SIGN"), S("RSA Signature")},
178 {CALG_RSA_KEYX, 512, 384, 1024, CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC, S("RSA_KEYX"), S("RSA Key Exchange")},
179 {CALG_HMAC, 0, 0, 0, 0, S("HMAC"), S("Hugo's MAC (HMAC)")},
180 {0, 0, 0, 0, 0, S(""), S("")}
183 {CALG_RC2, 128, 40, 128, 0, S("RC2"), S("RSA Data Security's RC2")},
184 {CALG_RC4, 128, 40, 128, 0, S("RC4"), S("RSA Data Security's RC4")},
185 {CALG_DES, 56, 56, 56, 0, S("DES"), S("Data Encryption Standard (DES)")},
186 {CALG_3DES_112, 112, 112, 112, 0, S("3DES TWO KEY"), S("Two Key Triple DES")},
187 {CALG_3DES, 168, 168, 168, 0, S("3DES"), S("Three Key Triple DES")},
188 {CALG_SHA, 160, 160, 160, CRYPT_FLAG_SIGNING, S("SHA-1"), S("Secure Hash Algorithm (SHA-1)")},
189 {CALG_MD2, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD2"), S("Message Digest 2 (MD2)")},
190 {CALG_MD4, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD4"), S("Message Digest 4 (MD4)")},
191 {CALG_MD5, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD5"), S("Message Digest 5 (MD5)")},
192 {CALG_SSL3_SHAMD5, 288, 288, 288, 0, S("SSL3 SHAMD5"), S("SSL3 SHAMD5")},
193 {CALG_MAC, 0, 0, 0, 0, S("MAC"), S("Message Authentication Code")},
194 {CALG_RSA_SIGN, 1024, 384, 16384, CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC, S("RSA_SIGN"), S("RSA Signature")},
195 {CALG_RSA_KEYX, 1024, 384, 16384, CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC, S("RSA_KEYX"), S("RSA Key Exchange")},
196 {CALG_HMAC, 0, 0, 0, 0, S("HMAC"), S("Hugo's MAC (HMAC)")},
197 {0, 0, 0, 0, 0, S(""), S("")}
200 {CALG_RC2, 128, 40, 128, 0, S("RC2"), S("RSA Data Security's RC2")},
201 {CALG_RC4, 128, 40, 128, 0, S("RC4"), S("RSA Data Security's RC4")},
202 {CALG_DES, 56, 56, 56, 0, S("DES"), S("Data Encryption Standard (DES)")},
203 {CALG_3DES_112, 112, 112, 112, 0, S("3DES TWO KEY"), S("Two Key Triple DES")},
204 {CALG_3DES, 168, 168, 168, 0, S("3DES"), S("Three Key Triple DES")},
205 {CALG_SHA, 160, 160, 160, CRYPT_FLAG_SIGNING, S("SHA-1"), S("Secure Hash Algorithm (SHA-1)")},
206 {CALG_MD2, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD2"), S("Message Digest 2 (MD2)")},
207 {CALG_MD4, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD4"), S("Message Digest 4 (MD4)")},
208 {CALG_MD5, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD5"), S("Message Digest 5 (MD5)")},
209 {CALG_SSL3_SHAMD5, 288, 288, 288, 0, S("SSL3 SHAMD5"), S("SSL3 SHAMD5")},
210 {CALG_MAC, 0, 0, 0, 0, S("MAC"), S("Message Authentication Code")},
211 {CALG_RSA_SIGN, 1024, 384, 16384, CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC, S("RSA_SIGN"), S("RSA Signature")},
212 {CALG_RSA_KEYX, 1024, 384, 16384, CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC, S("RSA_KEYX"), S("RSA Key Exchange")},
213 {CALG_HMAC, 0, 0, 0, 0, S("HMAC"), S("Hugo's MAC (HMAC)")},
214 {0, 0, 0, 0, 0, S(""), S("")}
217 {CALG_RC2, 128, 40, 128, RSAENH_PCT1_SSL2_SSL3_TLS1, S("RC2"), S("RSA Data Security's RC2")},
218 {CALG_RC4, 128, 40, 128, RSAENH_PCT1_SSL2_SSL3_TLS1, S("RC4"), S("RSA Data Security's RC4")},
219 {CALG_DES, 56, 56, 56, RSAENH_PCT1_SSL2_SSL3_TLS1, S("DES"), S("Data Encryption Standard (DES)")},
220 {CALG_3DES_112, 112, 112, 112, RSAENH_PCT1_SSL2_SSL3_TLS1, S("3DES TWO KEY"), S("Two Key Triple DES")},
221 {CALG_3DES, 168, 168, 168, RSAENH_PCT1_SSL2_SSL3_TLS1, S("3DES"), S("Three Key Triple DES")},
222 {CALG_SHA, 160, 160, 160, CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1, S("SHA-1"), S("Secure Hash Algorithm (SHA-1)")},
223 {CALG_MD5, 128, 128, 128, CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1, S("MD5"), S("Message Digest 5 (MD5)")},
224 {CALG_SSL3_SHAMD5, 288, 288, 288, 0, S("SSL3 SHAMD5"), S("SSL3 SHAMD5")},
225 {CALG_MAC, 0, 0, 0, 0, S("MAC"), S("Message Authentication Code")},
226 {CALG_RSA_SIGN, 1024, 384, 16384, CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1, S("RSA_SIGN"), S("RSA Signature")},
227 {CALG_RSA_KEYX, 1024, 384, 16384, CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1, S("RSA_KEYX"), S("RSA Key Exchange")},
228 {CALG_HMAC, 0, 0, 0, 0, S("HMAC"), S("Hugo's MAC (HMAC)")},
229 {CALG_PCT1_MASTER, 128, 128, 128, CRYPT_FLAG_PCT1, S("PCT1 MASTER"), S("PCT1 Master")},
230 {CALG_SSL2_MASTER, 40, 40, 192, CRYPT_FLAG_SSL2, S("SSL2 MASTER"), S("SSL2 Master")},
231 {CALG_SSL3_MASTER, 384, 384, 384, CRYPT_FLAG_SSL3, S("SSL3 MASTER"), S("SSL3 Master")},
232 {CALG_TLS1_MASTER, 384, 384, 384, CRYPT_FLAG_TLS1, S("TLS1 MASTER"), S("TLS1 Master")},
233 {CALG_SCHANNEL_MASTER_HASH, 0, 0, -1, 0, S("SCH MASTER HASH"), S("SChannel Master Hash")},
234 {CALG_SCHANNEL_MAC_KEY, 0, 0, -1, 0, S("SCH MAC KEY"), S("SChannel MAC Key")},
235 {CALG_SCHANNEL_ENC_KEY, 0, 0, -1, 0, S("SCH ENC KEY"), S("SChannel Encryption Key")},
236 {CALG_TLS1PRF, 0, 0, -1, 0, S("TLS1 PRF"), S("TLS1 Pseudo Random Function")},
237 {0, 0, 0, 0, 0, S(""), S("")}
240 {CALG_RC2, 128, 40, 128, 0, S("RC2"), S("RSA Data Security's RC2")},
241 {CALG_RC4, 128, 40, 128, 0, S("RC4"), S("RSA Data Security's RC4")},
242 {CALG_DES, 56, 56, 56, 0, S("DES"), S("Data Encryption Standard (DES)")},
243 {CALG_3DES_112, 112, 112, 112, 0, S("3DES TWO KEY"), S("Two Key Triple DES")},
244 {CALG_3DES, 168, 168, 168, 0, S("3DES"), S("Three Key Triple DES")},
245 {CALG_AES_128, 128, 128, 128, 0, S("AES-128"), S("Advanced Encryption Standard (AES-128)")},
246 {CALG_AES_192, 192, 192, 192, 0, S("AES-192"), S("Advanced Encryption Standard (AES-192)")},
247 {CALG_AES_256, 256, 256, 256, 0, S("AES-256"), S("Advanced Encryption Standard (AES-256)")},
248 {CALG_SHA, 160, 160, 160, CRYPT_FLAG_SIGNING, S("SHA-1"), S("Secure Hash Algorithm (SHA-1)")},
249 {CALG_SHA_256, 256, 256, 256, CRYPT_FLAG_SIGNING, S("SHA-256"), S("Secure Hash Algorithm (SHA-256)")},
250 {CALG_SHA_384, 384, 384, 384, CRYPT_FLAG_SIGNING, S("SHA-384"), S("Secure Hash Algorithm (SHA-384)")},
251 {CALG_SHA_512, 512, 512, 512, CRYPT_FLAG_SIGNING, S("SHA-512"), S("Secure Hash Algorithm (SHA-512)")},
252 {CALG_MD2, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD2"), S("Message Digest 2 (MD2)")},
253 {CALG_MD4, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD4"), S("Message Digest 4 (MD4)")},
254 {CALG_MD5, 128, 128, 128, CRYPT_FLAG_SIGNING, S("MD5"), S("Message Digest 5 (MD5)")},
255 {CALG_SSL3_SHAMD5, 288, 288, 288, 0, S("SSL3 SHAMD5"), S("SSL3 SHAMD5")},
256 {CALG_MAC, 0, 0, 0, 0, S("MAC"), S("Message Authentication Code")},
257 {CALG_RSA_SIGN, 1024, 384, 16384, CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC, S("RSA_SIGN"), S("RSA Signature")},
258 {CALG_RSA_KEYX, 1024, 384, 16384, CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC, S("RSA_KEYX"), S("RSA Key Exchange")},
259 {CALG_HMAC, 0, 0, 0, 0, S("HMAC"), S("Hugo's MAC (HMAC)")},
260 {0, 0, 0, 0, 0, S(""), S("")}
263 #undef S
265 /******************************************************************************
266 * API forward declarations
268 BOOL WINAPI
269 RSAENH_CPGetKeyParam(
270 HCRYPTPROV hProv,
271 HCRYPTKEY hKey,
272 DWORD dwParam,
273 BYTE *pbData,
274 DWORD *pdwDataLen,
275 DWORD dwFlags
278 BOOL WINAPI
279 RSAENH_CPEncrypt(
280 HCRYPTPROV hProv,
281 HCRYPTKEY hKey,
282 HCRYPTHASH hHash,
283 BOOL Final,
284 DWORD dwFlags,
285 BYTE *pbData,
286 DWORD *pdwDataLen,
287 DWORD dwBufLen
290 BOOL WINAPI
291 RSAENH_CPCreateHash(
292 HCRYPTPROV hProv,
293 ALG_ID Algid,
294 HCRYPTKEY hKey,
295 DWORD dwFlags,
296 HCRYPTHASH *phHash
299 BOOL WINAPI
300 RSAENH_CPSetHashParam(
301 HCRYPTPROV hProv,
302 HCRYPTHASH hHash,
303 DWORD dwParam,
304 BYTE *pbData, DWORD dwFlags
307 BOOL WINAPI
308 RSAENH_CPGetHashParam(
309 HCRYPTPROV hProv,
310 HCRYPTHASH hHash,
311 DWORD dwParam,
312 BYTE *pbData,
313 DWORD *pdwDataLen,
314 DWORD dwFlags
317 BOOL WINAPI
318 RSAENH_CPDestroyHash(
319 HCRYPTPROV hProv,
320 HCRYPTHASH hHash
323 static BOOL crypt_export_key(
324 CRYPTKEY *pCryptKey,
325 HCRYPTKEY hPubKey,
326 DWORD dwBlobType,
327 DWORD dwFlags,
328 BOOL force,
329 BYTE *pbData,
330 DWORD *pdwDataLen
333 static BOOL import_key(
334 HCRYPTPROV hProv,
335 const BYTE *pbData,
336 DWORD dwDataLen,
337 HCRYPTKEY hPubKey,
338 DWORD dwFlags,
339 BOOL fStoreKey,
340 HCRYPTKEY *phKey
343 BOOL WINAPI
344 RSAENH_CPHashData(
345 HCRYPTPROV hProv,
346 HCRYPTHASH hHash,
347 const BYTE *pbData,
348 DWORD dwDataLen,
349 DWORD dwFlags
352 /******************************************************************************
353 * CSP's handle table (used by all acquired key containers)
355 static struct handle_table handle_table;
357 /******************************************************************************
358 * DllMain (RSAENH.@)
360 * Initializes and destroys the handle table for the CSP's handles.
362 BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD fdwReason, PVOID reserved)
364 switch (fdwReason)
366 case DLL_PROCESS_ATTACH:
367 instance = hInstance;
368 DisableThreadLibraryCalls(hInstance);
369 init_handle_table(&handle_table);
370 break;
372 case DLL_PROCESS_DETACH:
373 if (reserved) break;
374 destroy_handle_table(&handle_table);
375 break;
377 return TRUE;
380 /******************************************************************************
381 * copy_param [Internal]
383 * Helper function that supports the standard WINAPI protocol for querying data
384 * of dynamic size.
386 * PARAMS
387 * pbBuffer [O] Buffer where the queried parameter is copied to, if it is large enough.
388 * May be NUL if the required buffer size is to be queried only.
389 * pdwBufferSize [I/O] In: Size of the buffer at pbBuffer
390 * Out: Size of parameter pbParam
391 * pbParam [I] Parameter value.
392 * dwParamSize [I] Size of pbParam
394 * RETURN
395 * Success: TRUE (pbParam was copied into pbBuffer or pbBuffer is NULL)
396 * Failure: FALSE (pbBuffer is not large enough to hold pbParam). Last error: ERROR_MORE_DATA
398 static inline BOOL copy_param(BYTE *pbBuffer, DWORD *pdwBufferSize, const BYTE *pbParam,
399 DWORD dwParamSize)
401 if (pbBuffer)
403 if (dwParamSize > *pdwBufferSize)
405 SetLastError(ERROR_MORE_DATA);
406 *pdwBufferSize = dwParamSize;
407 return FALSE;
409 memcpy(pbBuffer, pbParam, dwParamSize);
411 *pdwBufferSize = dwParamSize;
412 return TRUE;
415 static inline KEYCONTAINER* get_key_container(HCRYPTPROV hProv)
417 KEYCONTAINER *pKeyContainer;
419 if (!lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER,
420 (OBJECTHDR**)&pKeyContainer))
422 SetLastError(NTE_BAD_UID);
423 return NULL;
425 return pKeyContainer;
428 /******************************************************************************
429 * get_algid_info [Internal]
431 * Query CSP capabilities for a given crypto algorithm.
433 * PARAMS
434 * hProv [I] Handle to a key container of the CSP whose capabilities are to be queried.
435 * algid [I] Identifier of the crypto algorithm about which information is requested.
437 * RETURNS
438 * Success: Pointer to a PROV_ENUMALGS_EX struct containing information about the crypto algorithm.
439 * Failure: NULL (algid not supported)
441 static inline const PROV_ENUMALGS_EX* get_algid_info(HCRYPTPROV hProv, ALG_ID algid) {
442 const PROV_ENUMALGS_EX *iterator;
443 KEYCONTAINER *pKeyContainer;
445 if (!(pKeyContainer = get_key_container(hProv))) return NULL;
447 for (iterator = aProvEnumAlgsEx[pKeyContainer->dwPersonality]; iterator->aiAlgid; iterator++) {
448 if (iterator->aiAlgid == algid) return iterator;
451 SetLastError(NTE_BAD_ALGID);
452 return NULL;
455 /******************************************************************************
456 * copy_data_blob [Internal]
458 * deeply copies a DATA_BLOB
460 * PARAMS
461 * dst [O] That's where the blob will be copied to
462 * src [I] Source blob
464 * RETURNS
465 * Success: TRUE
466 * Failure: FALSE (GetLastError() == NTE_NO_MEMORY
468 * NOTES
469 * Use free_data_blob to release resources occupied by copy_data_blob.
471 static inline BOOL copy_data_blob(PCRYPT_DATA_BLOB dst, const PCRYPT_DATA_BLOB src)
473 dst->pbData = HeapAlloc(GetProcessHeap(), 0, src->cbData);
474 if (!dst->pbData) {
475 SetLastError(NTE_NO_MEMORY);
476 return FALSE;
478 dst->cbData = src->cbData;
479 memcpy(dst->pbData, src->pbData, src->cbData);
480 return TRUE;
483 /******************************************************************************
484 * concat_data_blobs [Internal]
486 * Concatenates two blobs
488 * PARAMS
489 * dst [O] The new blob will be copied here
490 * src1 [I] Prefix blob
491 * src2 [I] Appendix blob
493 * RETURNS
494 * Success: TRUE
495 * Failure: FALSE (GetLastError() == NTE_NO_MEMORY)
497 * NOTES
498 * Release resources occupied by concat_data_blobs with free_data_blobs
500 static inline BOOL concat_data_blobs(PCRYPT_DATA_BLOB dst, const PCRYPT_DATA_BLOB src1,
501 const PCRYPT_DATA_BLOB src2)
503 dst->cbData = src1->cbData + src2->cbData;
504 dst->pbData = HeapAlloc(GetProcessHeap(), 0, dst->cbData);
505 if (!dst->pbData) {
506 SetLastError(NTE_NO_MEMORY);
507 return FALSE;
509 memcpy(dst->pbData, src1->pbData, src1->cbData);
510 memcpy(dst->pbData + src1->cbData, src2->pbData, src2->cbData);
511 return TRUE;
514 /******************************************************************************
515 * free_data_blob [Internal]
517 * releases resource occupied by a dynamically allocated CRYPT_DATA_BLOB
519 * PARAMS
520 * pBlob [I] Heap space occupied by pBlob->pbData is released
522 static inline void free_data_blob(PCRYPT_DATA_BLOB pBlob) {
523 HeapFree(GetProcessHeap(), 0, pBlob->pbData);
526 /******************************************************************************
527 * init_data_blob [Internal]
529 static inline void init_data_blob(PCRYPT_DATA_BLOB pBlob) {
530 pBlob->pbData = NULL;
531 pBlob->cbData = 0;
534 /******************************************************************************
535 * free_hmac_info [Internal]
537 * Deeply free an HMAC_INFO struct.
539 * PARAMS
540 * hmac_info [I] Pointer to the HMAC_INFO struct to be freed.
542 * NOTES
543 * See Internet RFC 2104 for details on the HMAC algorithm.
545 static inline void free_hmac_info(PHMAC_INFO hmac_info) {
546 if (!hmac_info) return;
547 HeapFree(GetProcessHeap(), 0, hmac_info->pbInnerString);
548 HeapFree(GetProcessHeap(), 0, hmac_info->pbOuterString);
549 HeapFree(GetProcessHeap(), 0, hmac_info);
552 /******************************************************************************
553 * copy_hmac_info [Internal]
555 * Deeply copy an HMAC_INFO struct
557 * PARAMS
558 * dst [O] Pointer to a location where the pointer to the HMAC_INFO copy will be stored.
559 * src [I] Pointer to the HMAC_INFO struct to be copied.
561 * RETURNS
562 * Success: TRUE
563 * Failure: FALSE
565 * NOTES
566 * See Internet RFC 2104 for details on the HMAC algorithm.
568 static BOOL copy_hmac_info(PHMAC_INFO *dst, const HMAC_INFO *src) {
569 if (!src) return FALSE;
570 *dst = HeapAlloc(GetProcessHeap(), 0, sizeof(HMAC_INFO));
571 if (!*dst) return FALSE;
572 **dst = *src;
573 (*dst)->pbInnerString = NULL;
574 (*dst)->pbOuterString = NULL;
575 if ((*dst)->cbInnerString == 0) (*dst)->cbInnerString = RSAENH_HMAC_DEF_PAD_LEN;
576 (*dst)->pbInnerString = HeapAlloc(GetProcessHeap(), 0, (*dst)->cbInnerString);
577 if (!(*dst)->pbInnerString) {
578 free_hmac_info(*dst);
579 return FALSE;
581 if (src->cbInnerString)
582 memcpy((*dst)->pbInnerString, src->pbInnerString, src->cbInnerString);
583 else
584 memset((*dst)->pbInnerString, RSAENH_HMAC_DEF_IPAD_CHAR, RSAENH_HMAC_DEF_PAD_LEN);
585 if ((*dst)->cbOuterString == 0) (*dst)->cbOuterString = RSAENH_HMAC_DEF_PAD_LEN;
586 (*dst)->pbOuterString = HeapAlloc(GetProcessHeap(), 0, (*dst)->cbOuterString);
587 if (!(*dst)->pbOuterString) {
588 free_hmac_info(*dst);
589 return FALSE;
591 if (src->cbOuterString)
592 memcpy((*dst)->pbOuterString, src->pbOuterString, src->cbOuterString);
593 else
594 memset((*dst)->pbOuterString, RSAENH_HMAC_DEF_OPAD_CHAR, RSAENH_HMAC_DEF_PAD_LEN);
595 return TRUE;
598 /******************************************************************************
599 * destroy_hash [Internal]
601 * Destructor for hash objects
603 * PARAMS
604 * pCryptHash [I] Pointer to the hash object to be destroyed.
605 * Will be invalid after function returns!
607 static void destroy_hash(OBJECTHDR *pObject)
609 CRYPTHASH *pCryptHash = (CRYPTHASH*)pObject;
611 free_hmac_info(pCryptHash->pHMACInfo);
612 free_data_blob(&pCryptHash->tpPRFParams.blobLabel);
613 free_data_blob(&pCryptHash->tpPRFParams.blobSeed);
614 HeapFree(GetProcessHeap(), 0, pCryptHash);
617 /******************************************************************************
618 * init_hash [Internal]
620 * Initialize (or reset) a hash object
622 * PARAMS
623 * pCryptHash [I] The hash object to be initialized.
625 static inline BOOL init_hash(CRYPTHASH *pCryptHash) {
626 DWORD dwLen;
628 switch (pCryptHash->aiAlgid)
630 case CALG_HMAC:
631 if (pCryptHash->pHMACInfo) {
632 const PROV_ENUMALGS_EX *pAlgInfo;
634 pAlgInfo = get_algid_info(pCryptHash->hProv, pCryptHash->pHMACInfo->HashAlgid);
635 if (!pAlgInfo) return FALSE;
636 pCryptHash->dwHashSize = pAlgInfo->dwDefaultLen >> 3;
637 init_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context);
638 update_hash_impl(&pCryptHash->context,
639 pCryptHash->pHMACInfo->pbInnerString,
640 pCryptHash->pHMACInfo->cbInnerString);
642 return TRUE;
644 case CALG_MAC:
645 dwLen = sizeof(DWORD);
646 RSAENH_CPGetKeyParam(pCryptHash->hProv, pCryptHash->hKey, KP_BLOCKLEN,
647 (BYTE*)&pCryptHash->dwHashSize, &dwLen, 0);
648 pCryptHash->dwHashSize >>= 3;
649 return TRUE;
651 default:
652 return init_hash_impl(pCryptHash->aiAlgid, &pCryptHash->context);
656 /******************************************************************************
657 * update_hash [Internal]
659 * Hashes the given data and updates the hash object's state accordingly
661 * PARAMS
662 * pCryptHash [I] Hash object to be updated.
663 * pbData [I] Pointer to data stream to be hashed.
664 * dwDataLen [I] Length of data stream.
666 static inline void update_hash(CRYPTHASH *pCryptHash, const BYTE *pbData, DWORD dwDataLen)
668 BYTE *pbTemp;
670 switch (pCryptHash->aiAlgid)
672 case CALG_HMAC:
673 if (pCryptHash->pHMACInfo)
674 update_hash_impl(&pCryptHash->context, pbData, dwDataLen);
675 break;
677 case CALG_MAC:
678 pbTemp = HeapAlloc(GetProcessHeap(), 0, dwDataLen);
679 if (!pbTemp) return;
680 memcpy(pbTemp, pbData, dwDataLen);
681 RSAENH_CPEncrypt(pCryptHash->hProv, pCryptHash->hKey, 0, FALSE, 0,
682 pbTemp, &dwDataLen, dwDataLen);
683 HeapFree(GetProcessHeap(), 0, pbTemp);
684 break;
686 default:
687 update_hash_impl(&pCryptHash->context, pbData, dwDataLen);
691 /******************************************************************************
692 * finalize_hash [Internal]
694 * Finalizes the hash, after all data has been hashed with update_hash.
695 * No additional data can be hashed afterwards until the hash gets initialized again.
697 * PARAMS
698 * pCryptHash [I] Hash object to be finalized.
700 static inline void finalize_hash(CRYPTHASH *pCryptHash) {
701 DWORD dwDataLen;
703 switch (pCryptHash->aiAlgid)
705 case CALG_HMAC:
706 if (pCryptHash->pHMACInfo) {
707 BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
709 finalize_hash_impl(&pCryptHash->context, pCryptHash->abHashValue);
710 memcpy(abHashValue, pCryptHash->abHashValue, pCryptHash->dwHashSize);
711 init_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context);
712 update_hash_impl(&pCryptHash->context,
713 pCryptHash->pHMACInfo->pbOuterString,
714 pCryptHash->pHMACInfo->cbOuterString);
715 update_hash_impl(&pCryptHash->context,
716 abHashValue, pCryptHash->dwHashSize);
717 finalize_hash_impl(&pCryptHash->context, pCryptHash->abHashValue);
719 break;
721 case CALG_MAC:
722 dwDataLen = 0;
723 RSAENH_CPEncrypt(pCryptHash->hProv, pCryptHash->hKey, 0, TRUE, 0,
724 pCryptHash->abHashValue, &dwDataLen, pCryptHash->dwHashSize);
725 break;
727 default:
728 finalize_hash_impl(&pCryptHash->context, pCryptHash->abHashValue);
732 /******************************************************************************
733 * destroy_key [Internal]
735 * Destructor for key objects
737 * PARAMS
738 * pCryptKey [I] Pointer to the key object to be destroyed.
739 * Will be invalid after function returns!
741 static void destroy_key(OBJECTHDR *pObject)
743 CRYPTKEY *pCryptKey = (CRYPTKEY*)pObject;
745 free_key_impl(pCryptKey->aiAlgid, &pCryptKey->context);
746 free_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom);
747 free_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom);
748 free_data_blob(&pCryptKey->blobHmacKey);
749 HeapFree(GetProcessHeap(), 0, pCryptKey);
752 /******************************************************************************
753 * setup_key [Internal]
755 * Initialize (or reset) a key object
757 * PARAMS
758 * pCryptKey [I] The key object to be initialized.
760 static inline void setup_key(CRYPTKEY *pCryptKey) {
761 pCryptKey->dwState = RSAENH_KEYSTATE_IDLE;
762 memcpy(pCryptKey->abChainVector, pCryptKey->abInitVector, sizeof(pCryptKey->abChainVector));
763 setup_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen,
764 pCryptKey->dwEffectiveKeyLen, pCryptKey->dwSaltLen,
765 pCryptKey->abKeyValue);
768 /******************************************************************************
769 * new_key [Internal]
771 * Creates a new key object without assigning the actual binary key value.
772 * This is done by CPDeriveKey, CPGenKey or CPImportKey, which call this function.
774 * PARAMS
775 * hProv [I] Handle to the provider to which the created key will belong.
776 * aiAlgid [I] The new key shall use the crypto algorithm identified by aiAlgid.
777 * dwFlags [I] Upper 16 bits give the key length.
778 * Lower 16 bits: CRYPT_EXPORTABLE, CRYPT_CREATE_SALT,
779 * CRYPT_NO_SALT
780 * ppCryptKey [O] Pointer to the created key
782 * RETURNS
783 * Success: Handle to the created key.
784 * Failure: INVALID_HANDLE_VALUE
786 static HCRYPTKEY new_key(HCRYPTPROV hProv, ALG_ID aiAlgid, DWORD dwFlags, CRYPTKEY **ppCryptKey)
788 HCRYPTKEY hCryptKey;
789 CRYPTKEY *pCryptKey;
790 DWORD dwKeyLen = HIWORD(dwFlags);
791 const PROV_ENUMALGS_EX *peaAlgidInfo;
793 *ppCryptKey = NULL;
796 * Retrieve the CSP's capabilities for the given ALG_ID value
798 peaAlgidInfo = get_algid_info(hProv, aiAlgid);
799 if (!peaAlgidInfo) return (HCRYPTKEY)INVALID_HANDLE_VALUE;
801 TRACE("alg = %s, dwKeyLen = %d\n", debugstr_a(peaAlgidInfo->szName),
802 dwKeyLen);
804 * Assume the default key length, if none is specified explicitly
806 if (dwKeyLen == 0) dwKeyLen = peaAlgidInfo->dwDefaultLen;
809 * Check if the requested key length is supported by the current CSP.
810 * Adjust key length's for DES algorithms.
812 switch (aiAlgid) {
813 case CALG_DES:
814 if (dwKeyLen == RSAENH_DES_EFFECTIVE_KEYLEN) {
815 dwKeyLen = RSAENH_DES_STORAGE_KEYLEN;
817 if (dwKeyLen != RSAENH_DES_STORAGE_KEYLEN) {
818 SetLastError(NTE_BAD_FLAGS);
819 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
821 break;
823 case CALG_3DES_112:
824 if (dwKeyLen == RSAENH_3DES112_EFFECTIVE_KEYLEN) {
825 dwKeyLen = RSAENH_3DES112_STORAGE_KEYLEN;
827 if (dwKeyLen != RSAENH_3DES112_STORAGE_KEYLEN) {
828 SetLastError(NTE_BAD_FLAGS);
829 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
831 break;
833 case CALG_3DES:
834 if (dwKeyLen == RSAENH_3DES_EFFECTIVE_KEYLEN) {
835 dwKeyLen = RSAENH_3DES_STORAGE_KEYLEN;
837 if (dwKeyLen != RSAENH_3DES_STORAGE_KEYLEN) {
838 SetLastError(NTE_BAD_FLAGS);
839 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
841 break;
843 case CALG_HMAC:
844 /* Avoid the key length check for HMAC keys, which have unlimited
845 * length.
847 break;
849 default:
850 if (dwKeyLen % 8 ||
851 dwKeyLen > peaAlgidInfo->dwMaxLen ||
852 dwKeyLen < peaAlgidInfo->dwMinLen)
854 TRACE("key len %d out of bounds (%d, %d)\n", dwKeyLen,
855 peaAlgidInfo->dwMinLen, peaAlgidInfo->dwMaxLen);
856 SetLastError(NTE_BAD_DATA);
857 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
861 hCryptKey = new_object(&handle_table, sizeof(CRYPTKEY), RSAENH_MAGIC_KEY,
862 destroy_key, (OBJECTHDR**)&pCryptKey);
863 if (hCryptKey != (HCRYPTKEY)INVALID_HANDLE_VALUE)
865 KEYCONTAINER *pKeyContainer = get_key_container(hProv);
866 pCryptKey->aiAlgid = aiAlgid;
867 pCryptKey->hProv = hProv;
868 pCryptKey->dwModeBits = 0;
869 pCryptKey->dwPermissions = CRYPT_ENCRYPT | CRYPT_DECRYPT | CRYPT_READ | CRYPT_WRITE |
870 CRYPT_MAC;
871 if (dwFlags & CRYPT_EXPORTABLE)
872 pCryptKey->dwPermissions |= CRYPT_EXPORT;
873 pCryptKey->dwKeyLen = dwKeyLen >> 3;
874 pCryptKey->dwEffectiveKeyLen = 0;
877 * For compatibility reasons a 40 bit key on the Enhanced
878 * provider will not have salt
880 if (pKeyContainer->dwPersonality == RSAENH_PERSONALITY_ENHANCED
881 && (aiAlgid == CALG_RC2 || aiAlgid == CALG_RC4)
882 && (dwFlags & CRYPT_CREATE_SALT) && dwKeyLen == 40)
883 pCryptKey->dwSaltLen = 0;
884 else if ((dwFlags & CRYPT_CREATE_SALT) || (dwKeyLen == 40 && !(dwFlags & CRYPT_NO_SALT)))
885 pCryptKey->dwSaltLen = 16 /*FIXME*/ - pCryptKey->dwKeyLen;
886 else
887 pCryptKey->dwSaltLen = 0;
888 memset(pCryptKey->abKeyValue, 0, sizeof(pCryptKey->abKeyValue));
889 memset(pCryptKey->abInitVector, 0, sizeof(pCryptKey->abInitVector));
890 memset(&pCryptKey->siSChannelInfo.saEncAlg, 0, sizeof(pCryptKey->siSChannelInfo.saEncAlg));
891 memset(&pCryptKey->siSChannelInfo.saMACAlg, 0, sizeof(pCryptKey->siSChannelInfo.saMACAlg));
892 init_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom);
893 init_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom);
894 init_data_blob(&pCryptKey->blobHmacKey);
896 switch(aiAlgid)
898 case CALG_PCT1_MASTER:
899 case CALG_SSL2_MASTER:
900 case CALG_SSL3_MASTER:
901 case CALG_TLS1_MASTER:
902 case CALG_RC4:
903 pCryptKey->dwBlockLen = 0;
904 pCryptKey->dwMode = 0;
905 break;
907 case CALG_RC2:
908 case CALG_DES:
909 case CALG_3DES_112:
910 case CALG_3DES:
911 pCryptKey->dwBlockLen = 8;
912 pCryptKey->dwMode = CRYPT_MODE_CBC;
913 break;
915 case CALG_AES_128:
916 case CALG_AES_192:
917 case CALG_AES_256:
918 pCryptKey->dwBlockLen = 16;
919 pCryptKey->dwMode = CRYPT_MODE_CBC;
920 break;
922 case CALG_RSA_KEYX:
923 case CALG_RSA_SIGN:
924 pCryptKey->dwBlockLen = dwKeyLen >> 3;
925 pCryptKey->dwMode = 0;
926 break;
928 case CALG_HMAC:
929 pCryptKey->dwBlockLen = 0;
930 pCryptKey->dwMode = 0;
931 break;
934 *ppCryptKey = pCryptKey;
937 return hCryptKey;
940 /******************************************************************************
941 * map_key_spec_to_key_pair_name [Internal]
943 * Returns the name of the registry value associated with a key spec.
945 * PARAMS
946 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
948 * RETURNS
949 * Success: Name of registry value.
950 * Failure: NULL
952 static LPCSTR map_key_spec_to_key_pair_name(DWORD dwKeySpec)
954 LPCSTR szValueName;
956 switch (dwKeySpec)
958 case AT_KEYEXCHANGE:
959 szValueName = "KeyExchangeKeyPair";
960 break;
961 case AT_SIGNATURE:
962 szValueName = "SignatureKeyPair";
963 break;
964 default:
965 WARN("invalid key spec %d\n", dwKeySpec);
966 szValueName = NULL;
968 return szValueName;
971 /******************************************************************************
972 * store_key_pair [Internal]
974 * Stores a key pair to the registry
976 * PARAMS
977 * hCryptKey [I] Handle to the key to be stored
978 * hKey [I] Registry key where the key pair is to be stored
979 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
980 * dwFlags [I] Flags for protecting the key
982 static void store_key_pair(HCRYPTKEY hCryptKey, HKEY hKey, DWORD dwKeySpec, DWORD dwFlags)
984 LPCSTR szValueName;
985 DATA_BLOB blobIn, blobOut;
986 CRYPTKEY *pKey;
987 DWORD dwLen;
988 BYTE *pbKey;
990 if (!(szValueName = map_key_spec_to_key_pair_name(dwKeySpec)))
991 return;
992 if (lookup_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY,
993 (OBJECTHDR**)&pKey))
995 if (crypt_export_key(pKey, 0, PRIVATEKEYBLOB, 0, TRUE, 0, &dwLen))
997 pbKey = HeapAlloc(GetProcessHeap(), 0, dwLen);
998 if (pbKey)
1000 if (crypt_export_key(pKey, 0, PRIVATEKEYBLOB, 0, TRUE, pbKey,
1001 &dwLen))
1003 blobIn.pbData = pbKey;
1004 blobIn.cbData = dwLen;
1006 if (CryptProtectData(&blobIn, NULL, NULL, NULL, NULL,
1007 dwFlags, &blobOut))
1009 RegSetValueExA(hKey, szValueName, 0, REG_BINARY,
1010 blobOut.pbData, blobOut.cbData);
1011 LocalFree(blobOut.pbData);
1014 HeapFree(GetProcessHeap(), 0, pbKey);
1020 /******************************************************************************
1021 * map_key_spec_to_permissions_name [Internal]
1023 * Returns the name of the registry value associated with the permissions for
1024 * a key spec.
1026 * PARAMS
1027 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
1029 * RETURNS
1030 * Success: Name of registry value.
1031 * Failure: NULL
1033 static LPCSTR map_key_spec_to_permissions_name(DWORD dwKeySpec)
1035 LPCSTR szValueName;
1037 switch (dwKeySpec)
1039 case AT_KEYEXCHANGE:
1040 szValueName = "KeyExchangePermissions";
1041 break;
1042 case AT_SIGNATURE:
1043 szValueName = "SignaturePermissions";
1044 break;
1045 default:
1046 WARN("invalid key spec %d\n", dwKeySpec);
1047 szValueName = NULL;
1049 return szValueName;
1052 /******************************************************************************
1053 * store_key_permissions [Internal]
1055 * Stores a key's permissions to the registry
1057 * PARAMS
1058 * hCryptKey [I] Handle to the key whose permissions are to be stored
1059 * hKey [I] Registry key where the key permissions are to be stored
1060 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
1062 static void store_key_permissions(HCRYPTKEY hCryptKey, HKEY hKey, DWORD dwKeySpec)
1064 LPCSTR szValueName;
1065 CRYPTKEY *pKey;
1067 if (!(szValueName = map_key_spec_to_permissions_name(dwKeySpec)))
1068 return;
1069 if (lookup_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY,
1070 (OBJECTHDR**)&pKey))
1071 RegSetValueExA(hKey, szValueName, 0, REG_DWORD,
1072 (BYTE *)&pKey->dwPermissions,
1073 sizeof(pKey->dwPermissions));
1076 /******************************************************************************
1077 * create_container_key [Internal]
1079 * Creates the registry key for a key container's persistent storage.
1081 * PARAMS
1082 * pKeyContainer [I] Pointer to the key container
1083 * sam [I] Desired registry access
1084 * phKey [O] Returned key
1086 static BOOL create_container_key(KEYCONTAINER *pKeyContainer, REGSAM sam, HKEY *phKey)
1088 CHAR szRSABase[sizeof(RSAENH_REGKEY) + MAX_PATH];
1089 HKEY hRootKey;
1091 sprintf(szRSABase, RSAENH_REGKEY, pKeyContainer->szName);
1093 if (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET)
1094 hRootKey = HKEY_LOCAL_MACHINE;
1095 else
1096 hRootKey = HKEY_CURRENT_USER;
1098 /* @@ Wine registry key: HKLM\Software\Wine\Crypto\RSA */
1099 /* @@ Wine registry key: HKCU\Software\Wine\Crypto\RSA */
1100 return RegCreateKeyExA(hRootKey, szRSABase, 0, NULL,
1101 REG_OPTION_NON_VOLATILE, sam, NULL, phKey, NULL)
1102 == ERROR_SUCCESS;
1105 /******************************************************************************
1106 * open_container_key [Internal]
1108 * Opens a key container's persistent storage for reading.
1110 * PARAMS
1111 * pszContainerName [I] Name of the container to be opened. May be the empty
1112 * string if the parent key of all containers is to be
1113 * opened.
1114 * dwFlags [I] Flags indicating which keyset to be opened.
1115 * phKey [O] Returned key
1117 static BOOL open_container_key(LPCSTR pszContainerName, DWORD dwFlags, REGSAM access, HKEY *phKey)
1119 CHAR szRSABase[sizeof(RSAENH_REGKEY) + MAX_PATH];
1120 HKEY hRootKey;
1122 sprintf(szRSABase, RSAENH_REGKEY, pszContainerName);
1124 if (dwFlags & CRYPT_MACHINE_KEYSET)
1125 hRootKey = HKEY_LOCAL_MACHINE;
1126 else
1127 hRootKey = HKEY_CURRENT_USER;
1129 /* @@ Wine registry key: HKLM\Software\Wine\Crypto\RSA */
1130 /* @@ Wine registry key: HKCU\Software\Wine\Crypto\RSA */
1131 return RegOpenKeyExA(hRootKey, szRSABase, 0, access, phKey) ==
1132 ERROR_SUCCESS;
1135 /******************************************************************************
1136 * delete_container_key [Internal]
1138 * Deletes a key container's persistent storage.
1140 * PARAMS
1141 * pszContainerName [I] Name of the container to be opened.
1142 * dwFlags [I] Flags indicating which keyset to be opened.
1144 static BOOL delete_container_key(LPCSTR pszContainerName, DWORD dwFlags)
1146 CHAR szRegKey[sizeof(RSAENH_REGKEY) + MAX_PATH];
1147 HKEY hRootKey;
1149 sprintf(szRegKey, RSAENH_REGKEY, pszContainerName);
1151 if (dwFlags & CRYPT_MACHINE_KEYSET)
1152 hRootKey = HKEY_LOCAL_MACHINE;
1153 else
1154 hRootKey = HKEY_CURRENT_USER;
1155 if (!RegDeleteKeyA(hRootKey, szRegKey)) {
1156 SetLastError(ERROR_SUCCESS);
1157 return TRUE;
1158 } else {
1159 SetLastError(NTE_BAD_KEYSET);
1160 return FALSE;
1164 /******************************************************************************
1165 * store_key_container_keys [Internal]
1167 * Stores key container's keys in a persistent location.
1169 * PARAMS
1170 * pKeyContainer [I] Pointer to the key container whose keys are to be saved
1172 static void store_key_container_keys(KEYCONTAINER *pKeyContainer)
1174 HKEY hKey;
1175 DWORD dwFlags;
1177 /* On WinXP, persistent keys are stored in a file located at:
1178 * $AppData$\\Microsoft\\Crypto\\RSA\\$SID$\\some_hex_string
1181 if (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET)
1182 dwFlags = CRYPTPROTECT_LOCAL_MACHINE;
1183 else
1184 dwFlags = 0;
1186 if (create_container_key(pKeyContainer, KEY_WRITE, &hKey))
1188 store_key_pair(pKeyContainer->hKeyExchangeKeyPair, hKey,
1189 AT_KEYEXCHANGE, dwFlags);
1190 store_key_pair(pKeyContainer->hSignatureKeyPair, hKey,
1191 AT_SIGNATURE, dwFlags);
1192 RegCloseKey(hKey);
1196 /******************************************************************************
1197 * store_key_container_permissions [Internal]
1199 * Stores key container's key permissions in a persistent location.
1201 * PARAMS
1202 * pKeyContainer [I] Pointer to the key container whose key permissions are to
1203 * be saved
1205 static void store_key_container_permissions(KEYCONTAINER *pKeyContainer)
1207 HKEY hKey;
1209 if (create_container_key(pKeyContainer, KEY_WRITE, &hKey))
1211 store_key_permissions(pKeyContainer->hKeyExchangeKeyPair, hKey,
1212 AT_KEYEXCHANGE);
1213 store_key_permissions(pKeyContainer->hSignatureKeyPair, hKey,
1214 AT_SIGNATURE);
1215 RegCloseKey(hKey);
1219 /******************************************************************************
1220 * release_key_container_keys [Internal]
1222 * Releases key container's keys.
1224 * PARAMS
1225 * pKeyContainer [I] Pointer to the key container whose keys are to be released.
1227 static void release_key_container_keys(KEYCONTAINER *pKeyContainer)
1229 release_handle(&handle_table, pKeyContainer->hKeyExchangeKeyPair,
1230 RSAENH_MAGIC_KEY);
1231 release_handle(&handle_table, pKeyContainer->hSignatureKeyPair,
1232 RSAENH_MAGIC_KEY);
1235 /******************************************************************************
1236 * destroy_key_container [Internal]
1238 * Destructor for key containers.
1240 * PARAMS
1241 * pObjectHdr [I] Pointer to the key container to be destroyed.
1243 static void destroy_key_container(OBJECTHDR *pObjectHdr)
1245 KEYCONTAINER *pKeyContainer = (KEYCONTAINER*)pObjectHdr;
1247 if (!(pKeyContainer->dwFlags & CRYPT_VERIFYCONTEXT))
1249 store_key_container_keys(pKeyContainer);
1250 store_key_container_permissions(pKeyContainer);
1251 release_key_container_keys(pKeyContainer);
1253 else
1254 release_key_container_keys(pKeyContainer);
1255 HeapFree( GetProcessHeap(), 0, pKeyContainer );
1258 /******************************************************************************
1259 * new_key_container [Internal]
1261 * Create a new key container. The personality (RSA Base, Strong or Enhanced CP)
1262 * of the CSP is determined via the pVTable->pszProvName string.
1264 * PARAMS
1265 * pszContainerName [I] Name of the key container.
1266 * pVTable [I] Callback functions and context info provided by the OS
1268 * RETURNS
1269 * Success: Handle to the new key container.
1270 * Failure: INVALID_HANDLE_VALUE
1272 static HCRYPTPROV new_key_container(PCCH pszContainerName, DWORD dwFlags, const VTableProvStruc *pVTable)
1274 KEYCONTAINER *pKeyContainer;
1275 HCRYPTPROV hKeyContainer;
1277 hKeyContainer = new_object(&handle_table, sizeof(KEYCONTAINER), RSAENH_MAGIC_CONTAINER,
1278 destroy_key_container, (OBJECTHDR**)&pKeyContainer);
1279 if (hKeyContainer != (HCRYPTPROV)INVALID_HANDLE_VALUE)
1281 lstrcpynA(pKeyContainer->szName, pszContainerName, MAX_PATH);
1282 pKeyContainer->dwFlags = dwFlags;
1283 pKeyContainer->dwEnumAlgsCtr = 0;
1284 pKeyContainer->hKeyExchangeKeyPair = (HCRYPTKEY)INVALID_HANDLE_VALUE;
1285 pKeyContainer->hSignatureKeyPair = (HCRYPTKEY)INVALID_HANDLE_VALUE;
1286 if (pVTable && pVTable->pszProvName) {
1287 lstrcpynA(pKeyContainer->szProvName, pVTable->pszProvName, MAX_PATH);
1288 if (!strcmp(pVTable->pszProvName, MS_DEF_PROV_A)) {
1289 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_BASE;
1290 } else if (!strcmp(pVTable->pszProvName, MS_ENHANCED_PROV_A)) {
1291 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_ENHANCED;
1292 } else if (!strcmp(pVTable->pszProvName, MS_DEF_RSA_SCHANNEL_PROV_A)) {
1293 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_SCHANNEL;
1294 } else if (!strcmp(pVTable->pszProvName, MS_ENH_RSA_AES_PROV_A) ||
1295 !strcmp(pVTable->pszProvName, MS_ENH_RSA_AES_PROV_XP_A)) {
1296 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_AES;
1297 } else {
1298 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_STRONG;
1302 /* The new key container has to be inserted into the CSP immediately
1303 * after creation to be available for CPGetProvParam's PP_ENUMCONTAINERS. */
1304 if (!(dwFlags & CRYPT_VERIFYCONTEXT)) {
1305 HKEY hKey;
1307 if (create_container_key(pKeyContainer, KEY_WRITE, &hKey))
1308 RegCloseKey(hKey);
1312 return hKeyContainer;
1315 /******************************************************************************
1316 * read_key_value [Internal]
1318 * Reads a key pair value from the registry
1320 * PARAMS
1321 * hKeyContainer [I] Crypt provider to use to import the key
1322 * hKey [I] Registry key from which to read the key pair
1323 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
1324 * dwFlags [I] Flags for unprotecting the key
1325 * phCryptKey [O] Returned key
1327 static BOOL read_key_value(HCRYPTPROV hKeyContainer, HKEY hKey, DWORD dwKeySpec, DWORD dwFlags, HCRYPTKEY *phCryptKey)
1329 LPCSTR szValueName;
1330 DWORD dwValueType, dwLen;
1331 BYTE *pbKey;
1332 DATA_BLOB blobIn, blobOut;
1333 BOOL ret = FALSE;
1335 if (!(szValueName = map_key_spec_to_key_pair_name(dwKeySpec)))
1336 return FALSE;
1337 if (RegQueryValueExA(hKey, szValueName, 0, &dwValueType, NULL, &dwLen) ==
1338 ERROR_SUCCESS)
1340 pbKey = HeapAlloc(GetProcessHeap(), 0, dwLen);
1341 if (pbKey)
1343 if (RegQueryValueExA(hKey, szValueName, 0, &dwValueType, pbKey, &dwLen) ==
1344 ERROR_SUCCESS)
1346 blobIn.pbData = pbKey;
1347 blobIn.cbData = dwLen;
1349 if (CryptUnprotectData(&blobIn, NULL, NULL, NULL, NULL,
1350 dwFlags, &blobOut))
1352 ret = import_key(hKeyContainer, blobOut.pbData, blobOut.cbData, 0, 0,
1353 FALSE, phCryptKey);
1354 LocalFree(blobOut.pbData);
1357 HeapFree(GetProcessHeap(), 0, pbKey);
1360 if (ret)
1362 CRYPTKEY *pKey;
1364 if (lookup_handle(&handle_table, *phCryptKey, RSAENH_MAGIC_KEY,
1365 (OBJECTHDR**)&pKey))
1367 if ((szValueName = map_key_spec_to_permissions_name(dwKeySpec)))
1369 dwLen = sizeof(pKey->dwPermissions);
1370 RegQueryValueExA(hKey, szValueName, 0, NULL,
1371 (BYTE *)&pKey->dwPermissions, &dwLen);
1375 return ret;
1378 /******************************************************************************
1379 * read_key_container [Internal]
1381 * Tries to read the persistent state of the key container (mainly the signature
1382 * and key exchange private keys) given by pszContainerName.
1384 * PARAMS
1385 * pszContainerName [I] Name of the key container to read from the registry
1386 * pVTable [I] Pointer to context data provided by the operating system
1388 * RETURNS
1389 * Success: Handle to the key container read from the registry
1390 * Failure: INVALID_HANDLE_VALUE
1392 static HCRYPTPROV read_key_container(PCHAR pszContainerName, DWORD dwFlags, const VTableProvStruc *pVTable)
1394 HKEY hKey;
1395 KEYCONTAINER *pKeyContainer;
1396 HCRYPTPROV hKeyContainer;
1397 HCRYPTKEY hCryptKey;
1399 if (!open_container_key(pszContainerName, dwFlags, KEY_READ, &hKey))
1401 SetLastError(NTE_BAD_KEYSET);
1402 return (HCRYPTPROV)INVALID_HANDLE_VALUE;
1405 hKeyContainer = new_key_container(pszContainerName, dwFlags, pVTable);
1406 if (hKeyContainer != (HCRYPTPROV)INVALID_HANDLE_VALUE)
1408 DWORD dwProtectFlags = (dwFlags & CRYPT_MACHINE_KEYSET) ?
1409 CRYPTPROTECT_LOCAL_MACHINE : 0;
1411 if (!lookup_handle(&handle_table, hKeyContainer, RSAENH_MAGIC_CONTAINER,
1412 (OBJECTHDR**)&pKeyContainer))
1413 return (HCRYPTPROV)INVALID_HANDLE_VALUE;
1415 /* read_key_value calls import_key, which calls import_private_key,
1416 * which implicitly installs the key value into the appropriate key
1417 * container key. Thus the ref count is incremented twice, once for
1418 * the output key value, and once for the implicit install, and needs
1419 * to be decremented to balance the two.
1421 if (read_key_value(hKeyContainer, hKey, AT_KEYEXCHANGE,
1422 dwProtectFlags, &hCryptKey))
1423 release_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY);
1424 if (read_key_value(hKeyContainer, hKey, AT_SIGNATURE,
1425 dwProtectFlags, &hCryptKey))
1426 release_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY);
1429 return hKeyContainer;
1432 /******************************************************************************
1433 * build_hash_signature [Internal]
1435 * Builds a padded version of a hash to match the length of the RSA key modulus.
1437 * PARAMS
1438 * pbSignature [O] The padded hash object is stored here.
1439 * dwLen [I] Length of the pbSignature buffer.
1440 * aiAlgid [I] Algorithm identifier of the hash to be padded.
1441 * abHashValue [I] The value of the hash object.
1442 * dwHashLen [I] Length of the hash value.
1443 * dwFlags [I] Selection of padding algorithm.
1445 * RETURNS
1446 * Success: TRUE
1447 * Failure: FALSE (NTE_BAD_ALGID)
1449 static BOOL build_hash_signature(BYTE *pbSignature, DWORD dwLen, ALG_ID aiAlgid,
1450 const BYTE *abHashValue, DWORD dwHashLen, DWORD dwFlags)
1452 /* These prefixes are meant to be concatenated with hash values of the
1453 * respective kind to form a PKCS #7 DigestInfo. */
1454 static const struct tagOIDDescriptor {
1455 ALG_ID aiAlgid;
1456 DWORD dwLen;
1457 const BYTE abOID[19];
1458 } aOIDDescriptor[] = {
1459 { CALG_MD2, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48,
1460 0x86, 0xf7, 0x0d, 0x02, 0x02, 0x05, 0x00, 0x04, 0x10 } },
1461 { CALG_MD4, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48,
1462 0x86, 0xf7, 0x0d, 0x02, 0x04, 0x05, 0x00, 0x04, 0x10 } },
1463 { CALG_MD5, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48,
1464 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10 } },
1465 { CALG_SHA, 15, { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
1466 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 } },
1467 { CALG_SHA_256, 19, { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
1468 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01,
1469 0x05, 0x00, 0x04, 0x20 } },
1470 { CALG_SHA_384, 19, { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
1471 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02,
1472 0x05, 0x00, 0x04, 0x30 } },
1473 { CALG_SHA_512, 19, { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
1474 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03,
1475 0x05, 0x00, 0x04, 0x40 } },
1476 { CALG_SSL3_SHAMD5, 0, { 0 } },
1477 { 0, 0, { 0 } }
1479 DWORD dwIdxOID, i, j;
1481 for (dwIdxOID = 0; aOIDDescriptor[dwIdxOID].aiAlgid; dwIdxOID++) {
1482 if (aOIDDescriptor[dwIdxOID].aiAlgid == aiAlgid) break;
1485 if (!aOIDDescriptor[dwIdxOID].aiAlgid) {
1486 SetLastError(NTE_BAD_ALGID);
1487 return FALSE;
1490 /* Build the padded signature */
1491 if (dwFlags & CRYPT_X931_FORMAT) {
1492 pbSignature[0] = 0x6b;
1493 for (i=1; i < dwLen - dwHashLen - 3; i++) {
1494 pbSignature[i] = 0xbb;
1496 pbSignature[i++] = 0xba;
1497 for (j=0; j < dwHashLen; j++, i++) {
1498 pbSignature[i] = abHashValue[j];
1500 pbSignature[i++] = 0x33;
1501 pbSignature[i++] = 0xcc;
1502 } else {
1503 pbSignature[0] = 0x00;
1504 pbSignature[1] = 0x01;
1505 if (dwFlags & CRYPT_NOHASHOID) {
1506 for (i=2; i < dwLen - 1 - dwHashLen; i++) {
1507 pbSignature[i] = 0xff;
1509 pbSignature[i++] = 0x00;
1510 } else {
1511 for (i=2; i < dwLen - 1 - aOIDDescriptor[dwIdxOID].dwLen - dwHashLen; i++) {
1512 pbSignature[i] = 0xff;
1514 pbSignature[i++] = 0x00;
1515 for (j=0; j < aOIDDescriptor[dwIdxOID].dwLen; j++) {
1516 pbSignature[i++] = aOIDDescriptor[dwIdxOID].abOID[j];
1519 for (j=0; j < dwHashLen; j++) {
1520 pbSignature[i++] = abHashValue[j];
1524 return TRUE;
1527 /******************************************************************************
1528 * tls1_p [Internal]
1530 * This is an implementation of the 'P_hash' helper function for TLS1's PRF.
1531 * It is used exclusively by tls1_prf. For details see RFC 2246, chapter 5.
1532 * The pseudo random stream generated by this function is exclusive or'ed with
1533 * the data in pbBuffer.
1535 * PARAMS
1536 * hHMAC [I] HMAC object, which will be used in pseudo random generation
1537 * pblobSeed [I] Seed value
1538 * pbBuffer [I/O] Pseudo random stream will be xor'ed to the provided data
1539 * dwBufferLen [I] Number of pseudo random bytes desired
1541 * RETURNS
1542 * Success: TRUE
1543 * Failure: FALSE
1545 static BOOL tls1_p(HCRYPTHASH hHMAC, const PCRYPT_DATA_BLOB pblobSeed, BYTE *pbBuffer,
1546 DWORD dwBufferLen)
1548 CRYPTHASH *pHMAC;
1549 BYTE abAi[RSAENH_MAX_HASH_SIZE];
1550 DWORD i = 0;
1552 if (!lookup_handle(&handle_table, hHMAC, RSAENH_MAGIC_HASH, (OBJECTHDR**)&pHMAC)) {
1553 SetLastError(NTE_BAD_HASH);
1554 return FALSE;
1557 /* compute A_1 = HMAC(seed) */
1558 init_hash(pHMAC);
1559 update_hash(pHMAC, pblobSeed->pbData, pblobSeed->cbData);
1560 finalize_hash(pHMAC);
1561 memcpy(abAi, pHMAC->abHashValue, pHMAC->dwHashSize);
1563 do {
1564 /* compute HMAC(A_i + seed) */
1565 init_hash(pHMAC);
1566 update_hash(pHMAC, abAi, pHMAC->dwHashSize);
1567 update_hash(pHMAC, pblobSeed->pbData, pblobSeed->cbData);
1568 finalize_hash(pHMAC);
1570 /* pseudo random stream := CONCAT_{i=1..n} ( HMAC(A_i + seed) ) */
1571 do {
1572 if (i >= dwBufferLen) break;
1573 pbBuffer[i] ^= pHMAC->abHashValue[i % pHMAC->dwHashSize];
1574 i++;
1575 } while (i % pHMAC->dwHashSize);
1577 /* compute A_{i+1} = HMAC(A_i) */
1578 init_hash(pHMAC);
1579 update_hash(pHMAC, abAi, pHMAC->dwHashSize);
1580 finalize_hash(pHMAC);
1581 memcpy(abAi, pHMAC->abHashValue, pHMAC->dwHashSize);
1582 } while (i < dwBufferLen);
1584 return TRUE;
1587 /******************************************************************************
1588 * tls1_prf [Internal]
1590 * TLS1 pseudo random function as specified in RFC 2246, chapter 5
1592 * PARAMS
1593 * hProv [I] Key container used to compute the pseudo random stream
1594 * hSecret [I] Key that holds the (pre-)master secret
1595 * pblobLabel [I] Descriptive label
1596 * pblobSeed [I] Seed value
1597 * pbBuffer [O] Pseudo random numbers will be stored here
1598 * dwBufferLen [I] Number of pseudo random bytes desired
1600 * RETURNS
1601 * Success: TRUE
1602 * Failure: FALSE
1604 static BOOL tls1_prf(HCRYPTPROV hProv, HCRYPTPROV hSecret, const PCRYPT_DATA_BLOB pblobLabel,
1605 const PCRYPT_DATA_BLOB pblobSeed, BYTE *pbBuffer, DWORD dwBufferLen)
1607 HMAC_INFO hmacInfo = { 0, NULL, 0, NULL, 0 };
1608 HCRYPTHASH hHMAC = (HCRYPTHASH)INVALID_HANDLE_VALUE;
1609 HCRYPTKEY hHalfSecret = (HCRYPTKEY)INVALID_HANDLE_VALUE;
1610 CRYPTKEY *pHalfSecret, *pSecret;
1611 DWORD dwHalfSecretLen;
1612 BOOL result = FALSE;
1613 CRYPT_DATA_BLOB blobLabelSeed;
1615 TRACE("(hProv=%08lx, hSecret=%08lx, pblobLabel=%p, pblobSeed=%p, pbBuffer=%p, dwBufferLen=%d)\n",
1616 hProv, hSecret, pblobLabel, pblobSeed, pbBuffer, dwBufferLen);
1618 if (!lookup_handle(&handle_table, hSecret, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pSecret)) {
1619 SetLastError(NTE_FAIL);
1620 return FALSE;
1623 dwHalfSecretLen = (pSecret->dwKeyLen+1)/2;
1625 /* concatenation of the label and the seed */
1626 if (!concat_data_blobs(&blobLabelSeed, pblobLabel, pblobSeed)) goto exit;
1628 /* zero out the buffer, since two random streams will be xor'ed into it. */
1629 memset(pbBuffer, 0, dwBufferLen);
1631 /* build a 'fake' key, to hold the secret. CALG_SSL2_MASTER is used since it provides
1632 * the biggest range of valid key lengths. */
1633 hHalfSecret = new_key(hProv, CALG_SSL2_MASTER, MAKELONG(0,dwHalfSecretLen*8), &pHalfSecret);
1634 if (hHalfSecret == (HCRYPTKEY)INVALID_HANDLE_VALUE) goto exit;
1636 /* Derive an HMAC_MD5 hash and call the helper function. */
1637 memcpy(pHalfSecret->abKeyValue, pSecret->abKeyValue, dwHalfSecretLen);
1638 if (!RSAENH_CPCreateHash(hProv, CALG_HMAC, hHalfSecret, 0, &hHMAC)) goto exit;
1639 hmacInfo.HashAlgid = CALG_MD5;
1640 if (!RSAENH_CPSetHashParam(hProv, hHMAC, HP_HMAC_INFO, (BYTE*)&hmacInfo, 0)) goto exit;
1641 if (!tls1_p(hHMAC, &blobLabelSeed, pbBuffer, dwBufferLen)) goto exit;
1643 /* Reconfigure to HMAC_SHA hash and call helper function again. */
1644 memcpy(pHalfSecret->abKeyValue, pSecret->abKeyValue + (pSecret->dwKeyLen/2), dwHalfSecretLen);
1645 hmacInfo.HashAlgid = CALG_SHA;
1646 if (!RSAENH_CPSetHashParam(hProv, hHMAC, HP_HMAC_INFO, (BYTE*)&hmacInfo, 0)) goto exit;
1647 if (!tls1_p(hHMAC, &blobLabelSeed, pbBuffer, dwBufferLen)) goto exit;
1649 result = TRUE;
1650 exit:
1651 release_handle(&handle_table, hHalfSecret, RSAENH_MAGIC_KEY);
1652 if (hHMAC != (HCRYPTHASH)INVALID_HANDLE_VALUE) RSAENH_CPDestroyHash(hProv, hHMAC);
1653 free_data_blob(&blobLabelSeed);
1654 return result;
1657 /******************************************************************************
1658 * pad_data [Internal]
1660 * Helper function for data padding according to PKCS1 #2
1662 * PARAMS
1663 * abData [I] The data to be padded
1664 * dwDataLen [I] Length of the data
1665 * abBuffer [O] Padded data will be stored here
1666 * dwBufferLen [I] Length of the buffer (also length of padded data)
1667 * dwFlags [I] Padding format (CRYPT_SSL2_FALLBACK)
1669 * RETURN
1670 * Success: TRUE
1671 * Failure: FALSE (NTE_BAD_LEN, too much data to pad)
1673 static BOOL pad_data(const BYTE *abData, DWORD dwDataLen, BYTE *abBuffer, DWORD dwBufferLen,
1674 DWORD dwFlags)
1676 DWORD i;
1678 /* Ensure there is enough space for PKCS1 #2 padding */
1679 if (dwDataLen > dwBufferLen-11) {
1680 SetLastError(NTE_BAD_LEN);
1681 return FALSE;
1684 memmove(abBuffer + dwBufferLen - dwDataLen, abData, dwDataLen);
1686 abBuffer[0] = 0x00;
1687 abBuffer[1] = RSAENH_PKC_BLOCKTYPE;
1688 for (i=2; i < dwBufferLen - dwDataLen - 1; i++)
1689 do gen_rand_impl(&abBuffer[i], 1); while (!abBuffer[i]);
1690 if (dwFlags & CRYPT_SSL2_FALLBACK)
1691 for (i-=8; i < dwBufferLen - dwDataLen - 1; i++)
1692 abBuffer[i] = 0x03;
1693 abBuffer[i] = 0x00;
1695 return TRUE;
1698 /******************************************************************************
1699 * unpad_data [Internal]
1701 * Remove the PKCS1 padding from RSA decrypted data
1703 * PARAMS
1704 * abData [I] The padded data
1705 * dwDataLen [I] Length of the padded data
1706 * abBuffer [O] Data without padding will be stored here
1707 * dwBufferLen [I/O] I: Length of the buffer, O: Length of unpadded data
1708 * dwFlags [I] Currently none defined
1710 * RETURNS
1711 * Success: TRUE
1712 * Failure: FALSE, (NTE_BAD_DATA, no valid PKCS1 padding or buffer too small)
1714 static BOOL unpad_data(const BYTE *abData, DWORD dwDataLen, BYTE *abBuffer, DWORD *dwBufferLen,
1715 DWORD dwFlags)
1717 DWORD i;
1719 if (dwDataLen < 3)
1721 SetLastError(NTE_BAD_DATA);
1722 return FALSE;
1724 for (i=2; i<dwDataLen; i++)
1725 if (!abData[i])
1726 break;
1728 if ((i == dwDataLen) || (*dwBufferLen < dwDataLen - i - 1) ||
1729 (abData[0] != 0x00) || (abData[1] != RSAENH_PKC_BLOCKTYPE))
1731 SetLastError(NTE_BAD_DATA);
1732 return FALSE;
1735 *dwBufferLen = dwDataLen - i - 1;
1736 memmove(abBuffer, abData + i + 1, *dwBufferLen);
1737 return TRUE;
1740 /******************************************************************************
1741 * CPAcquireContext (RSAENH.@)
1743 * Acquire a handle to the key container specified by pszContainer
1745 * PARAMS
1746 * phProv [O] Pointer to the location the acquired handle will be written to.
1747 * pszContainer [I] Name of the desired key container. See Notes
1748 * dwFlags [I] Flags. See Notes.
1749 * pVTable [I] Pointer to a PVTableProvStruct containing callbacks.
1751 * RETURNS
1752 * Success: TRUE
1753 * Failure: FALSE
1755 * NOTES
1756 * If pszContainer is NULL or points to a zero length string the user's login
1757 * name will be used as the key container name.
1759 * If the CRYPT_NEW_KEYSET flag is set in dwFlags a new keyset will be created.
1760 * If a keyset with the given name already exists, the function fails and sets
1761 * last error to NTE_EXISTS. If CRYPT_NEW_KEYSET is not set and the specified
1762 * key container does not exist, function fails and sets last error to
1763 * NTE_BAD_KEYSET.
1765 BOOL WINAPI RSAENH_CPAcquireContext(HCRYPTPROV *phProv, LPSTR pszContainer,
1766 DWORD dwFlags, PVTableProvStruc pVTable)
1768 CHAR szKeyContainerName[MAX_PATH];
1770 TRACE("(phProv=%p, pszContainer=%s, dwFlags=%08x, pVTable=%p)\n", phProv,
1771 debugstr_a(pszContainer), dwFlags, pVTable);
1773 if (pszContainer && *pszContainer)
1775 lstrcpynA(szKeyContainerName, pszContainer, MAX_PATH);
1777 else
1779 DWORD dwLen = sizeof(szKeyContainerName);
1780 if (!GetUserNameA(szKeyContainerName, &dwLen)) return FALSE;
1783 switch (dwFlags & (CRYPT_NEWKEYSET|CRYPT_VERIFYCONTEXT|CRYPT_DELETEKEYSET))
1785 case 0:
1786 *phProv = read_key_container(szKeyContainerName, dwFlags, pVTable);
1787 break;
1789 case CRYPT_DELETEKEYSET:
1790 return delete_container_key(szKeyContainerName, dwFlags);
1792 case CRYPT_NEWKEYSET:
1793 *phProv = read_key_container(szKeyContainerName, dwFlags, pVTable);
1794 if (*phProv != (HCRYPTPROV)INVALID_HANDLE_VALUE)
1796 release_handle(&handle_table, *phProv, RSAENH_MAGIC_CONTAINER);
1797 TRACE("Can't create new keyset, already exists\n");
1798 SetLastError(NTE_EXISTS);
1799 return FALSE;
1801 *phProv = new_key_container(szKeyContainerName, dwFlags, pVTable);
1802 break;
1804 case CRYPT_VERIFYCONTEXT|CRYPT_NEWKEYSET:
1805 case CRYPT_VERIFYCONTEXT:
1806 if (pszContainer && *pszContainer) {
1807 TRACE("pszContainer should be empty\n");
1808 SetLastError(NTE_BAD_FLAGS);
1809 return FALSE;
1811 *phProv = new_key_container("", dwFlags, pVTable);
1812 break;
1814 default:
1815 *phProv = (HCRYPTPROV)INVALID_HANDLE_VALUE;
1816 SetLastError(NTE_BAD_FLAGS);
1817 return FALSE;
1820 if (*phProv != (HCRYPTPROV)INVALID_HANDLE_VALUE) {
1821 SetLastError(ERROR_SUCCESS);
1822 return TRUE;
1823 } else {
1824 return FALSE;
1828 /******************************************************************************
1829 * CPCreateHash (RSAENH.@)
1831 * CPCreateHash creates and initializes a new hash object.
1833 * PARAMS
1834 * hProv [I] Handle to the key container to which the new hash will belong.
1835 * Algid [I] Identifies the hash algorithm, which will be used for the hash.
1836 * hKey [I] Handle to a session key applied for keyed hashes.
1837 * dwFlags [I] Currently no flags defined. Must be zero.
1838 * phHash [O] Points to the location where a handle to the new hash will be stored.
1840 * RETURNS
1841 * Success: TRUE
1842 * Failure: FALSE
1844 * NOTES
1845 * hKey is a handle to a session key applied in keyed hashes like MAC and HMAC.
1846 * If a normal hash object is to be created (like e.g. MD2 or SHA1) hKey must be zero.
1848 BOOL WINAPI RSAENH_CPCreateHash(HCRYPTPROV hProv, ALG_ID Algid, HCRYPTKEY hKey, DWORD dwFlags,
1849 HCRYPTHASH *phHash)
1851 CRYPTKEY *pCryptKey;
1852 CRYPTHASH *pCryptHash;
1853 const PROV_ENUMALGS_EX *peaAlgidInfo;
1855 TRACE("(hProv=%08lx, Algid=%08x, hKey=%08lx, dwFlags=%08x, phHash=%p)\n", hProv, Algid, hKey,
1856 dwFlags, phHash);
1858 peaAlgidInfo = get_algid_info(hProv, Algid);
1859 if (!peaAlgidInfo) return FALSE;
1861 if (dwFlags)
1863 SetLastError(NTE_BAD_FLAGS);
1864 return FALSE;
1867 if (Algid == CALG_MAC || Algid == CALG_HMAC || Algid == CALG_SCHANNEL_MASTER_HASH ||
1868 Algid == CALG_TLS1PRF)
1870 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey)) {
1871 SetLastError(NTE_BAD_KEY);
1872 return FALSE;
1875 if ((Algid == CALG_MAC) && (GET_ALG_TYPE(pCryptKey->aiAlgid) != ALG_TYPE_BLOCK)) {
1876 SetLastError(NTE_BAD_KEY);
1877 return FALSE;
1880 if ((Algid == CALG_SCHANNEL_MASTER_HASH || Algid == CALG_TLS1PRF) &&
1881 (pCryptKey->aiAlgid != CALG_TLS1_MASTER))
1883 SetLastError(NTE_BAD_KEY);
1884 return FALSE;
1886 if (Algid == CALG_SCHANNEL_MASTER_HASH &&
1887 ((!pCryptKey->siSChannelInfo.blobClientRandom.cbData) ||
1888 (!pCryptKey->siSChannelInfo.blobServerRandom.cbData)))
1890 SetLastError(ERROR_INVALID_PARAMETER);
1891 return FALSE;
1894 if ((Algid == CALG_TLS1PRF) && (pCryptKey->dwState != RSAENH_KEYSTATE_MASTERKEY)) {
1895 SetLastError(NTE_BAD_KEY_STATE);
1896 return FALSE;
1900 *phHash = new_object(&handle_table, sizeof(CRYPTHASH), RSAENH_MAGIC_HASH,
1901 destroy_hash, (OBJECTHDR**)&pCryptHash);
1902 if (!pCryptHash) return FALSE;
1904 pCryptHash->aiAlgid = Algid;
1905 pCryptHash->hKey = hKey;
1906 pCryptHash->hProv = hProv;
1907 pCryptHash->dwState = RSAENH_HASHSTATE_HASHING;
1908 pCryptHash->pHMACInfo = NULL;
1909 pCryptHash->dwHashSize = peaAlgidInfo->dwDefaultLen >> 3;
1910 init_data_blob(&pCryptHash->tpPRFParams.blobLabel);
1911 init_data_blob(&pCryptHash->tpPRFParams.blobSeed);
1913 if (Algid == CALG_SCHANNEL_MASTER_HASH) {
1914 static const char keyex[] = "key expansion";
1915 BYTE key_expansion[sizeof keyex];
1916 CRYPT_DATA_BLOB blobRandom, blobKeyExpansion = { 13, key_expansion };
1918 memcpy( key_expansion, keyex, sizeof keyex );
1920 if (pCryptKey->dwState != RSAENH_KEYSTATE_MASTERKEY) {
1921 static const char msec[] = "master secret";
1922 BYTE master_secret[sizeof msec];
1923 CRYPT_DATA_BLOB blobLabel = { 13, master_secret };
1924 BYTE abKeyValue[48];
1926 memcpy( master_secret, msec, sizeof msec );
1928 /* See RFC 2246, chapter 8.1 */
1929 if (!concat_data_blobs(&blobRandom,
1930 &pCryptKey->siSChannelInfo.blobClientRandom,
1931 &pCryptKey->siSChannelInfo.blobServerRandom))
1933 return FALSE;
1935 tls1_prf(hProv, hKey, &blobLabel, &blobRandom, abKeyValue, 48);
1936 pCryptKey->dwState = RSAENH_KEYSTATE_MASTERKEY;
1937 memcpy(pCryptKey->abKeyValue, abKeyValue, 48);
1938 free_data_blob(&blobRandom);
1941 /* See RFC 2246, chapter 6.3 */
1942 if (!concat_data_blobs(&blobRandom,
1943 &pCryptKey->siSChannelInfo.blobServerRandom,
1944 &pCryptKey->siSChannelInfo.blobClientRandom))
1946 return FALSE;
1948 tls1_prf(hProv, hKey, &blobKeyExpansion, &blobRandom, pCryptHash->abHashValue,
1949 RSAENH_MAX_HASH_SIZE);
1950 free_data_blob(&blobRandom);
1953 return init_hash(pCryptHash);
1956 /******************************************************************************
1957 * CPDestroyHash (RSAENH.@)
1959 * Releases the handle to a hash object. The object is destroyed if its reference
1960 * count reaches zero.
1962 * PARAMS
1963 * hProv [I] Handle to the key container to which the hash object belongs.
1964 * hHash [I] Handle to the hash object to be released.
1966 * RETURNS
1967 * Success: TRUE
1968 * Failure: FALSE
1970 BOOL WINAPI RSAENH_CPDestroyHash(HCRYPTPROV hProv, HCRYPTHASH hHash)
1972 TRACE("(hProv=%08lx, hHash=%08lx)\n", hProv, hHash);
1974 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
1976 SetLastError(NTE_BAD_UID);
1977 return FALSE;
1980 if (!release_handle(&handle_table, hHash, RSAENH_MAGIC_HASH))
1982 SetLastError(NTE_BAD_HASH);
1983 return FALSE;
1986 return TRUE;
1989 /******************************************************************************
1990 * CPDestroyKey (RSAENH.@)
1992 * Releases the handle to a key object. The object is destroyed if its reference
1993 * count reaches zero.
1995 * PARAMS
1996 * hProv [I] Handle to the key container to which the key object belongs.
1997 * hKey [I] Handle to the key object to be released.
1999 * RETURNS
2000 * Success: TRUE
2001 * Failure: FALSE
2003 BOOL WINAPI RSAENH_CPDestroyKey(HCRYPTPROV hProv, HCRYPTKEY hKey)
2005 TRACE("(hProv=%08lx, hKey=%08lx)\n", hProv, hKey);
2007 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2009 SetLastError(NTE_BAD_UID);
2010 return FALSE;
2013 if (!release_handle(&handle_table, hKey, RSAENH_MAGIC_KEY))
2015 SetLastError(NTE_BAD_KEY);
2016 return FALSE;
2019 return TRUE;
2022 /******************************************************************************
2023 * CPDuplicateHash (RSAENH.@)
2025 * Clones a hash object including its current state.
2027 * PARAMS
2028 * hUID [I] Handle to the key container the hash belongs to.
2029 * hHash [I] Handle to the hash object to be cloned.
2030 * pdwReserved [I] Reserved. Must be NULL.
2031 * dwFlags [I] No flags are currently defined. Must be 0.
2032 * phHash [O] Handle to the cloned hash object.
2034 * RETURNS
2035 * Success: TRUE.
2036 * Failure: FALSE.
2038 BOOL WINAPI RSAENH_CPDuplicateHash(HCRYPTPROV hUID, HCRYPTHASH hHash, DWORD *pdwReserved,
2039 DWORD dwFlags, HCRYPTHASH *phHash)
2041 CRYPTHASH *pSrcHash, *pDestHash;
2043 TRACE("(hUID=%08lx, hHash=%08lx, pdwReserved=%p, dwFlags=%08x, phHash=%p)\n", hUID, hHash,
2044 pdwReserved, dwFlags, phHash);
2046 if (!is_valid_handle(&handle_table, hUID, RSAENH_MAGIC_CONTAINER))
2048 SetLastError(NTE_BAD_UID);
2049 return FALSE;
2052 if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH, (OBJECTHDR**)&pSrcHash))
2054 SetLastError(NTE_BAD_HASH);
2055 return FALSE;
2058 if (!phHash || pdwReserved || dwFlags)
2060 SetLastError(ERROR_INVALID_PARAMETER);
2061 return FALSE;
2064 *phHash = new_object(&handle_table, sizeof(CRYPTHASH), RSAENH_MAGIC_HASH,
2065 destroy_hash, (OBJECTHDR**)&pDestHash);
2066 if (*phHash != (HCRYPTHASH)INVALID_HANDLE_VALUE)
2068 *pDestHash = *pSrcHash;
2069 duplicate_hash_impl(&pSrcHash->context, &pDestHash->context);
2070 copy_hmac_info(&pDestHash->pHMACInfo, pSrcHash->pHMACInfo);
2071 copy_data_blob(&pDestHash->tpPRFParams.blobLabel, &pSrcHash->tpPRFParams.blobLabel);
2072 copy_data_blob(&pDestHash->tpPRFParams.blobSeed, &pSrcHash->tpPRFParams.blobSeed);
2075 return *phHash != (HCRYPTHASH)INVALID_HANDLE_VALUE;
2078 /******************************************************************************
2079 * CPDuplicateKey (RSAENH.@)
2081 * Clones a key object including its current state.
2083 * PARAMS
2084 * hUID [I] Handle to the key container the hash belongs to.
2085 * hKey [I] Handle to the key object to be cloned.
2086 * pdwReserved [I] Reserved. Must be NULL.
2087 * dwFlags [I] No flags are currently defined. Must be 0.
2088 * phHash [O] Handle to the cloned key object.
2090 * RETURNS
2091 * Success: TRUE.
2092 * Failure: FALSE.
2094 BOOL WINAPI RSAENH_CPDuplicateKey(HCRYPTPROV hUID, HCRYPTKEY hKey, DWORD *pdwReserved,
2095 DWORD dwFlags, HCRYPTKEY *phKey)
2097 CRYPTKEY *pSrcKey, *pDestKey;
2099 TRACE("(hUID=%08lx, hKey=%08lx, pdwReserved=%p, dwFlags=%08x, phKey=%p)\n", hUID, hKey,
2100 pdwReserved, dwFlags, phKey);
2102 if (!is_valid_handle(&handle_table, hUID, RSAENH_MAGIC_CONTAINER))
2104 SetLastError(NTE_BAD_UID);
2105 return FALSE;
2108 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pSrcKey))
2110 SetLastError(NTE_BAD_KEY);
2111 return FALSE;
2114 if (!phKey || pdwReserved || dwFlags)
2116 SetLastError(ERROR_INVALID_PARAMETER);
2117 return FALSE;
2120 *phKey = new_object(&handle_table, sizeof(CRYPTKEY), RSAENH_MAGIC_KEY, destroy_key,
2121 (OBJECTHDR**)&pDestKey);
2122 if (*phKey != (HCRYPTKEY)INVALID_HANDLE_VALUE)
2124 *pDestKey = *pSrcKey;
2125 copy_data_blob(&pDestKey->siSChannelInfo.blobServerRandom,
2126 &pSrcKey->siSChannelInfo.blobServerRandom);
2127 copy_data_blob(&pDestKey->siSChannelInfo.blobClientRandom,
2128 &pSrcKey->siSChannelInfo.blobClientRandom);
2129 duplicate_key_impl(pSrcKey->aiAlgid, &pSrcKey->context, &pDestKey->context);
2130 return TRUE;
2132 else
2134 return FALSE;
2138 /******************************************************************************
2139 * CPEncrypt (RSAENH.@)
2141 * Encrypt data.
2143 * PARAMS
2144 * hProv [I] The key container hKey and hHash belong to.
2145 * hKey [I] The key used to encrypt the data.
2146 * hHash [I] An optional hash object for parallel hashing. See notes.
2147 * Final [I] Indicates if this is the last block of data to encrypt.
2148 * dwFlags [I] Currently no flags defined. Must be zero.
2149 * pbData [I/O] Pointer to the data to encrypt. Encrypted data will also be stored there.
2150 * pdwDataLen [I/O] I: Length of data to encrypt, O: Length of encrypted data.
2151 * dwBufLen [I] Size of the buffer at pbData.
2153 * RETURNS
2154 * Success: TRUE.
2155 * Failure: FALSE.
2157 * NOTES
2158 * If a hash object handle is provided in hHash, it will be updated with the plaintext.
2159 * This is useful for message signatures.
2161 * This function uses the standard WINAPI protocol for querying data of dynamic length.
2163 BOOL WINAPI RSAENH_CPEncrypt(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final,
2164 DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen, DWORD dwBufLen)
2166 CRYPTKEY *pCryptKey;
2167 BYTE *in, out[RSAENH_MAX_BLOCK_SIZE], o[RSAENH_MAX_BLOCK_SIZE];
2168 DWORD dwEncryptedLen, i, j, k;
2170 TRACE("(hProv=%08lx, hKey=%08lx, hHash=%08lx, Final=%d, dwFlags=%08x, pbData=%p, "
2171 "pdwDataLen=%p, dwBufLen=%d)\n", hProv, hKey, hHash, Final, dwFlags, pbData, pdwDataLen,
2172 dwBufLen);
2174 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2176 SetLastError(NTE_BAD_UID);
2177 return FALSE;
2180 if (dwFlags)
2182 SetLastError(NTE_BAD_FLAGS);
2183 return FALSE;
2186 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2188 SetLastError(NTE_BAD_KEY);
2189 return FALSE;
2192 if (pCryptKey->dwState == RSAENH_KEYSTATE_IDLE)
2193 pCryptKey->dwState = RSAENH_KEYSTATE_ENCRYPTING;
2195 if (pCryptKey->dwState != RSAENH_KEYSTATE_ENCRYPTING)
2197 SetLastError(NTE_BAD_DATA);
2198 return FALSE;
2201 if (is_valid_handle(&handle_table, hHash, RSAENH_MAGIC_HASH)) {
2202 if (!RSAENH_CPHashData(hProv, hHash, pbData, *pdwDataLen, 0)) return FALSE;
2205 if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_BLOCK) {
2206 if (!Final && (*pdwDataLen % pCryptKey->dwBlockLen)) {
2207 SetLastError(NTE_BAD_DATA);
2208 return FALSE;
2211 dwEncryptedLen = (*pdwDataLen/pCryptKey->dwBlockLen+(Final?1:0))*pCryptKey->dwBlockLen;
2213 if (pbData == NULL) {
2214 *pdwDataLen = dwEncryptedLen;
2215 return TRUE;
2217 else if (dwEncryptedLen > dwBufLen) {
2218 *pdwDataLen = dwEncryptedLen;
2219 SetLastError(ERROR_MORE_DATA);
2220 return FALSE;
2223 /* Pad final block with length bytes */
2224 for (i=*pdwDataLen; i<dwEncryptedLen; i++) pbData[i] = dwEncryptedLen - *pdwDataLen;
2225 *pdwDataLen = dwEncryptedLen;
2227 for (i=0, in=pbData; i<*pdwDataLen; i+=pCryptKey->dwBlockLen, in+=pCryptKey->dwBlockLen) {
2228 switch (pCryptKey->dwMode) {
2229 case CRYPT_MODE_ECB:
2230 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out,
2231 RSAENH_ENCRYPT);
2232 break;
2234 case CRYPT_MODE_CBC:
2235 for (j=0; j<pCryptKey->dwBlockLen; j++) in[j] ^= pCryptKey->abChainVector[j];
2236 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out,
2237 RSAENH_ENCRYPT);
2238 memcpy(pCryptKey->abChainVector, out, pCryptKey->dwBlockLen);
2239 break;
2241 case CRYPT_MODE_CFB:
2242 for (j=0; j<pCryptKey->dwBlockLen; j++) {
2243 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context,
2244 pCryptKey->abChainVector, o, RSAENH_ENCRYPT);
2245 out[j] = in[j] ^ o[0];
2246 for (k=0; k<pCryptKey->dwBlockLen-1; k++)
2247 pCryptKey->abChainVector[k] = pCryptKey->abChainVector[k+1];
2248 pCryptKey->abChainVector[k] = out[j];
2250 break;
2252 default:
2253 SetLastError(NTE_BAD_ALGID);
2254 return FALSE;
2256 memcpy(in, out, pCryptKey->dwBlockLen);
2258 } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_STREAM) {
2259 if (pbData == NULL) {
2260 *pdwDataLen = dwBufLen;
2261 return TRUE;
2263 encrypt_stream_impl(pCryptKey->aiAlgid, &pCryptKey->context, pbData, *pdwDataLen);
2264 } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_RSA) {
2265 if (pCryptKey->aiAlgid == CALG_RSA_SIGN) {
2266 SetLastError(NTE_BAD_KEY);
2267 return FALSE;
2269 if (!pbData) {
2270 *pdwDataLen = pCryptKey->dwBlockLen;
2271 return TRUE;
2273 if (dwBufLen < pCryptKey->dwBlockLen) {
2274 SetLastError(ERROR_MORE_DATA);
2275 return FALSE;
2277 if (!pad_data(pbData, *pdwDataLen, pbData, pCryptKey->dwBlockLen, dwFlags)) return FALSE;
2278 encrypt_block_impl(pCryptKey->aiAlgid, PK_PUBLIC, &pCryptKey->context, pbData, pbData, RSAENH_ENCRYPT);
2279 *pdwDataLen = pCryptKey->dwBlockLen;
2280 Final = TRUE;
2281 } else {
2282 SetLastError(NTE_BAD_TYPE);
2283 return FALSE;
2286 if (Final) setup_key(pCryptKey);
2288 return TRUE;
2291 /******************************************************************************
2292 * CPDecrypt (RSAENH.@)
2294 * Decrypt data.
2296 * PARAMS
2297 * hProv [I] The key container hKey and hHash belong to.
2298 * hKey [I] The key used to decrypt the data.
2299 * hHash [I] An optional hash object for parallel hashing. See notes.
2300 * Final [I] Indicates if this is the last block of data to decrypt.
2301 * dwFlags [I] Currently no flags defined. Must be zero.
2302 * pbData [I/O] Pointer to the data to decrypt. Plaintext will also be stored there.
2303 * pdwDataLen [I/O] I: Length of ciphertext, O: Length of plaintext.
2305 * RETURNS
2306 * Success: TRUE.
2307 * Failure: FALSE.
2309 * NOTES
2310 * If a hash object handle is provided in hHash, it will be updated with the plaintext.
2311 * This is useful for message signatures.
2313 * This function uses the standard WINAPI protocol for querying data of dynamic length.
2315 BOOL WINAPI RSAENH_CPDecrypt(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final,
2316 DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2318 CRYPTKEY *pCryptKey;
2319 BYTE *in, out[RSAENH_MAX_BLOCK_SIZE], o[RSAENH_MAX_BLOCK_SIZE];
2320 DWORD i, j, k;
2321 DWORD dwMax;
2323 TRACE("(hProv=%08lx, hKey=%08lx, hHash=%08lx, Final=%d, dwFlags=%08x, pbData=%p, "
2324 "pdwDataLen=%p)\n", hProv, hKey, hHash, Final, dwFlags, pbData, pdwDataLen);
2326 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2328 SetLastError(NTE_BAD_UID);
2329 return FALSE;
2332 if (dwFlags)
2334 SetLastError(NTE_BAD_FLAGS);
2335 return FALSE;
2338 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2340 SetLastError(NTE_BAD_KEY);
2341 return FALSE;
2344 if (pCryptKey->dwState == RSAENH_KEYSTATE_IDLE)
2345 pCryptKey->dwState = RSAENH_KEYSTATE_ENCRYPTING;
2347 if (pCryptKey->dwState != RSAENH_KEYSTATE_ENCRYPTING)
2349 SetLastError(NTE_BAD_DATA);
2350 return FALSE;
2353 dwMax=*pdwDataLen;
2355 if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_BLOCK) {
2356 for (i=0, in=pbData; i<*pdwDataLen; i+=pCryptKey->dwBlockLen, in+=pCryptKey->dwBlockLen) {
2357 switch (pCryptKey->dwMode) {
2358 case CRYPT_MODE_ECB:
2359 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out,
2360 RSAENH_DECRYPT);
2361 break;
2363 case CRYPT_MODE_CBC:
2364 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out,
2365 RSAENH_DECRYPT);
2366 for (j=0; j<pCryptKey->dwBlockLen; j++) out[j] ^= pCryptKey->abChainVector[j];
2367 memcpy(pCryptKey->abChainVector, in, pCryptKey->dwBlockLen);
2368 break;
2370 case CRYPT_MODE_CFB:
2371 for (j=0; j<pCryptKey->dwBlockLen; j++) {
2372 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context,
2373 pCryptKey->abChainVector, o, RSAENH_ENCRYPT);
2374 out[j] = in[j] ^ o[0];
2375 for (k=0; k<pCryptKey->dwBlockLen-1; k++)
2376 pCryptKey->abChainVector[k] = pCryptKey->abChainVector[k+1];
2377 pCryptKey->abChainVector[k] = in[j];
2379 break;
2381 default:
2382 SetLastError(NTE_BAD_ALGID);
2383 return FALSE;
2385 memcpy(in, out, pCryptKey->dwBlockLen);
2387 if (Final) {
2388 if (pbData[*pdwDataLen-1] &&
2389 pbData[*pdwDataLen-1] <= pCryptKey->dwBlockLen &&
2390 pbData[*pdwDataLen-1] <= *pdwDataLen) {
2391 BOOL padOkay = TRUE;
2393 /* check that every bad byte has the same value */
2394 for (i = 1; padOkay && i < pbData[*pdwDataLen-1]; i++)
2395 if (pbData[*pdwDataLen - i - 1] != pbData[*pdwDataLen - 1])
2396 padOkay = FALSE;
2397 if (padOkay)
2398 *pdwDataLen -= pbData[*pdwDataLen-1];
2399 else {
2400 SetLastError(NTE_BAD_DATA);
2401 setup_key(pCryptKey);
2402 return FALSE;
2405 else {
2406 SetLastError(NTE_BAD_DATA);
2407 setup_key(pCryptKey);
2408 return FALSE;
2412 } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_STREAM) {
2413 encrypt_stream_impl(pCryptKey->aiAlgid, &pCryptKey->context, pbData, *pdwDataLen);
2414 } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_RSA) {
2415 if (pCryptKey->aiAlgid == CALG_RSA_SIGN) {
2416 SetLastError(NTE_BAD_KEY);
2417 return FALSE;
2419 encrypt_block_impl(pCryptKey->aiAlgid, PK_PRIVATE, &pCryptKey->context, pbData, pbData, RSAENH_DECRYPT);
2420 if (!unpad_data(pbData, pCryptKey->dwBlockLen, pbData, pdwDataLen, dwFlags)) return FALSE;
2421 Final = TRUE;
2422 } else {
2423 SetLastError(NTE_BAD_TYPE);
2424 return FALSE;
2427 if (Final) setup_key(pCryptKey);
2429 if (is_valid_handle(&handle_table, hHash, RSAENH_MAGIC_HASH)) {
2430 if (*pdwDataLen>dwMax ||
2431 !RSAENH_CPHashData(hProv, hHash, pbData, *pdwDataLen, 0)) return FALSE;
2434 return TRUE;
2437 static BOOL crypt_export_simple(CRYPTKEY *pCryptKey, CRYPTKEY *pPubKey,
2438 DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2440 BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2441 ALG_ID *pAlgid = (ALG_ID*)(pBlobHeader+1);
2442 DWORD dwDataLen;
2444 if (!(GET_ALG_CLASS(pCryptKey->aiAlgid)&(ALG_CLASS_DATA_ENCRYPT|ALG_CLASS_MSG_ENCRYPT))) {
2445 SetLastError(NTE_BAD_KEY); /* FIXME: error code? */
2446 return FALSE;
2449 dwDataLen = sizeof(BLOBHEADER) + sizeof(ALG_ID) + pPubKey->dwBlockLen;
2450 if (pbData) {
2451 if (*pdwDataLen < dwDataLen) {
2452 SetLastError(ERROR_MORE_DATA);
2453 *pdwDataLen = dwDataLen;
2454 return FALSE;
2457 pBlobHeader->bType = SIMPLEBLOB;
2458 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2459 pBlobHeader->reserved = 0;
2460 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2462 *pAlgid = pPubKey->aiAlgid;
2464 if (!pad_data(pCryptKey->abKeyValue, pCryptKey->dwKeyLen, (BYTE*)(pAlgid+1),
2465 pPubKey->dwBlockLen, dwFlags))
2467 return FALSE;
2470 encrypt_block_impl(pPubKey->aiAlgid, PK_PUBLIC, &pPubKey->context, (BYTE*)(pAlgid+1),
2471 (BYTE*)(pAlgid+1), RSAENH_ENCRYPT);
2473 *pdwDataLen = dwDataLen;
2474 return TRUE;
2477 static BOOL crypt_export_public_key(CRYPTKEY *pCryptKey, BYTE *pbData,
2478 DWORD *pdwDataLen)
2480 BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2481 RSAPUBKEY *pRSAPubKey = (RSAPUBKEY*)(pBlobHeader+1);
2482 DWORD dwDataLen;
2484 if ((pCryptKey->aiAlgid != CALG_RSA_KEYX) && (pCryptKey->aiAlgid != CALG_RSA_SIGN)) {
2485 SetLastError(NTE_BAD_KEY);
2486 return FALSE;
2489 dwDataLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) + pCryptKey->dwKeyLen;
2490 if (pbData) {
2491 if (*pdwDataLen < dwDataLen) {
2492 SetLastError(ERROR_MORE_DATA);
2493 *pdwDataLen = dwDataLen;
2494 return FALSE;
2497 pBlobHeader->bType = PUBLICKEYBLOB;
2498 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2499 pBlobHeader->reserved = 0;
2500 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2502 pRSAPubKey->magic = RSAENH_MAGIC_RSA1;
2503 pRSAPubKey->bitlen = pCryptKey->dwKeyLen << 3;
2505 export_public_key_impl((BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2506 pCryptKey->dwKeyLen, &pRSAPubKey->pubexp);
2508 *pdwDataLen = dwDataLen;
2509 return TRUE;
2512 static BOOL crypt_export_private_key(CRYPTKEY *pCryptKey, BOOL force,
2513 BYTE *pbData, DWORD *pdwDataLen)
2515 BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2516 RSAPUBKEY *pRSAPubKey = (RSAPUBKEY*)(pBlobHeader+1);
2517 DWORD dwDataLen;
2519 if ((pCryptKey->aiAlgid != CALG_RSA_KEYX) && (pCryptKey->aiAlgid != CALG_RSA_SIGN)) {
2520 SetLastError(NTE_BAD_KEY);
2521 return FALSE;
2523 if (!force && !(pCryptKey->dwPermissions & CRYPT_EXPORT))
2525 SetLastError(NTE_BAD_KEY_STATE);
2526 return FALSE;
2529 dwDataLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) +
2530 2 * pCryptKey->dwKeyLen + 5 * ((pCryptKey->dwKeyLen + 1) >> 1);
2531 if (pbData) {
2532 if (*pdwDataLen < dwDataLen) {
2533 SetLastError(ERROR_MORE_DATA);
2534 *pdwDataLen = dwDataLen;
2535 return FALSE;
2538 pBlobHeader->bType = PRIVATEKEYBLOB;
2539 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2540 pBlobHeader->reserved = 0;
2541 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2543 pRSAPubKey->magic = RSAENH_MAGIC_RSA2;
2544 pRSAPubKey->bitlen = pCryptKey->dwKeyLen << 3;
2546 export_private_key_impl((BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2547 pCryptKey->dwKeyLen, &pRSAPubKey->pubexp);
2549 *pdwDataLen = dwDataLen;
2550 return TRUE;
2553 static BOOL crypt_export_plaintext_key(CRYPTKEY *pCryptKey, BYTE *pbData,
2554 DWORD *pdwDataLen)
2556 BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2557 DWORD *pKeyLen = (DWORD*)(pBlobHeader+1);
2558 BYTE *pbKey = (BYTE*)(pKeyLen+1);
2559 DWORD dwDataLen;
2561 dwDataLen = sizeof(BLOBHEADER) + sizeof(DWORD) + pCryptKey->dwKeyLen;
2562 if (pbData) {
2563 if (*pdwDataLen < dwDataLen) {
2564 SetLastError(ERROR_MORE_DATA);
2565 *pdwDataLen = dwDataLen;
2566 return FALSE;
2569 pBlobHeader->bType = PLAINTEXTKEYBLOB;
2570 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2571 pBlobHeader->reserved = 0;
2572 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2574 *pKeyLen = pCryptKey->dwKeyLen;
2575 memcpy(pbKey, pCryptKey->abKeyValue, pCryptKey->dwKeyLen);
2577 *pdwDataLen = dwDataLen;
2578 return TRUE;
2580 /******************************************************************************
2581 * crypt_export_key [Internal]
2583 * Export a key into a binary large object (BLOB). Called by CPExportKey and
2584 * by store_key_pair.
2586 * PARAMS
2587 * pCryptKey [I] Key to be exported.
2588 * hPubKey [I] Key used to encrypt sensitive BLOB data.
2589 * dwBlobType [I] SIMPLEBLOB, PUBLICKEYBLOB or PRIVATEKEYBLOB.
2590 * dwFlags [I] Currently none defined.
2591 * force [I] If TRUE, the key is written no matter what the key's
2592 * permissions are. Otherwise the key's permissions are
2593 * checked before exporting.
2594 * pbData [O] Pointer to a buffer where the BLOB will be written to.
2595 * pdwDataLen [I/O] I: Size of buffer at pbData, O: Size of BLOB
2597 * RETURNS
2598 * Success: TRUE.
2599 * Failure: FALSE.
2601 static BOOL crypt_export_key(CRYPTKEY *pCryptKey, HCRYPTKEY hPubKey,
2602 DWORD dwBlobType, DWORD dwFlags, BOOL force,
2603 BYTE *pbData, DWORD *pdwDataLen)
2605 CRYPTKEY *pPubKey;
2607 if (dwFlags & CRYPT_SSL2_FALLBACK) {
2608 if (pCryptKey->aiAlgid != CALG_SSL2_MASTER) {
2609 SetLastError(NTE_BAD_KEY);
2610 return FALSE;
2614 switch ((BYTE)dwBlobType)
2616 case SIMPLEBLOB:
2617 if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pPubKey)){
2618 SetLastError(NTE_BAD_PUBLIC_KEY); /* FIXME: error_code? */
2619 return FALSE;
2621 return crypt_export_simple(pCryptKey, pPubKey, dwFlags, pbData,
2622 pdwDataLen);
2624 case PUBLICKEYBLOB:
2625 if (is_valid_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY)) {
2626 SetLastError(NTE_BAD_KEY); /* FIXME: error code? */
2627 return FALSE;
2630 return crypt_export_public_key(pCryptKey, pbData, pdwDataLen);
2632 case PRIVATEKEYBLOB:
2633 return crypt_export_private_key(pCryptKey, force, pbData, pdwDataLen);
2635 case PLAINTEXTKEYBLOB:
2636 return crypt_export_plaintext_key(pCryptKey, pbData, pdwDataLen);
2638 default:
2639 SetLastError(NTE_BAD_TYPE); /* FIXME: error code? */
2640 return FALSE;
2644 /******************************************************************************
2645 * CPExportKey (RSAENH.@)
2647 * Export a key into a binary large object (BLOB).
2649 * PARAMS
2650 * hProv [I] Key container from which a key is to be exported.
2651 * hKey [I] Key to be exported.
2652 * hPubKey [I] Key used to encrypt sensitive BLOB data.
2653 * dwBlobType [I] SIMPLEBLOB, PUBLICKEYBLOB or PRIVATEKEYBLOB.
2654 * dwFlags [I] Currently none defined.
2655 * pbData [O] Pointer to a buffer where the BLOB will be written to.
2656 * pdwDataLen [I/O] I: Size of buffer at pbData, O: Size of BLOB
2658 * RETURNS
2659 * Success: TRUE.
2660 * Failure: FALSE.
2662 BOOL WINAPI RSAENH_CPExportKey(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTKEY hPubKey,
2663 DWORD dwBlobType, DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2665 CRYPTKEY *pCryptKey;
2667 TRACE("(hProv=%08lx, hKey=%08lx, hPubKey=%08lx, dwBlobType=%08x, dwFlags=%08x, pbData=%p,"
2668 "pdwDataLen=%p)\n", hProv, hKey, hPubKey, dwBlobType, dwFlags, pbData, pdwDataLen);
2670 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2672 SetLastError(NTE_BAD_UID);
2673 return FALSE;
2676 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2678 SetLastError(NTE_BAD_KEY);
2679 return FALSE;
2682 return crypt_export_key(pCryptKey, hPubKey, dwBlobType, dwFlags, FALSE,
2683 pbData, pdwDataLen);
2686 /******************************************************************************
2687 * release_and_install_key [Internal]
2689 * Release an existing key, if present, and replaces it with a new one.
2691 * PARAMS
2692 * hProv [I] Key container into which the key is to be imported.
2693 * src [I] Key which will replace *dest
2694 * dest [I] Points to key to be released and replaced with src
2695 * fStoreKey [I] If TRUE, the newly installed key is stored to the registry.
2697 static void release_and_install_key(HCRYPTPROV hProv, HCRYPTKEY src,
2698 HCRYPTKEY *dest, DWORD fStoreKey)
2700 RSAENH_CPDestroyKey(hProv, *dest);
2701 copy_handle(&handle_table, src, RSAENH_MAGIC_KEY, dest);
2702 if (fStoreKey)
2704 KEYCONTAINER *pKeyContainer;
2706 if ((pKeyContainer = get_key_container(hProv)))
2708 store_key_container_keys(pKeyContainer);
2709 store_key_container_permissions(pKeyContainer);
2714 /******************************************************************************
2715 * import_private_key [Internal]
2717 * Import a BLOB'ed private key into a key container.
2719 * PARAMS
2720 * hProv [I] Key container into which the private key is to be imported.
2721 * pbData [I] Pointer to a buffer which holds the private key BLOB.
2722 * dwDataLen [I] Length of data in buffer at pbData.
2723 * dwFlags [I] One of:
2724 * CRYPT_EXPORTABLE: the imported key is marked exportable
2725 * fStoreKey [I] If TRUE, the imported key is stored to the registry.
2726 * phKey [O] Handle to the imported key.
2729 * NOTES
2730 * Assumes the caller has already checked the BLOBHEADER at pbData to ensure
2731 * it's a PRIVATEKEYBLOB.
2733 * RETURNS
2734 * Success: TRUE.
2735 * Failure: FALSE.
2737 static BOOL import_private_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
2738 DWORD dwFlags, BOOL fStoreKey, HCRYPTKEY *phKey)
2740 KEYCONTAINER *pKeyContainer;
2741 CRYPTKEY *pCryptKey;
2742 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
2743 const RSAPUBKEY *pRSAPubKey = (const RSAPUBKEY*)(pBlobHeader+1);
2744 BOOL ret;
2746 if (dwFlags & CRYPT_IPSEC_HMAC_KEY)
2748 FIXME("unimplemented for CRYPT_IPSEC_HMAC_KEY\n");
2749 SetLastError(NTE_BAD_FLAGS);
2750 return FALSE;
2752 if (!(pKeyContainer = get_key_container(hProv)))
2753 return FALSE;
2755 if ((dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY)))
2757 ERR("datalen %d not long enough for a BLOBHEADER + RSAPUBKEY\n",
2758 dwDataLen);
2759 SetLastError(NTE_BAD_DATA);
2760 return FALSE;
2762 if (pRSAPubKey->magic != RSAENH_MAGIC_RSA2)
2764 ERR("unexpected magic %08x\n", pRSAPubKey->magic);
2765 SetLastError(NTE_BAD_DATA);
2766 return FALSE;
2768 if ((dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) +
2769 (pRSAPubKey->bitlen >> 3) + (5 * ((pRSAPubKey->bitlen+8)>>4))))
2771 DWORD expectedLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) +
2772 (pRSAPubKey->bitlen >> 3) + (5 * ((pRSAPubKey->bitlen+8)>>4));
2774 ERR("blob too short for pub key: expect %d, got %d\n",
2775 expectedLen, dwDataLen);
2776 SetLastError(NTE_BAD_DATA);
2777 return FALSE;
2780 *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, MAKELONG(0,pRSAPubKey->bitlen), &pCryptKey);
2781 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
2782 setup_key(pCryptKey);
2783 ret = import_private_key_impl((const BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2784 pRSAPubKey->bitlen/8, dwDataLen, pRSAPubKey->pubexp);
2785 if (ret) {
2786 if (dwFlags & CRYPT_EXPORTABLE)
2787 pCryptKey->dwPermissions |= CRYPT_EXPORT;
2788 switch (pBlobHeader->aiKeyAlg)
2790 case AT_SIGNATURE:
2791 case CALG_RSA_SIGN:
2792 TRACE("installing signing key\n");
2793 release_and_install_key(hProv, *phKey, &pKeyContainer->hSignatureKeyPair,
2794 fStoreKey);
2795 break;
2796 case AT_KEYEXCHANGE:
2797 case CALG_RSA_KEYX:
2798 TRACE("installing key exchange key\n");
2799 release_and_install_key(hProv, *phKey, &pKeyContainer->hKeyExchangeKeyPair,
2800 fStoreKey);
2801 break;
2804 return ret;
2807 /******************************************************************************
2808 * import_public_key [Internal]
2810 * Import a BLOB'ed public key.
2812 * PARAMS
2813 * hProv [I] A CSP.
2814 * pbData [I] Pointer to a buffer which holds the public key BLOB.
2815 * dwDataLen [I] Length of data in buffer at pbData.
2816 * dwFlags [I] One of:
2817 * CRYPT_EXPORTABLE: the imported key is marked exportable
2818 * phKey [O] Handle to the imported key.
2821 * NOTES
2822 * Assumes the caller has already checked the BLOBHEADER at pbData to ensure
2823 * it's a PUBLICKEYBLOB.
2825 * RETURNS
2826 * Success: TRUE.
2827 * Failure: FALSE.
2829 static BOOL import_public_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
2830 DWORD dwFlags, HCRYPTKEY *phKey)
2832 CRYPTKEY *pCryptKey;
2833 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
2834 const RSAPUBKEY *pRSAPubKey = (const RSAPUBKEY*)(pBlobHeader+1);
2835 ALG_ID algID;
2836 BOOL ret;
2838 if (dwFlags & CRYPT_IPSEC_HMAC_KEY)
2840 FIXME("unimplemented for CRYPT_IPSEC_HMAC_KEY\n");
2841 SetLastError(NTE_BAD_FLAGS);
2842 return FALSE;
2845 if ((dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY)) ||
2846 (pRSAPubKey->magic != RSAENH_MAGIC_RSA1) ||
2847 (dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) + (pRSAPubKey->bitlen >> 3)))
2849 SetLastError(NTE_BAD_DATA);
2850 return FALSE;
2853 /* Since this is a public key blob, only the public key is
2854 * available, so only signature verification is possible.
2856 algID = pBlobHeader->aiKeyAlg;
2857 *phKey = new_key(hProv, algID, MAKELONG(0,pRSAPubKey->bitlen), &pCryptKey);
2858 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
2859 setup_key(pCryptKey);
2860 ret = import_public_key_impl((const BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2861 pRSAPubKey->bitlen >> 3, pRSAPubKey->pubexp);
2862 if (ret) {
2863 if (dwFlags & CRYPT_EXPORTABLE)
2864 pCryptKey->dwPermissions |= CRYPT_EXPORT;
2866 return ret;
2869 /******************************************************************************
2870 * import_symmetric_key [Internal]
2872 * Import a BLOB'ed symmetric key into a key container.
2874 * PARAMS
2875 * hProv [I] Key container into which the symmetric key is to be imported.
2876 * pbData [I] Pointer to a buffer which holds the symmetric key BLOB.
2877 * dwDataLen [I] Length of data in buffer at pbData.
2878 * hPubKey [I] Key used to decrypt sensitive BLOB data.
2879 * dwFlags [I] One of:
2880 * CRYPT_EXPORTABLE: the imported key is marked exportable
2881 * phKey [O] Handle to the imported key.
2884 * NOTES
2885 * Assumes the caller has already checked the BLOBHEADER at pbData to ensure
2886 * it's a SIMPLEBLOB.
2888 * RETURNS
2889 * Success: TRUE.
2890 * Failure: FALSE.
2892 static BOOL import_symmetric_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
2893 HCRYPTKEY hPubKey, DWORD dwFlags, HCRYPTKEY *phKey)
2895 CRYPTKEY *pCryptKey, *pPubKey;
2896 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
2897 const ALG_ID *pAlgid = (const ALG_ID*)(pBlobHeader+1);
2898 const BYTE *pbKeyStream = (const BYTE*)(pAlgid + 1);
2899 BYTE *pbDecrypted;
2900 DWORD dwKeyLen;
2902 if (dwFlags & CRYPT_IPSEC_HMAC_KEY)
2904 FIXME("unimplemented for CRYPT_IPSEC_HMAC_KEY\n");
2905 SetLastError(NTE_BAD_FLAGS);
2906 return FALSE;
2908 if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pPubKey) ||
2909 pPubKey->aiAlgid != CALG_RSA_KEYX)
2911 SetLastError(NTE_BAD_PUBLIC_KEY); /* FIXME: error code? */
2912 return FALSE;
2915 if (dwDataLen < sizeof(BLOBHEADER)+sizeof(ALG_ID)+pPubKey->dwBlockLen)
2917 SetLastError(NTE_BAD_DATA); /* FIXME: error code */
2918 return FALSE;
2921 pbDecrypted = HeapAlloc(GetProcessHeap(), 0, pPubKey->dwBlockLen);
2922 if (!pbDecrypted) return FALSE;
2923 encrypt_block_impl(pPubKey->aiAlgid, PK_PRIVATE, &pPubKey->context, pbKeyStream, pbDecrypted,
2924 RSAENH_DECRYPT);
2926 dwKeyLen = RSAENH_MAX_KEY_SIZE;
2927 if (!unpad_data(pbDecrypted, pPubKey->dwBlockLen, pbDecrypted, &dwKeyLen, dwFlags)) {
2928 HeapFree(GetProcessHeap(), 0, pbDecrypted);
2929 return FALSE;
2932 *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, dwKeyLen<<19, &pCryptKey);
2933 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
2935 HeapFree(GetProcessHeap(), 0, pbDecrypted);
2936 return FALSE;
2938 memcpy(pCryptKey->abKeyValue, pbDecrypted, dwKeyLen);
2939 HeapFree(GetProcessHeap(), 0, pbDecrypted);
2940 setup_key(pCryptKey);
2941 if (dwFlags & CRYPT_EXPORTABLE)
2942 pCryptKey->dwPermissions |= CRYPT_EXPORT;
2943 return TRUE;
2946 /******************************************************************************
2947 * import_plaintext_key [Internal]
2949 * Import a plaintext key into a key container.
2951 * PARAMS
2952 * hProv [I] Key container into which the symmetric key is to be imported.
2953 * pbData [I] Pointer to a buffer which holds the plaintext key BLOB.
2954 * dwDataLen [I] Length of data in buffer at pbData.
2955 * dwFlags [I] One of:
2956 * CRYPT_EXPORTABLE: the imported key is marked exportable
2957 * phKey [O] Handle to the imported key.
2960 * NOTES
2961 * Assumes the caller has already checked the BLOBHEADER at pbData to ensure
2962 * it's a PLAINTEXTKEYBLOB.
2964 * RETURNS
2965 * Success: TRUE.
2966 * Failure: FALSE.
2968 static BOOL import_plaintext_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
2969 DWORD dwFlags, HCRYPTKEY *phKey)
2971 CRYPTKEY *pCryptKey;
2972 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
2973 const DWORD *pKeyLen = (const DWORD *)(pBlobHeader + 1);
2974 const BYTE *pbKeyStream = (const BYTE*)(pKeyLen + 1);
2976 if (dwDataLen < sizeof(BLOBHEADER)+sizeof(DWORD)+*pKeyLen)
2978 SetLastError(NTE_BAD_DATA); /* FIXME: error code */
2979 return FALSE;
2982 if (dwFlags & CRYPT_IPSEC_HMAC_KEY)
2984 *phKey = new_key(hProv, CALG_HMAC, 0, &pCryptKey);
2985 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
2986 return FALSE;
2987 if (*pKeyLen <= RSAENH_MIN(sizeof(pCryptKey->abKeyValue), RSAENH_HMAC_BLOCK_LEN))
2989 memcpy(pCryptKey->abKeyValue, pbKeyStream, *pKeyLen);
2990 pCryptKey->dwKeyLen = *pKeyLen;
2992 else
2994 CRYPT_DATA_BLOB blobHmacKey = { *pKeyLen, (BYTE *)pbKeyStream };
2996 /* In order to initialize an HMAC key, the key material is hashed,
2997 * and the output of the hash function is used as the key material.
2998 * Unfortunately, the way the Crypto API is designed, we don't know
2999 * the hash algorithm yet, so we have to copy the entire key
3000 * material.
3002 if (!copy_data_blob(&pCryptKey->blobHmacKey, &blobHmacKey))
3004 release_handle(&handle_table, *phKey, RSAENH_MAGIC_KEY);
3005 *phKey = (HCRYPTKEY)INVALID_HANDLE_VALUE;
3006 return FALSE;
3009 setup_key(pCryptKey);
3010 if (dwFlags & CRYPT_EXPORTABLE)
3011 pCryptKey->dwPermissions |= CRYPT_EXPORT;
3013 else
3015 *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, *pKeyLen<<19, &pCryptKey);
3016 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
3017 return FALSE;
3018 memcpy(pCryptKey->abKeyValue, pbKeyStream, *pKeyLen);
3019 setup_key(pCryptKey);
3020 if (dwFlags & CRYPT_EXPORTABLE)
3021 pCryptKey->dwPermissions |= CRYPT_EXPORT;
3023 return TRUE;
3026 /******************************************************************************
3027 * import_key [Internal]
3029 * Import a BLOB'ed key into a key container, optionally storing the key's
3030 * value to the registry.
3032 * PARAMS
3033 * hProv [I] Key container into which the key is to be imported.
3034 * pbData [I] Pointer to a buffer which holds the BLOB.
3035 * dwDataLen [I] Length of data in buffer at pbData.
3036 * hPubKey [I] Key used to decrypt sensitive BLOB data.
3037 * dwFlags [I] One of:
3038 * CRYPT_EXPORTABLE: the imported key is marked exportable
3039 * fStoreKey [I] If TRUE, the imported key is stored to the registry.
3040 * phKey [O] Handle to the imported key.
3042 * RETURNS
3043 * Success: TRUE.
3044 * Failure: FALSE.
3046 static BOOL import_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen, HCRYPTKEY hPubKey,
3047 DWORD dwFlags, BOOL fStoreKey, HCRYPTKEY *phKey)
3049 KEYCONTAINER *pKeyContainer;
3050 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
3052 if (!(pKeyContainer = get_key_container(hProv)))
3053 return FALSE;
3055 if (dwDataLen < sizeof(BLOBHEADER) ||
3056 pBlobHeader->bVersion != CUR_BLOB_VERSION ||
3057 pBlobHeader->reserved != 0)
3059 TRACE("bVersion = %d, reserved = %d\n", pBlobHeader->bVersion,
3060 pBlobHeader->reserved);
3061 SetLastError(NTE_BAD_DATA);
3062 return FALSE;
3065 /* If this is a verify-only context, the key is not persisted regardless of
3066 * fStoreKey's original value.
3068 fStoreKey = fStoreKey && !(dwFlags & CRYPT_VERIFYCONTEXT);
3069 TRACE("blob type: %x\n", pBlobHeader->bType);
3070 switch (pBlobHeader->bType)
3072 case PRIVATEKEYBLOB:
3073 return import_private_key(hProv, pbData, dwDataLen, dwFlags,
3074 fStoreKey, phKey);
3076 case PUBLICKEYBLOB:
3077 return import_public_key(hProv, pbData, dwDataLen, dwFlags,
3078 phKey);
3080 case SIMPLEBLOB:
3081 return import_symmetric_key(hProv, pbData, dwDataLen, hPubKey,
3082 dwFlags, phKey);
3084 case PLAINTEXTKEYBLOB:
3085 return import_plaintext_key(hProv, pbData, dwDataLen, dwFlags,
3086 phKey);
3088 default:
3089 SetLastError(NTE_BAD_TYPE); /* FIXME: error code? */
3090 return FALSE;
3094 /******************************************************************************
3095 * CPImportKey (RSAENH.@)
3097 * Import a BLOB'ed key into a key container.
3099 * PARAMS
3100 * hProv [I] Key container into which the key is to be imported.
3101 * pbData [I] Pointer to a buffer which holds the BLOB.
3102 * dwDataLen [I] Length of data in buffer at pbData.
3103 * hPubKey [I] Key used to decrypt sensitive BLOB data.
3104 * dwFlags [I] One of:
3105 * CRYPT_EXPORTABLE: the imported key is marked exportable
3106 * phKey [O] Handle to the imported key.
3108 * RETURNS
3109 * Success: TRUE.
3110 * Failure: FALSE.
3112 BOOL WINAPI RSAENH_CPImportKey(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
3113 HCRYPTKEY hPubKey, DWORD dwFlags, HCRYPTKEY *phKey)
3115 TRACE("(hProv=%08lx, pbData=%p, dwDataLen=%d, hPubKey=%08lx, dwFlags=%08x, phKey=%p)\n",
3116 hProv, pbData, dwDataLen, hPubKey, dwFlags, phKey);
3118 return import_key(hProv, pbData, dwDataLen, hPubKey, dwFlags, TRUE, phKey);
3121 /******************************************************************************
3122 * CPGenKey (RSAENH.@)
3124 * Generate a key in the key container
3126 * PARAMS
3127 * hProv [I] Key container for which a key is to be generated.
3128 * Algid [I] Crypto algorithm identifier for the key to be generated.
3129 * dwFlags [I] Upper 16 bits: Binary length of key. Lower 16 bits: Flags. See Notes
3130 * phKey [O] Handle to the generated key.
3132 * RETURNS
3133 * Success: TRUE.
3134 * Failure: FALSE.
3136 * FIXME
3137 * Flags currently not considered.
3139 * NOTES
3140 * Private key-exchange- and signature-keys can be generated with Algid AT_KEYEXCHANGE
3141 * and AT_SIGNATURE values.
3143 BOOL WINAPI RSAENH_CPGenKey(HCRYPTPROV hProv, ALG_ID Algid, DWORD dwFlags, HCRYPTKEY *phKey)
3145 KEYCONTAINER *pKeyContainer;
3146 CRYPTKEY *pCryptKey;
3148 TRACE("(hProv=%08lx, aiAlgid=%d, dwFlags=%08x, phKey=%p)\n", hProv, Algid, dwFlags, phKey);
3150 if (!(pKeyContainer = get_key_container(hProv)))
3152 /* MSDN: hProv not containing valid context handle */
3153 return FALSE;
3156 switch (Algid)
3158 case AT_SIGNATURE:
3159 case CALG_RSA_SIGN:
3160 *phKey = new_key(hProv, CALG_RSA_SIGN, dwFlags, &pCryptKey);
3161 if (pCryptKey) {
3162 new_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen);
3163 setup_key(pCryptKey);
3164 release_and_install_key(hProv, *phKey,
3165 &pKeyContainer->hSignatureKeyPair,
3166 FALSE);
3168 break;
3170 case AT_KEYEXCHANGE:
3171 case CALG_RSA_KEYX:
3172 *phKey = new_key(hProv, CALG_RSA_KEYX, dwFlags, &pCryptKey);
3173 if (pCryptKey) {
3174 new_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen);
3175 setup_key(pCryptKey);
3176 release_and_install_key(hProv, *phKey,
3177 &pKeyContainer->hKeyExchangeKeyPair,
3178 FALSE);
3180 break;
3182 case CALG_RC2:
3183 case CALG_RC4:
3184 case CALG_DES:
3185 case CALG_3DES_112:
3186 case CALG_3DES:
3187 case CALG_AES_128:
3188 case CALG_AES_192:
3189 case CALG_AES_256:
3190 case CALG_PCT1_MASTER:
3191 case CALG_SSL2_MASTER:
3192 case CALG_SSL3_MASTER:
3193 case CALG_TLS1_MASTER:
3194 *phKey = new_key(hProv, Algid, dwFlags, &pCryptKey);
3195 if (pCryptKey) {
3196 gen_rand_impl(pCryptKey->abKeyValue, RSAENH_MAX_KEY_SIZE);
3197 switch (Algid) {
3198 case CALG_SSL3_MASTER:
3199 pCryptKey->abKeyValue[0] = RSAENH_SSL3_VERSION_MAJOR;
3200 pCryptKey->abKeyValue[1] = RSAENH_SSL3_VERSION_MINOR;
3201 break;
3203 case CALG_TLS1_MASTER:
3204 pCryptKey->abKeyValue[0] = RSAENH_TLS1_VERSION_MAJOR;
3205 pCryptKey->abKeyValue[1] = RSAENH_TLS1_VERSION_MINOR;
3206 break;
3208 setup_key(pCryptKey);
3210 break;
3212 default:
3213 /* MSDN: Algorithm not supported specified by Algid */
3214 SetLastError(NTE_BAD_ALGID);
3215 return FALSE;
3218 return *phKey != (HCRYPTKEY)INVALID_HANDLE_VALUE;
3221 /******************************************************************************
3222 * CPGenRandom (RSAENH.@)
3224 * Generate a random byte stream.
3226 * PARAMS
3227 * hProv [I] Key container that is used to generate random bytes.
3228 * dwLen [I] Specifies the number of requested random data bytes.
3229 * pbBuffer [O] Random bytes will be stored here.
3231 * RETURNS
3232 * Success: TRUE
3233 * Failure: FALSE
3235 BOOL WINAPI RSAENH_CPGenRandom(HCRYPTPROV hProv, DWORD dwLen, BYTE *pbBuffer)
3237 TRACE("(hProv=%08lx, dwLen=%d, pbBuffer=%p)\n", hProv, dwLen, pbBuffer);
3239 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3241 /* MSDN: hProv not containing valid context handle */
3242 SetLastError(NTE_BAD_UID);
3243 return FALSE;
3246 return gen_rand_impl(pbBuffer, dwLen);
3249 /******************************************************************************
3250 * CPGetHashParam (RSAENH.@)
3252 * Query parameters of an hash object.
3254 * PARAMS
3255 * hProv [I] The kea container, which the hash belongs to.
3256 * hHash [I] The hash object that is to be queried.
3257 * dwParam [I] Specifies the parameter that is to be queried.
3258 * pbData [I] Pointer to the buffer where the parameter value will be stored.
3259 * pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
3260 * dwFlags [I] None currently defined.
3262 * RETURNS
3263 * Success: TRUE
3264 * Failure: FALSE
3266 * NOTES
3267 * Valid dwParams are: HP_ALGID, HP_HASHSIZE, HP_HASHVALUE. The hash will be
3268 * finalized if HP_HASHVALUE is queried.
3270 BOOL WINAPI RSAENH_CPGetHashParam(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwParam, BYTE *pbData,
3271 DWORD *pdwDataLen, DWORD dwFlags)
3273 CRYPTHASH *pCryptHash;
3275 TRACE("(hProv=%08lx, hHash=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p, dwFlags=%08x)\n",
3276 hProv, hHash, dwParam, pbData, pdwDataLen, dwFlags);
3278 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3280 SetLastError(NTE_BAD_UID);
3281 return FALSE;
3284 if (dwFlags)
3286 SetLastError(NTE_BAD_FLAGS);
3287 return FALSE;
3290 if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH,
3291 (OBJECTHDR**)&pCryptHash))
3293 SetLastError(NTE_BAD_HASH);
3294 return FALSE;
3297 if (!pdwDataLen)
3299 SetLastError(ERROR_INVALID_PARAMETER);
3300 return FALSE;
3303 switch (dwParam)
3305 case HP_ALGID:
3306 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptHash->aiAlgid,
3307 sizeof(ALG_ID));
3309 case HP_HASHSIZE:
3310 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptHash->dwHashSize,
3311 sizeof(DWORD));
3313 case HP_HASHVAL:
3314 if (pCryptHash->aiAlgid == CALG_TLS1PRF) {
3315 return tls1_prf(hProv, pCryptHash->hKey, &pCryptHash->tpPRFParams.blobLabel,
3316 &pCryptHash->tpPRFParams.blobSeed, pbData, *pdwDataLen);
3319 if ( pbData == NULL ) {
3320 *pdwDataLen = pCryptHash->dwHashSize;
3321 return TRUE;
3324 if (pbData && (pCryptHash->dwState != RSAENH_HASHSTATE_FINISHED))
3326 finalize_hash(pCryptHash);
3327 pCryptHash->dwState = RSAENH_HASHSTATE_FINISHED;
3330 return copy_param(pbData, pdwDataLen, pCryptHash->abHashValue,
3331 pCryptHash->dwHashSize);
3333 default:
3334 SetLastError(NTE_BAD_TYPE);
3335 return FALSE;
3339 /******************************************************************************
3340 * CPSetKeyParam (RSAENH.@)
3342 * Set a parameter of a key object
3344 * PARAMS
3345 * hProv [I] The key container to which the key belongs.
3346 * hKey [I] The key for which a parameter is to be set.
3347 * dwParam [I] Parameter type. See Notes.
3348 * pbData [I] Pointer to the parameter value.
3349 * dwFlags [I] Currently none defined.
3351 * RETURNS
3352 * Success: TRUE.
3353 * Failure: FALSE.
3355 * NOTES:
3356 * Defined dwParam types are:
3357 * - KP_MODE: Values MODE_CBC, MODE_ECB, MODE_CFB.
3358 * - KP_MODE_BITS: Shift width for cipher feedback mode. (Currently ignored by MS CSP's)
3359 * - KP_PERMISSIONS: Or'ed combination of CRYPT_ENCRYPT, CRYPT_DECRYPT,
3360 * CRYPT_EXPORT, CRYPT_READ, CRYPT_WRITE, CRYPT_MAC
3361 * - KP_IV: Initialization vector
3363 BOOL WINAPI RSAENH_CPSetKeyParam(HCRYPTPROV hProv, HCRYPTKEY hKey, DWORD dwParam, BYTE *pbData,
3364 DWORD dwFlags)
3366 CRYPTKEY *pCryptKey;
3368 TRACE("(hProv=%08lx, hKey=%08lx, dwParam=%08x, pbData=%p, dwFlags=%08x)\n", hProv, hKey,
3369 dwParam, pbData, dwFlags);
3371 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3373 SetLastError(NTE_BAD_UID);
3374 return FALSE;
3377 if (dwFlags) {
3378 SetLastError(NTE_BAD_FLAGS);
3379 return FALSE;
3382 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
3384 SetLastError(NTE_BAD_KEY);
3385 return FALSE;
3388 switch (dwParam) {
3389 case KP_PADDING:
3390 /* The MS providers only support PKCS5_PADDING */
3391 if (*(DWORD *)pbData != PKCS5_PADDING) {
3392 SetLastError(NTE_BAD_DATA);
3393 return FALSE;
3395 return TRUE;
3397 case KP_MODE:
3398 pCryptKey->dwMode = *(DWORD*)pbData;
3399 return TRUE;
3401 case KP_MODE_BITS:
3402 pCryptKey->dwModeBits = *(DWORD*)pbData;
3403 return TRUE;
3405 case KP_PERMISSIONS:
3407 DWORD perms = *(DWORD *)pbData;
3409 if ((perms & CRYPT_EXPORT) &&
3410 !(pCryptKey->dwPermissions & CRYPT_EXPORT))
3412 SetLastError(NTE_BAD_DATA);
3413 return FALSE;
3415 else if (!(perms & CRYPT_EXPORT) &&
3416 (pCryptKey->dwPermissions & CRYPT_EXPORT))
3418 /* Clearing the export permission appears to be ignored,
3419 * see tests.
3421 perms |= CRYPT_EXPORT;
3423 pCryptKey->dwPermissions = perms;
3424 return TRUE;
3427 case KP_IV:
3428 memcpy(pCryptKey->abInitVector, pbData, pCryptKey->dwBlockLen);
3429 setup_key(pCryptKey);
3430 return TRUE;
3432 case KP_SALT:
3433 switch (pCryptKey->aiAlgid) {
3434 case CALG_RC2:
3435 case CALG_RC4:
3437 KEYCONTAINER *pKeyContainer = get_key_container(pCryptKey->hProv);
3438 if (!pbData)
3440 SetLastError(ERROR_INVALID_PARAMETER);
3441 return FALSE;
3443 /* MSDN: the base provider always sets eleven bytes of
3444 * salt value.
3446 memcpy(pCryptKey->abKeyValue + pCryptKey->dwKeyLen,
3447 pbData, 11);
3448 pCryptKey->dwSaltLen = 11;
3449 setup_key(pCryptKey);
3450 /* After setting the salt value if the provider is not base or
3451 * strong the salt length will be reset. */
3452 if (pKeyContainer->dwPersonality != RSAENH_PERSONALITY_BASE &&
3453 pKeyContainer->dwPersonality != RSAENH_PERSONALITY_STRONG)
3454 pCryptKey->dwSaltLen = 0;
3455 break;
3457 default:
3458 SetLastError(NTE_BAD_KEY);
3459 return FALSE;
3461 return TRUE;
3463 case KP_SALT_EX:
3465 CRYPT_INTEGER_BLOB *blob = (CRYPT_INTEGER_BLOB *)pbData;
3467 /* salt length can't be greater than 184 bits = 24 bytes */
3468 if (blob->cbData > 24)
3470 SetLastError(NTE_BAD_DATA);
3471 return FALSE;
3473 memcpy(pCryptKey->abKeyValue + pCryptKey->dwKeyLen, blob->pbData,
3474 blob->cbData);
3475 pCryptKey->dwSaltLen = blob->cbData;
3476 setup_key(pCryptKey);
3477 return TRUE;
3480 case KP_EFFECTIVE_KEYLEN:
3481 switch (pCryptKey->aiAlgid) {
3482 case CALG_RC2:
3484 DWORD keylen, deflen;
3485 BOOL ret = TRUE;
3486 KEYCONTAINER *pKeyContainer = get_key_container(pCryptKey->hProv);
3488 if (!pbData)
3490 SetLastError(ERROR_INVALID_PARAMETER);
3491 return FALSE;
3493 keylen = *(DWORD *)pbData;
3494 if (!keylen || keylen > 1024)
3496 SetLastError(NTE_BAD_DATA);
3497 return FALSE;
3501 * The Base provider will force the key length to default
3502 * and set an error state if a key length different from
3503 * the default is tried.
3505 deflen = aProvEnumAlgsEx[pKeyContainer->dwPersonality]->dwDefaultLen;
3506 if (pKeyContainer->dwPersonality == RSAENH_PERSONALITY_BASE
3507 && keylen != deflen)
3509 keylen = deflen;
3510 SetLastError(NTE_BAD_DATA);
3511 ret = FALSE;
3513 pCryptKey->dwEffectiveKeyLen = keylen;
3514 setup_key(pCryptKey);
3515 return ret;
3517 default:
3518 SetLastError(NTE_BAD_TYPE);
3519 return FALSE;
3521 return TRUE;
3523 case KP_SCHANNEL_ALG:
3524 switch (((PSCHANNEL_ALG)pbData)->dwUse) {
3525 case SCHANNEL_ENC_KEY:
3526 memcpy(&pCryptKey->siSChannelInfo.saEncAlg, pbData, sizeof(SCHANNEL_ALG));
3527 break;
3529 case SCHANNEL_MAC_KEY:
3530 memcpy(&pCryptKey->siSChannelInfo.saMACAlg, pbData, sizeof(SCHANNEL_ALG));
3531 break;
3533 default:
3534 SetLastError(NTE_FAIL); /* FIXME: error code */
3535 return FALSE;
3537 return TRUE;
3539 case KP_CLIENT_RANDOM:
3540 return copy_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom, (PCRYPT_DATA_BLOB)pbData);
3542 case KP_SERVER_RANDOM:
3543 return copy_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom, (PCRYPT_DATA_BLOB)pbData);
3545 default:
3546 SetLastError(NTE_BAD_TYPE);
3547 return FALSE;
3551 /******************************************************************************
3552 * CPGetKeyParam (RSAENH.@)
3554 * Query a key parameter.
3556 * PARAMS
3557 * hProv [I] The key container, which the key belongs to.
3558 * hHash [I] The key object that is to be queried.
3559 * dwParam [I] Specifies the parameter that is to be queried.
3560 * pbData [I] Pointer to the buffer where the parameter value will be stored.
3561 * pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
3562 * dwFlags [I] None currently defined.
3564 * RETURNS
3565 * Success: TRUE
3566 * Failure: FALSE
3568 * NOTES
3569 * Defined dwParam types are:
3570 * - KP_MODE: Values MODE_CBC, MODE_ECB, MODE_CFB.
3571 * - KP_MODE_BITS: Shift width for cipher feedback mode.
3572 * (Currently ignored by MS CSP's - always eight)
3573 * - KP_PERMISSIONS: Or'ed combination of CRYPT_ENCRYPT, CRYPT_DECRYPT,
3574 * CRYPT_EXPORT, CRYPT_READ, CRYPT_WRITE, CRYPT_MAC
3575 * - KP_IV: Initialization vector.
3576 * - KP_KEYLEN: Bitwidth of the key.
3577 * - KP_BLOCKLEN: Size of a block cipher block.
3578 * - KP_SALT: Salt value.
3580 BOOL WINAPI RSAENH_CPGetKeyParam(HCRYPTPROV hProv, HCRYPTKEY hKey, DWORD dwParam, BYTE *pbData,
3581 DWORD *pdwDataLen, DWORD dwFlags)
3583 CRYPTKEY *pCryptKey;
3584 DWORD dwValue;
3586 TRACE("(hProv=%08lx, hKey=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p dwFlags=%08x)\n",
3587 hProv, hKey, dwParam, pbData, pdwDataLen, dwFlags);
3589 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3591 SetLastError(NTE_BAD_UID);
3592 return FALSE;
3595 if (dwFlags) {
3596 SetLastError(NTE_BAD_FLAGS);
3597 return FALSE;
3600 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
3602 SetLastError(NTE_BAD_KEY);
3603 return FALSE;
3606 switch (dwParam)
3608 case KP_IV:
3609 return copy_param(pbData, pdwDataLen, pCryptKey->abInitVector,
3610 pCryptKey->dwBlockLen);
3612 case KP_SALT:
3613 switch (pCryptKey->aiAlgid) {
3614 case CALG_RC2:
3615 case CALG_RC4:
3616 return copy_param(pbData, pdwDataLen,
3617 &pCryptKey->abKeyValue[pCryptKey->dwKeyLen],
3618 pCryptKey->dwSaltLen);
3619 default:
3620 SetLastError(NTE_BAD_KEY);
3621 return FALSE;
3624 case KP_PADDING:
3625 dwValue = PKCS5_PADDING;
3626 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwValue, sizeof(DWORD));
3628 case KP_KEYLEN:
3629 dwValue = pCryptKey->dwKeyLen << 3;
3630 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwValue, sizeof(DWORD));
3632 case KP_EFFECTIVE_KEYLEN:
3633 if (pCryptKey->dwEffectiveKeyLen)
3634 dwValue = pCryptKey->dwEffectiveKeyLen;
3635 else
3636 dwValue = pCryptKey->dwKeyLen << 3;
3637 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwValue, sizeof(DWORD));
3639 case KP_BLOCKLEN:
3640 dwValue = pCryptKey->dwBlockLen << 3;
3641 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwValue, sizeof(DWORD));
3643 case KP_MODE:
3644 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptKey->dwMode, sizeof(DWORD));
3646 case KP_MODE_BITS:
3647 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptKey->dwModeBits,
3648 sizeof(DWORD));
3650 case KP_PERMISSIONS:
3651 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptKey->dwPermissions,
3652 sizeof(DWORD));
3654 case KP_ALGID:
3655 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptKey->aiAlgid, sizeof(DWORD));
3657 default:
3658 SetLastError(NTE_BAD_TYPE);
3659 return FALSE;
3663 /******************************************************************************
3664 * CPGetProvParam (RSAENH.@)
3666 * Query a CSP parameter.
3668 * PARAMS
3669 * hProv [I] The key container that is to be queried.
3670 * dwParam [I] Specifies the parameter that is to be queried.
3671 * pbData [I] Pointer to the buffer where the parameter value will be stored.
3672 * pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
3673 * dwFlags [I] CRYPT_FIRST: Start enumeration (for PP_ENUMALGS{_EX}).
3675 * RETURNS
3676 * Success: TRUE
3677 * Failure: FALSE
3678 * NOTES:
3679 * Defined dwParam types:
3680 * - PP_CONTAINER: Name of the key container.
3681 * - PP_NAME: Name of the cryptographic service provider.
3682 * - PP_SIG_KEYSIZE_INC: RSA signature keywidth granularity in bits.
3683 * - PP_KEYX_KEYSIZE_INC: RSA key-exchange keywidth granularity in bits.
3684 * - PP_ENUMALGS{_EX}: Query provider capabilities.
3685 * - PP_KEYSET_SEC_DESCR: Retrieve security descriptor on container.
3687 BOOL WINAPI RSAENH_CPGetProvParam(HCRYPTPROV hProv, DWORD dwParam, BYTE *pbData,
3688 DWORD *pdwDataLen, DWORD dwFlags)
3690 KEYCONTAINER *pKeyContainer;
3691 PROV_ENUMALGS provEnumalgs;
3692 DWORD dwTemp;
3693 HKEY hKey;
3695 /* This is for dwParam PP_CRYPT_COUNT_KEY_USE.
3696 * IE6 SP1 asks for it in the 'About' dialog.
3697 * Returning this BLOB seems to satisfy IE. The marked 0x00 seem
3698 * to be 'don't care's. If you know anything more specific about
3699 * this provider parameter, please report to wine-devel@winehq.org */
3700 static const BYTE abWTF[96] = {
3701 0xb0, 0x25, 0x63, 0x86, 0x9c, 0xab, 0xb6, 0x37,
3702 0xe8, 0x82, /**/0x00,/**/ 0x72, 0x06, 0xb2, /**/0x00,/**/ 0x3b,
3703 0x60, 0x35, /**/0x00,/**/ 0x3b, 0x88, 0xce, /**/0x00,/**/ 0x82,
3704 0xbc, 0x7a, /**/0x00,/**/ 0xb7, 0x4f, 0x7e, /**/0x00,/**/ 0xde,
3705 0x92, 0xf1, /**/0x00,/**/ 0x83, 0xea, 0x5e, /**/0x00,/**/ 0xc8,
3706 0x12, 0x1e, 0xd4, 0x06, 0xf7, 0x66, /**/0x00,/**/ 0x01,
3707 0x29, 0xa4, /**/0x00,/**/ 0xf8, 0x24, 0x0c, /**/0x00,/**/ 0x33,
3708 0x06, 0x80, /**/0x00,/**/ 0x02, 0x46, 0x0b, /**/0x00,/**/ 0x6d,
3709 0x5b, 0xca, /**/0x00,/**/ 0x9a, 0x10, 0xf0, /**/0x00,/**/ 0x05,
3710 0x19, 0xd0, /**/0x00,/**/ 0x2c, 0xf6, 0x27, /**/0x00,/**/ 0xaa,
3711 0x7c, 0x6f, /**/0x00,/**/ 0xb9, 0xd8, 0x72, /**/0x00,/**/ 0x03,
3712 0xf3, 0x81, /**/0x00,/**/ 0xfa, 0xe8, 0x26, /**/0x00,/**/ 0xca
3715 TRACE("(hProv=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p, dwFlags=%08x)\n",
3716 hProv, dwParam, pbData, pdwDataLen, dwFlags);
3718 if (!pdwDataLen) {
3719 SetLastError(ERROR_INVALID_PARAMETER);
3720 return FALSE;
3723 if (!(pKeyContainer = get_key_container(hProv)))
3725 /* MSDN: hProv not containing valid context handle */
3726 return FALSE;
3729 switch (dwParam)
3731 case PP_CONTAINER:
3732 case PP_UNIQUE_CONTAINER:/* MSDN says we can return the same value as PP_CONTAINER */
3733 return copy_param(pbData, pdwDataLen, (const BYTE*)pKeyContainer->szName,
3734 strlen(pKeyContainer->szName)+1);
3736 case PP_NAME:
3737 return copy_param(pbData, pdwDataLen, (const BYTE*)pKeyContainer->szProvName,
3738 strlen(pKeyContainer->szProvName)+1);
3740 case PP_PROVTYPE:
3741 dwTemp = PROV_RSA_FULL;
3742 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
3744 case PP_KEYSPEC:
3745 dwTemp = AT_SIGNATURE | AT_KEYEXCHANGE;
3746 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
3748 case PP_KEYSET_TYPE:
3749 dwTemp = pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET;
3750 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
3752 case PP_KEYSTORAGE:
3753 dwTemp = CRYPT_SEC_DESCR;
3754 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
3756 case PP_SIG_KEYSIZE_INC:
3757 case PP_KEYX_KEYSIZE_INC:
3758 dwTemp = 8;
3759 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
3761 case PP_IMPTYPE:
3762 dwTemp = CRYPT_IMPL_SOFTWARE;
3763 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
3765 case PP_VERSION:
3766 dwTemp = 0x00000200;
3767 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
3769 case PP_ENUMCONTAINERS:
3770 if ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) pKeyContainer->dwEnumContainersCtr = 0;
3772 if (!pbData) {
3773 *pdwDataLen = (DWORD)MAX_PATH + 1;
3774 return TRUE;
3777 if (!open_container_key("", dwFlags, KEY_READ, &hKey))
3779 SetLastError(ERROR_NO_MORE_ITEMS);
3780 return FALSE;
3783 dwTemp = *pdwDataLen;
3784 switch (RegEnumKeyExA(hKey, pKeyContainer->dwEnumContainersCtr, (LPSTR)pbData, &dwTemp,
3785 NULL, NULL, NULL, NULL))
3787 case ERROR_MORE_DATA:
3788 *pdwDataLen = (DWORD)MAX_PATH + 1;
3790 case ERROR_SUCCESS:
3791 pKeyContainer->dwEnumContainersCtr++;
3792 RegCloseKey(hKey);
3793 return TRUE;
3795 case ERROR_NO_MORE_ITEMS:
3796 default:
3797 SetLastError(ERROR_NO_MORE_ITEMS);
3798 RegCloseKey(hKey);
3799 return FALSE;
3802 case PP_ENUMALGS:
3803 case PP_ENUMALGS_EX:
3804 if (((pKeyContainer->dwEnumAlgsCtr >= RSAENH_MAX_ENUMALGS-1) ||
3805 (!aProvEnumAlgsEx[pKeyContainer->dwPersonality]
3806 [pKeyContainer->dwEnumAlgsCtr+1].aiAlgid)) &&
3807 ((dwFlags & CRYPT_FIRST) != CRYPT_FIRST))
3809 SetLastError(ERROR_NO_MORE_ITEMS);
3810 return FALSE;
3813 if (dwParam == PP_ENUMALGS) {
3814 if (pbData && (*pdwDataLen >= sizeof(PROV_ENUMALGS)))
3815 pKeyContainer->dwEnumAlgsCtr = ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) ?
3816 0 : pKeyContainer->dwEnumAlgsCtr+1;
3818 provEnumalgs.aiAlgid = aProvEnumAlgsEx
3819 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].aiAlgid;
3820 provEnumalgs.dwBitLen = aProvEnumAlgsEx
3821 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].dwDefaultLen;
3822 provEnumalgs.dwNameLen = aProvEnumAlgsEx
3823 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].dwNameLen;
3824 memcpy(provEnumalgs.szName, aProvEnumAlgsEx
3825 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].szName,
3826 20*sizeof(CHAR));
3828 return copy_param(pbData, pdwDataLen, (const BYTE*)&provEnumalgs,
3829 sizeof(PROV_ENUMALGS));
3830 } else {
3831 if (pbData && (*pdwDataLen >= sizeof(PROV_ENUMALGS_EX)))
3832 pKeyContainer->dwEnumAlgsCtr = ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) ?
3833 0 : pKeyContainer->dwEnumAlgsCtr+1;
3835 return copy_param(pbData, pdwDataLen,
3836 (const BYTE*)&aProvEnumAlgsEx
3837 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr],
3838 sizeof(PROV_ENUMALGS_EX));
3841 case PP_CRYPT_COUNT_KEY_USE: /* Asked for by IE About dialog */
3842 return copy_param(pbData, pdwDataLen, abWTF, sizeof(abWTF));
3844 case PP_KEYSET_SEC_DESCR:
3846 SECURITY_DESCRIPTOR *sd;
3847 DWORD err, len, flags = (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET);
3849 if (!open_container_key(pKeyContainer->szName, flags, KEY_READ, &hKey))
3851 SetLastError(NTE_BAD_KEYSET);
3852 return FALSE;
3855 err = GetSecurityInfo(hKey, SE_REGISTRY_KEY, dwFlags, NULL, NULL, NULL, NULL, (void **)&sd);
3856 RegCloseKey(hKey);
3857 if (err)
3859 SetLastError(err);
3860 return FALSE;
3863 len = GetSecurityDescriptorLength(sd);
3864 if (*pdwDataLen >= len) memcpy(pbData, sd, len);
3865 else SetLastError(ERROR_INSUFFICIENT_BUFFER);
3866 *pdwDataLen = len;
3868 LocalFree(sd);
3869 return TRUE;
3872 default:
3873 /* MSDN: Unknown parameter number in dwParam */
3874 SetLastError(NTE_BAD_TYPE);
3875 return FALSE;
3879 /******************************************************************************
3880 * CPDeriveKey (RSAENH.@)
3882 * Derives a key from a hash value.
3884 * PARAMS
3885 * hProv [I] Key container for which a key is to be generated.
3886 * Algid [I] Crypto algorithm identifier for the key to be generated.
3887 * hBaseData [I] Hash from whose value the key will be derived.
3888 * dwFlags [I] See Notes.
3889 * phKey [O] The generated key.
3891 * RETURNS
3892 * Success: TRUE
3893 * Failure: FALSE
3895 * NOTES
3896 * Defined flags:
3897 * - CRYPT_EXPORTABLE: Key can be exported.
3898 * - CRYPT_NO_SALT: No salt is used for 40 bit keys.
3899 * - CRYPT_CREATE_SALT: Use remaining bits as salt value.
3901 BOOL WINAPI RSAENH_CPDeriveKey(HCRYPTPROV hProv, ALG_ID Algid, HCRYPTHASH hBaseData,
3902 DWORD dwFlags, HCRYPTKEY *phKey)
3904 CRYPTKEY *pCryptKey, *pMasterKey;
3905 CRYPTHASH *pCryptHash;
3906 BYTE abHashValue[RSAENH_MAX_HASH_SIZE*2];
3907 DWORD dwLen;
3909 TRACE("(hProv=%08lx, Algid=%d, hBaseData=%08lx, dwFlags=%08x phKey=%p)\n", hProv, Algid,
3910 hBaseData, dwFlags, phKey);
3912 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3914 SetLastError(NTE_BAD_UID);
3915 return FALSE;
3918 if (!lookup_handle(&handle_table, hBaseData, RSAENH_MAGIC_HASH,
3919 (OBJECTHDR**)&pCryptHash))
3921 SetLastError(NTE_BAD_HASH);
3922 return FALSE;
3925 if (!phKey)
3927 SetLastError(ERROR_INVALID_PARAMETER);
3928 return FALSE;
3931 switch (GET_ALG_CLASS(Algid))
3933 case ALG_CLASS_DATA_ENCRYPT:
3935 int need_padding, copy_len;
3936 *phKey = new_key(hProv, Algid, dwFlags, &pCryptKey);
3937 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
3940 * We derive the key material from the hash.
3941 * If the hash value is not large enough for the claimed key, we have to construct
3942 * a larger binary value based on the hash. This is documented in MSDN: CryptDeriveKey.
3944 dwLen = RSAENH_MAX_HASH_SIZE;
3945 RSAENH_CPGetHashParam(pCryptHash->hProv, hBaseData, HP_HASHVAL, abHashValue, &dwLen, 0);
3948 * The usage of padding seems to vary from algorithm to algorithm.
3949 * For now the only different case found was for AES with 128 bit key.
3951 switch(Algid)
3953 case CALG_AES_128:
3954 /* To reduce the chance of regressions we will only deviate
3955 * from the old behavior for the tested hash lengths */
3956 if (dwLen == 16 || dwLen == 20)
3958 need_padding = 1;
3959 break;
3961 default:
3962 need_padding = dwLen < pCryptKey->dwKeyLen;
3965 copy_len = pCryptKey->dwKeyLen;
3966 if (need_padding)
3968 BYTE pad1[RSAENH_HMAC_DEF_PAD_LEN], pad2[RSAENH_HMAC_DEF_PAD_LEN];
3969 BYTE old_hashval[RSAENH_MAX_HASH_SIZE];
3970 DWORD i;
3972 memcpy(old_hashval, pCryptHash->abHashValue, RSAENH_MAX_HASH_SIZE);
3974 for (i=0; i<RSAENH_HMAC_DEF_PAD_LEN; i++) {
3975 pad1[i] = RSAENH_HMAC_DEF_IPAD_CHAR ^ (i<dwLen ? abHashValue[i] : 0);
3976 pad2[i] = RSAENH_HMAC_DEF_OPAD_CHAR ^ (i<dwLen ? abHashValue[i] : 0);
3979 init_hash(pCryptHash);
3980 update_hash(pCryptHash, pad1, RSAENH_HMAC_DEF_PAD_LEN);
3981 finalize_hash(pCryptHash);
3982 memcpy(abHashValue, pCryptHash->abHashValue, pCryptHash->dwHashSize);
3984 init_hash(pCryptHash);
3985 update_hash(pCryptHash, pad2, RSAENH_HMAC_DEF_PAD_LEN);
3986 finalize_hash(pCryptHash);
3987 memcpy(abHashValue+pCryptHash->dwHashSize, pCryptHash->abHashValue,
3988 pCryptHash->dwHashSize);
3990 memcpy(pCryptHash->abHashValue, old_hashval, RSAENH_MAX_HASH_SIZE);
3993 * Padding was not required, we have more hash than needed.
3994 * Do we need to use the remaining hash as salt?
3996 else if((dwFlags & CRYPT_CREATE_SALT) &&
3997 (Algid == CALG_RC2 || Algid == CALG_RC4))
3999 copy_len += pCryptKey->dwSaltLen;
4002 memcpy(pCryptKey->abKeyValue, abHashValue,
4003 RSAENH_MIN(copy_len, sizeof(pCryptKey->abKeyValue)));
4004 break;
4006 case ALG_CLASS_MSG_ENCRYPT:
4007 if (!lookup_handle(&handle_table, pCryptHash->hKey, RSAENH_MAGIC_KEY,
4008 (OBJECTHDR**)&pMasterKey))
4010 SetLastError(NTE_FAIL); /* FIXME error code */
4011 return FALSE;
4014 switch (Algid)
4016 /* See RFC 2246, chapter 6.3 Key calculation */
4017 case CALG_SCHANNEL_ENC_KEY:
4018 if (!pMasterKey->siSChannelInfo.saEncAlg.Algid ||
4019 !pMasterKey->siSChannelInfo.saEncAlg.cBits)
4021 SetLastError(NTE_BAD_FLAGS);
4022 return FALSE;
4024 *phKey = new_key(hProv, pMasterKey->siSChannelInfo.saEncAlg.Algid,
4025 MAKELONG(LOWORD(dwFlags),pMasterKey->siSChannelInfo.saEncAlg.cBits),
4026 &pCryptKey);
4027 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
4028 memcpy(pCryptKey->abKeyValue,
4029 pCryptHash->abHashValue + (
4030 2 * (pMasterKey->siSChannelInfo.saMACAlg.cBits / 8) +
4031 ((dwFlags & CRYPT_SERVER) ?
4032 (pMasterKey->siSChannelInfo.saEncAlg.cBits / 8) : 0)),
4033 pMasterKey->siSChannelInfo.saEncAlg.cBits / 8);
4034 memcpy(pCryptKey->abInitVector,
4035 pCryptHash->abHashValue + (
4036 2 * (pMasterKey->siSChannelInfo.saMACAlg.cBits / 8) +
4037 2 * (pMasterKey->siSChannelInfo.saEncAlg.cBits / 8) +
4038 ((dwFlags & CRYPT_SERVER) ? pCryptKey->dwBlockLen : 0)),
4039 pCryptKey->dwBlockLen);
4040 break;
4042 case CALG_SCHANNEL_MAC_KEY:
4043 *phKey = new_key(hProv, Algid,
4044 MAKELONG(LOWORD(dwFlags),pMasterKey->siSChannelInfo.saMACAlg.cBits),
4045 &pCryptKey);
4046 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
4047 memcpy(pCryptKey->abKeyValue,
4048 pCryptHash->abHashValue + ((dwFlags & CRYPT_SERVER) ?
4049 pMasterKey->siSChannelInfo.saMACAlg.cBits / 8 : 0),
4050 pMasterKey->siSChannelInfo.saMACAlg.cBits / 8);
4051 break;
4053 default:
4054 SetLastError(NTE_BAD_ALGID);
4055 return FALSE;
4057 break;
4059 default:
4060 SetLastError(NTE_BAD_ALGID);
4061 return FALSE;
4064 setup_key(pCryptKey);
4065 return TRUE;
4068 /******************************************************************************
4069 * CPGetUserKey (RSAENH.@)
4071 * Returns a handle to the user's private key-exchange- or signature-key.
4073 * PARAMS
4074 * hProv [I] The key container from which a user key is requested.
4075 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
4076 * phUserKey [O] Handle to the requested key or INVALID_HANDLE_VALUE in case of failure.
4078 * RETURNS
4079 * Success: TRUE.
4080 * Failure: FALSE.
4082 * NOTE
4083 * A newly created key container does not contain private user key. Create them with CPGenKey.
4085 BOOL WINAPI RSAENH_CPGetUserKey(HCRYPTPROV hProv, DWORD dwKeySpec, HCRYPTKEY *phUserKey)
4087 KEYCONTAINER *pKeyContainer;
4089 TRACE("(hProv=%08lx, dwKeySpec=%08x, phUserKey=%p)\n", hProv, dwKeySpec, phUserKey);
4091 if (!(pKeyContainer = get_key_container(hProv)))
4093 /* MSDN: hProv not containing valid context handle */
4094 return FALSE;
4097 switch (dwKeySpec)
4099 case AT_KEYEXCHANGE:
4100 copy_handle(&handle_table, pKeyContainer->hKeyExchangeKeyPair, RSAENH_MAGIC_KEY,
4101 phUserKey);
4102 break;
4104 case AT_SIGNATURE:
4105 copy_handle(&handle_table, pKeyContainer->hSignatureKeyPair, RSAENH_MAGIC_KEY,
4106 phUserKey);
4107 break;
4109 default:
4110 *phUserKey = (HCRYPTKEY)INVALID_HANDLE_VALUE;
4113 if (*phUserKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
4115 /* MSDN: dwKeySpec parameter specifies nonexistent key */
4116 SetLastError(NTE_NO_KEY);
4117 return FALSE;
4120 return TRUE;
4123 /******************************************************************************
4124 * CPHashData (RSAENH.@)
4126 * Updates a hash object with the given data.
4128 * PARAMS
4129 * hProv [I] Key container to which the hash object belongs.
4130 * hHash [I] Hash object which is to be updated.
4131 * pbData [I] Pointer to data with which the hash object is to be updated.
4132 * dwDataLen [I] Length of the data.
4133 * dwFlags [I] Currently none defined.
4135 * RETURNS
4136 * Success: TRUE.
4137 * Failure: FALSE.
4139 * NOTES
4140 * The actual hash value is queried with CPGetHashParam, which will finalize
4141 * the hash. Updating a finalized hash will fail with a last error NTE_BAD_HASH_STATE.
4143 BOOL WINAPI RSAENH_CPHashData(HCRYPTPROV hProv, HCRYPTHASH hHash, const BYTE *pbData,
4144 DWORD dwDataLen, DWORD dwFlags)
4146 CRYPTHASH *pCryptHash;
4148 TRACE("(hProv=%08lx, hHash=%08lx, pbData=%p, dwDataLen=%d, dwFlags=%08x)\n",
4149 hProv, hHash, pbData, dwDataLen, dwFlags);
4151 if (dwFlags & ~CRYPT_USERDATA)
4153 SetLastError(NTE_BAD_FLAGS);
4154 return FALSE;
4157 if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH,
4158 (OBJECTHDR**)&pCryptHash))
4160 SetLastError(NTE_BAD_HASH);
4161 return FALSE;
4164 if (!get_algid_info(hProv, pCryptHash->aiAlgid) || pCryptHash->aiAlgid == CALG_SSL3_SHAMD5)
4166 SetLastError(NTE_BAD_ALGID);
4167 return FALSE;
4170 if (pCryptHash->dwState != RSAENH_HASHSTATE_HASHING)
4172 SetLastError(NTE_BAD_HASH_STATE);
4173 return FALSE;
4176 update_hash(pCryptHash, pbData, dwDataLen);
4177 return TRUE;
4180 /******************************************************************************
4181 * CPHashSessionKey (RSAENH.@)
4183 * Updates a hash object with the binary representation of a symmetric key.
4185 * PARAMS
4186 * hProv [I] Key container to which the hash object belongs.
4187 * hHash [I] Hash object which is to be updated.
4188 * hKey [I] The symmetric key, whose binary value will be added to the hash.
4189 * dwFlags [I] CRYPT_LITTLE_ENDIAN, if the binary key value shall be interpreted as little endian.
4191 * RETURNS
4192 * Success: TRUE.
4193 * Failure: FALSE.
4195 BOOL WINAPI RSAENH_CPHashSessionKey(HCRYPTPROV hProv, HCRYPTHASH hHash, HCRYPTKEY hKey,
4196 DWORD dwFlags)
4198 BYTE abKeyValue[RSAENH_MAX_KEY_SIZE], bTemp;
4199 CRYPTKEY *pKey;
4200 DWORD i;
4202 TRACE("(hProv=%08lx, hHash=%08lx, hKey=%08lx, dwFlags=%08x)\n", hProv, hHash, hKey, dwFlags);
4204 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pKey) ||
4205 (GET_ALG_CLASS(pKey->aiAlgid) != ALG_CLASS_DATA_ENCRYPT))
4207 SetLastError(NTE_BAD_KEY);
4208 return FALSE;
4211 if (dwFlags & ~CRYPT_LITTLE_ENDIAN) {
4212 SetLastError(NTE_BAD_FLAGS);
4213 return FALSE;
4216 memcpy(abKeyValue, pKey->abKeyValue, pKey->dwKeyLen);
4217 if (!(dwFlags & CRYPT_LITTLE_ENDIAN)) {
4218 for (i=0; i<pKey->dwKeyLen/2; i++) {
4219 bTemp = abKeyValue[i];
4220 abKeyValue[i] = abKeyValue[pKey->dwKeyLen-i-1];
4221 abKeyValue[pKey->dwKeyLen-i-1] = bTemp;
4225 return RSAENH_CPHashData(hProv, hHash, abKeyValue, pKey->dwKeyLen, 0);
4228 /******************************************************************************
4229 * CPReleaseContext (RSAENH.@)
4231 * Release a key container.
4233 * PARAMS
4234 * hProv [I] Key container to be released.
4235 * dwFlags [I] Currently none defined.
4237 * RETURNS
4238 * Success: TRUE
4239 * Failure: FALSE
4241 BOOL WINAPI RSAENH_CPReleaseContext(HCRYPTPROV hProv, DWORD dwFlags)
4243 TRACE("(hProv=%08lx, dwFlags=%08x)\n", hProv, dwFlags);
4245 if (!release_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
4247 /* MSDN: hProv not containing valid context handle */
4248 SetLastError(NTE_BAD_UID);
4249 return FALSE;
4252 if (dwFlags) {
4253 SetLastError(NTE_BAD_FLAGS);
4254 return FALSE;
4257 return TRUE;
4260 /******************************************************************************
4261 * CPSetHashParam (RSAENH.@)
4263 * Set a parameter of a hash object
4265 * PARAMS
4266 * hProv [I] The key container to which the key belongs.
4267 * hHash [I] The hash object for which a parameter is to be set.
4268 * dwParam [I] Parameter type. See Notes.
4269 * pbData [I] Pointer to the parameter value.
4270 * dwFlags [I] Currently none defined.
4272 * RETURNS
4273 * Success: TRUE.
4274 * Failure: FALSE.
4276 * NOTES
4277 * Currently only the HP_HMAC_INFO dwParam type is defined.
4278 * The HMAC_INFO struct will be deep copied into the hash object.
4279 * See Internet RFC 2104 for details on the HMAC algorithm.
4281 BOOL WINAPI RSAENH_CPSetHashParam(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwParam,
4282 BYTE *pbData, DWORD dwFlags)
4284 CRYPTHASH *pCryptHash;
4285 CRYPTKEY *pCryptKey;
4286 DWORD i;
4288 TRACE("(hProv=%08lx, hHash=%08lx, dwParam=%08x, pbData=%p, dwFlags=%08x)\n",
4289 hProv, hHash, dwParam, pbData, dwFlags);
4291 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
4293 SetLastError(NTE_BAD_UID);
4294 return FALSE;
4297 if (dwFlags) {
4298 SetLastError(NTE_BAD_FLAGS);
4299 return FALSE;
4302 if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH,
4303 (OBJECTHDR**)&pCryptHash))
4305 SetLastError(NTE_BAD_HASH);
4306 return FALSE;
4309 switch (dwParam) {
4310 case HP_HMAC_INFO:
4311 free_hmac_info(pCryptHash->pHMACInfo);
4312 if (!copy_hmac_info(&pCryptHash->pHMACInfo, (PHMAC_INFO)pbData)) return FALSE;
4314 if (!lookup_handle(&handle_table, pCryptHash->hKey, RSAENH_MAGIC_KEY,
4315 (OBJECTHDR**)&pCryptKey))
4317 SetLastError(NTE_FAIL); /* FIXME: correct error code? */
4318 return FALSE;
4321 if (pCryptKey->aiAlgid == CALG_HMAC && !pCryptKey->dwKeyLen) {
4322 HCRYPTHASH hKeyHash;
4323 DWORD keyLen;
4325 if (!RSAENH_CPCreateHash(hProv, ((PHMAC_INFO)pbData)->HashAlgid, 0, 0,
4326 &hKeyHash))
4327 return FALSE;
4328 if (!RSAENH_CPHashData(hProv, hKeyHash, pCryptKey->blobHmacKey.pbData,
4329 pCryptKey->blobHmacKey.cbData, 0))
4331 RSAENH_CPDestroyHash(hProv, hKeyHash);
4332 return FALSE;
4334 keyLen = sizeof(pCryptKey->abKeyValue);
4335 if (!RSAENH_CPGetHashParam(hProv, hKeyHash, HP_HASHVAL, pCryptKey->abKeyValue,
4336 &keyLen, 0))
4338 RSAENH_CPDestroyHash(hProv, hKeyHash);
4339 return FALSE;
4341 pCryptKey->dwKeyLen = keyLen;
4342 RSAENH_CPDestroyHash(hProv, hKeyHash);
4344 for (i=0; i<RSAENH_MIN(pCryptKey->dwKeyLen,pCryptHash->pHMACInfo->cbInnerString); i++) {
4345 pCryptHash->pHMACInfo->pbInnerString[i] ^= pCryptKey->abKeyValue[i];
4347 for (i=0; i<RSAENH_MIN(pCryptKey->dwKeyLen,pCryptHash->pHMACInfo->cbOuterString); i++) {
4348 pCryptHash->pHMACInfo->pbOuterString[i] ^= pCryptKey->abKeyValue[i];
4351 init_hash(pCryptHash);
4352 return TRUE;
4354 case HP_HASHVAL:
4355 memcpy(pCryptHash->abHashValue, pbData, pCryptHash->dwHashSize);
4356 pCryptHash->dwState = RSAENH_HASHSTATE_FINISHED;
4357 return TRUE;
4359 case HP_TLS1PRF_SEED:
4360 return copy_data_blob(&pCryptHash->tpPRFParams.blobSeed, (PCRYPT_DATA_BLOB)pbData);
4362 case HP_TLS1PRF_LABEL:
4363 return copy_data_blob(&pCryptHash->tpPRFParams.blobLabel, (PCRYPT_DATA_BLOB)pbData);
4365 default:
4366 SetLastError(NTE_BAD_TYPE);
4367 return FALSE;
4371 /******************************************************************************
4372 * CPSetProvParam (RSAENH.@)
4374 BOOL WINAPI RSAENH_CPSetProvParam(HCRYPTPROV hProv, DWORD dwParam, BYTE *pbData, DWORD dwFlags)
4376 KEYCONTAINER *pKeyContainer;
4377 HKEY hKey;
4379 TRACE("(hProv=%08lx, dwParam=%08x, pbData=%p, dwFlags=%08x)\n", hProv, dwParam, pbData, dwFlags);
4381 if (!(pKeyContainer = get_key_container(hProv)))
4382 return FALSE;
4384 switch (dwParam)
4386 case PP_KEYSET_SEC_DESCR:
4388 SECURITY_DESCRIPTOR *sd = (SECURITY_DESCRIPTOR *)pbData;
4389 DWORD err, flags = (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET);
4390 BOOL def, present;
4391 REGSAM access = WRITE_DAC | WRITE_OWNER | ACCESS_SYSTEM_SECURITY;
4392 PSID owner = NULL, group = NULL;
4393 PACL dacl = NULL, sacl = NULL;
4395 if (!open_container_key(pKeyContainer->szName, flags, access, &hKey))
4397 SetLastError(NTE_BAD_KEYSET);
4398 return FALSE;
4401 if ((dwFlags & OWNER_SECURITY_INFORMATION && !GetSecurityDescriptorOwner(sd, &owner, &def)) ||
4402 (dwFlags & GROUP_SECURITY_INFORMATION && !GetSecurityDescriptorGroup(sd, &group, &def)) ||
4403 (dwFlags & DACL_SECURITY_INFORMATION && !GetSecurityDescriptorDacl(sd, &present, &dacl, &def)) ||
4404 (dwFlags & SACL_SECURITY_INFORMATION && !GetSecurityDescriptorSacl(sd, &present, &sacl, &def)))
4406 RegCloseKey(hKey);
4407 return FALSE;
4410 err = SetSecurityInfo(hKey, SE_REGISTRY_KEY, dwFlags, owner, group, dacl, sacl);
4411 RegCloseKey(hKey);
4412 if (err)
4414 SetLastError(err);
4415 return FALSE;
4417 return TRUE;
4419 default:
4420 FIXME("unimplemented parameter %08x\n", dwParam);
4421 return FALSE;
4425 /******************************************************************************
4426 * CPSignHash (RSAENH.@)
4428 * Sign a hash object
4430 * PARAMS
4431 * hProv [I] The key container, to which the hash object belongs.
4432 * hHash [I] The hash object to be signed.
4433 * dwKeySpec [I] AT_SIGNATURE or AT_KEYEXCHANGE: Key used to generate the signature.
4434 * sDescription [I] Should be NULL for security reasons.
4435 * dwFlags [I] 0, CRYPT_NOHASHOID or CRYPT_X931_FORMAT: Format of the signature.
4436 * pbSignature [O] Buffer, to which the signature will be stored. May be NULL to query SigLen.
4437 * pdwSigLen [I/O] Size of the buffer (in), Length of the signature (out)
4439 * RETURNS
4440 * Success: TRUE
4441 * Failure: FALSE
4443 BOOL WINAPI RSAENH_CPSignHash(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwKeySpec,
4444 LPCWSTR sDescription, DWORD dwFlags, BYTE *pbSignature,
4445 DWORD *pdwSigLen)
4447 HCRYPTKEY hCryptKey = (HCRYPTKEY)INVALID_HANDLE_VALUE;
4448 CRYPTKEY *pCryptKey;
4449 DWORD dwHashLen;
4450 BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
4451 ALG_ID aiAlgid;
4452 BOOL ret = FALSE;
4454 TRACE("(hProv=%08lx, hHash=%08lx, dwKeySpec=%08x, sDescription=%s, dwFlags=%08x, "
4455 "pbSignature=%p, pdwSigLen=%p)\n", hProv, hHash, dwKeySpec, debugstr_w(sDescription),
4456 dwFlags, pbSignature, pdwSigLen);
4458 if (dwFlags & ~(CRYPT_NOHASHOID|CRYPT_X931_FORMAT)) {
4459 SetLastError(NTE_BAD_FLAGS);
4460 return FALSE;
4463 if (!RSAENH_CPGetUserKey(hProv, dwKeySpec, &hCryptKey)) return FALSE;
4465 if (!lookup_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY,
4466 (OBJECTHDR**)&pCryptKey))
4468 SetLastError(NTE_NO_KEY);
4469 goto out;
4472 if (!pbSignature) {
4473 *pdwSigLen = pCryptKey->dwKeyLen;
4474 ret = TRUE;
4475 goto out;
4477 if (pCryptKey->dwKeyLen > *pdwSigLen)
4479 SetLastError(ERROR_MORE_DATA);
4480 *pdwSigLen = pCryptKey->dwKeyLen;
4481 goto out;
4483 *pdwSigLen = pCryptKey->dwKeyLen;
4485 if (sDescription) {
4486 if (!RSAENH_CPHashData(hProv, hHash, (const BYTE*)sDescription,
4487 (DWORD)lstrlenW(sDescription)*sizeof(WCHAR), 0))
4489 goto out;
4493 dwHashLen = sizeof(DWORD);
4494 if (!RSAENH_CPGetHashParam(hProv, hHash, HP_ALGID, (BYTE*)&aiAlgid, &dwHashLen, 0)) goto out;
4496 dwHashLen = RSAENH_MAX_HASH_SIZE;
4497 if (!RSAENH_CPGetHashParam(hProv, hHash, HP_HASHVAL, abHashValue, &dwHashLen, 0)) goto out;
4500 if (!build_hash_signature(pbSignature, *pdwSigLen, aiAlgid, abHashValue, dwHashLen, dwFlags)) {
4501 goto out;
4504 ret = encrypt_block_impl(pCryptKey->aiAlgid, PK_PRIVATE, &pCryptKey->context, pbSignature, pbSignature, RSAENH_ENCRYPT);
4505 out:
4506 RSAENH_CPDestroyKey(hProv, hCryptKey);
4507 return ret;
4510 /******************************************************************************
4511 * CPVerifySignature (RSAENH.@)
4513 * Verify the signature of a hash object.
4515 * PARAMS
4516 * hProv [I] The key container, to which the hash belongs.
4517 * hHash [I] The hash for which the signature is verified.
4518 * pbSignature [I] The binary signature.
4519 * dwSigLen [I] Length of the signature BLOB.
4520 * hPubKey [I] Public key used to verify the signature.
4521 * sDescription [I] Should be NULL for security reasons.
4522 * dwFlags [I] 0, CRYPT_NOHASHOID or CRYPT_X931_FORMAT: Format of the signature.
4524 * RETURNS
4525 * Success: TRUE (Signature is valid)
4526 * Failure: FALSE (GetLastError() == NTE_BAD_SIGNATURE, if signature is invalid)
4528 BOOL WINAPI RSAENH_CPVerifySignature(HCRYPTPROV hProv, HCRYPTHASH hHash, const BYTE *pbSignature,
4529 DWORD dwSigLen, HCRYPTKEY hPubKey, LPCWSTR sDescription,
4530 DWORD dwFlags)
4532 BYTE *pbConstructed = NULL, *pbDecrypted = NULL;
4533 CRYPTKEY *pCryptKey;
4534 DWORD dwHashLen;
4535 ALG_ID aiAlgid;
4536 BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
4537 BOOL res = FALSE;
4539 TRACE("(hProv=%08lx, hHash=%08lx, pbSignature=%p, dwSigLen=%d, hPubKey=%08lx, sDescription=%s, "
4540 "dwFlags=%08x)\n", hProv, hHash, pbSignature, dwSigLen, hPubKey, debugstr_w(sDescription),
4541 dwFlags);
4543 if (dwFlags & ~(CRYPT_NOHASHOID|CRYPT_X931_FORMAT)) {
4544 SetLastError(NTE_BAD_FLAGS);
4545 return FALSE;
4548 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
4550 SetLastError(NTE_BAD_UID);
4551 return FALSE;
4554 if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY,
4555 (OBJECTHDR**)&pCryptKey))
4557 SetLastError(NTE_BAD_KEY);
4558 return FALSE;
4561 /* in Microsoft implementation, the signature length is checked before
4562 * the signature pointer.
4564 if (dwSigLen != pCryptKey->dwKeyLen)
4566 SetLastError(NTE_BAD_SIGNATURE);
4567 return FALSE;
4570 if (!hHash || !pbSignature)
4572 SetLastError(ERROR_INVALID_PARAMETER);
4573 return FALSE;
4576 if (sDescription) {
4577 if (!RSAENH_CPHashData(hProv, hHash, (const BYTE*)sDescription,
4578 (DWORD)lstrlenW(sDescription)*sizeof(WCHAR), 0))
4580 return FALSE;
4584 dwHashLen = sizeof(DWORD);
4585 if (!RSAENH_CPGetHashParam(hProv, hHash, HP_ALGID, (BYTE*)&aiAlgid, &dwHashLen, 0)) return FALSE;
4587 dwHashLen = RSAENH_MAX_HASH_SIZE;
4588 if (!RSAENH_CPGetHashParam(hProv, hHash, HP_HASHVAL, abHashValue, &dwHashLen, 0)) return FALSE;
4590 pbConstructed = HeapAlloc(GetProcessHeap(), 0, dwSigLen);
4591 if (!pbConstructed) {
4592 SetLastError(NTE_NO_MEMORY);
4593 goto cleanup;
4596 pbDecrypted = HeapAlloc(GetProcessHeap(), 0, dwSigLen);
4597 if (!pbDecrypted) {
4598 SetLastError(NTE_NO_MEMORY);
4599 goto cleanup;
4602 if (!encrypt_block_impl(pCryptKey->aiAlgid, PK_PUBLIC, &pCryptKey->context, pbSignature, pbDecrypted,
4603 RSAENH_DECRYPT))
4605 goto cleanup;
4608 if (build_hash_signature(pbConstructed, dwSigLen, aiAlgid, abHashValue, dwHashLen, dwFlags) &&
4609 !memcmp(pbDecrypted, pbConstructed, dwSigLen)) {
4610 res = TRUE;
4611 goto cleanup;
4614 if (!(dwFlags & CRYPT_NOHASHOID) &&
4615 build_hash_signature(pbConstructed, dwSigLen, aiAlgid, abHashValue, dwHashLen, dwFlags|CRYPT_NOHASHOID) &&
4616 !memcmp(pbDecrypted, pbConstructed, dwSigLen)) {
4617 res = TRUE;
4618 goto cleanup;
4621 SetLastError(NTE_BAD_SIGNATURE);
4623 cleanup:
4624 HeapFree(GetProcessHeap(), 0, pbConstructed);
4625 HeapFree(GetProcessHeap(), 0, pbDecrypted);
4626 return res;
4629 /******************************************************************************
4630 * DllRegisterServer (RSAENH.@)
4632 HRESULT WINAPI DllRegisterServer(void)
4634 return __wine_register_resources( instance );
4637 /******************************************************************************
4638 * DllUnregisterServer (RSAENH.@)
4640 HRESULT WINAPI DllUnregisterServer(void)
4642 return __wine_unregister_resources( instance );