rsaenh: Avoid potential buffer overflows in registry key name.
[wine.git] / dlls / rsaenh / rsaenh.c
blob3db828638b9e4ba96d9a00a820c926cb7356d4bb
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 static const PROV_ENUMALGS_EX aProvEnumAlgsEx[5][RSAENH_MAX_ENUMALGS+1] =
167 {CALG_RC2, 40, 40, 56,0, 4,"RC2", 24,"RSA Data Security's RC2"},
168 {CALG_RC4, 40, 40, 56,0, 4,"RC4", 24,"RSA Data Security's RC4"},
169 {CALG_DES, 56, 56, 56,0, 4,"DES", 31,"Data Encryption Standard (DES)"},
170 {CALG_SHA, 160,160, 160,CRYPT_FLAG_SIGNING, 6,"SHA-1", 30,"Secure Hash Algorithm (SHA-1)"},
171 {CALG_MD2, 128,128, 128,CRYPT_FLAG_SIGNING, 4,"MD2", 23,"Message Digest 2 (MD2)"},
172 {CALG_MD4, 128,128, 128,CRYPT_FLAG_SIGNING, 4,"MD4", 23,"Message Digest 4 (MD4)"},
173 {CALG_MD5, 128,128, 128,CRYPT_FLAG_SIGNING, 4,"MD5", 23,"Message Digest 5 (MD5)"},
174 {CALG_SSL3_SHAMD5,288,288,288,0, 12,"SSL3 SHAMD5",12,"SSL3 SHAMD5"},
175 {CALG_MAC, 0, 0, 0,0, 4,"MAC", 28,"Message Authentication Code"},
176 {CALG_RSA_SIGN, 512,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_SIGN",14,"RSA Signature"},
177 {CALG_RSA_KEYX, 512,384, 1024,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_KEYX",17,"RSA Key Exchange"},
178 {CALG_HMAC, 0, 0, 0,0, 5,"HMAC", 18,"Hugo's MAC (HMAC)"},
179 {0, 0, 0, 0,0, 1,"", 1,""}
182 {CALG_RC2, 128, 40, 128,0, 4,"RC2", 24,"RSA Data Security's RC2"},
183 {CALG_RC4, 128, 40, 128,0, 4,"RC4", 24,"RSA Data Security's RC4"},
184 {CALG_DES, 56, 56, 56,0, 4,"DES", 31,"Data Encryption Standard (DES)"},
185 {CALG_3DES_112, 112,112, 112,0, 13,"3DES TWO KEY",19,"Two Key Triple DES"},
186 {CALG_3DES, 168,168, 168,0, 5,"3DES", 21,"Three Key Triple DES"},
187 {CALG_SHA, 160,160, 160,CRYPT_FLAG_SIGNING, 6,"SHA-1", 30,"Secure Hash Algorithm (SHA-1)"},
188 {CALG_MD2, 128,128, 128,CRYPT_FLAG_SIGNING, 4,"MD2", 23,"Message Digest 2 (MD2)"},
189 {CALG_MD4, 128,128, 128,CRYPT_FLAG_SIGNING, 4,"MD4", 23,"Message Digest 4 (MD4)"},
190 {CALG_MD5, 128,128, 128,CRYPT_FLAG_SIGNING, 4,"MD5", 23,"Message Digest 5 (MD5)"},
191 {CALG_SSL3_SHAMD5,288,288,288,0, 12,"SSL3 SHAMD5",12,"SSL3 SHAMD5"},
192 {CALG_MAC, 0, 0, 0,0, 4,"MAC", 28,"Message Authentication Code"},
193 {CALG_RSA_SIGN,1024,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_SIGN",14,"RSA Signature"},
194 {CALG_RSA_KEYX,1024,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_KEYX",17,"RSA Key Exchange"},
195 {CALG_HMAC, 0, 0, 0,0, 5,"HMAC", 18,"Hugo's MAC (HMAC)"},
196 {0, 0, 0, 0,0, 1,"", 1,""}
199 {CALG_RC2, 128, 40, 128,0, 4,"RC2", 24,"RSA Data Security's RC2"},
200 {CALG_RC4, 128, 40, 128,0, 4,"RC4", 24,"RSA Data Security's RC4"},
201 {CALG_DES, 56, 56, 56,0, 4,"DES", 31,"Data Encryption Standard (DES)"},
202 {CALG_3DES_112, 112,112, 112,0, 13,"3DES TWO KEY",19,"Two Key Triple DES"},
203 {CALG_3DES, 168,168, 168,0, 5,"3DES", 21,"Three Key Triple DES"},
204 {CALG_SHA, 160,160, 160,CRYPT_FLAG_SIGNING, 6,"SHA-1", 30,"Secure Hash Algorithm (SHA-1)"},
205 {CALG_MD2, 128,128, 128,CRYPT_FLAG_SIGNING, 4,"MD2", 23,"Message Digest 2 (MD2)"},
206 {CALG_MD4, 128,128, 128,CRYPT_FLAG_SIGNING, 4,"MD4", 23,"Message Digest 4 (MD4)"},
207 {CALG_MD5, 128,128, 128,CRYPT_FLAG_SIGNING, 4,"MD5", 23,"Message Digest 5 (MD5)"},
208 {CALG_SSL3_SHAMD5,288,288,288,0, 12,"SSL3 SHAMD5",12,"SSL3 SHAMD5"},
209 {CALG_MAC, 0, 0, 0,0, 4,"MAC", 28,"Message Authentication Code"},
210 {CALG_RSA_SIGN,1024,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_SIGN",14,"RSA Signature"},
211 {CALG_RSA_KEYX,1024,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_KEYX",17,"RSA Key Exchange"},
212 {CALG_HMAC, 0, 0, 0,0, 5,"HMAC", 18,"Hugo's MAC (HMAC)"},
213 {0, 0, 0, 0,0, 1,"", 1,""}
216 {CALG_RC2, 128, 40, 128,RSAENH_PCT1_SSL2_SSL3_TLS1, 4,"RC2", 24,"RSA Data Security's RC2"},
217 {CALG_RC4, 128, 40, 128,RSAENH_PCT1_SSL2_SSL3_TLS1, 4,"RC4", 24,"RSA Data Security's RC4"},
218 {CALG_DES, 56, 56, 56,RSAENH_PCT1_SSL2_SSL3_TLS1, 4,"DES", 31,"Data Encryption Standard (DES)"},
219 {CALG_3DES_112, 112,112, 112,RSAENH_PCT1_SSL2_SSL3_TLS1,13,"3DES TWO KEY",19,"Two Key Triple DES"},
220 {CALG_3DES, 168,168, 168,RSAENH_PCT1_SSL2_SSL3_TLS1, 5,"3DES", 21,"Three Key Triple DES"},
221 {CALG_SHA,160,160,160,CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1,6,"SHA-1",30,"Secure Hash Algorithm (SHA-1)"},
222 {CALG_MD5,128,128,128,CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1,4,"MD5",23,"Message Digest 5 (MD5)"},
223 {CALG_SSL3_SHAMD5,288,288,288,0, 12,"SSL3 SHAMD5",12,"SSL3 SHAMD5"},
224 {CALG_MAC, 0, 0, 0,0, 4,"MAC", 28,"Message Authentication Code"},
225 {CALG_RSA_SIGN,1024,384,16384,CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1,9,"RSA_SIGN",14,"RSA Signature"},
226 {CALG_RSA_KEYX,1024,384,16384,CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1,9,"RSA_KEYX",17,"RSA Key Exchange"},
227 {CALG_HMAC, 0, 0, 0,0, 5,"HMAC", 18,"Hugo's MAC (HMAC)"},
228 {CALG_PCT1_MASTER,128,128,128,CRYPT_FLAG_PCT1, 12,"PCT1 MASTER",12,"PCT1 Master"},
229 {CALG_SSL2_MASTER,40,40, 192,CRYPT_FLAG_SSL2, 12,"SSL2 MASTER",12,"SSL2 Master"},
230 {CALG_SSL3_MASTER,384,384,384,CRYPT_FLAG_SSL3, 12,"SSL3 MASTER",12,"SSL3 Master"},
231 {CALG_TLS1_MASTER,384,384,384,CRYPT_FLAG_TLS1, 12,"TLS1 MASTER",12,"TLS1 Master"},
232 {CALG_SCHANNEL_MASTER_HASH,0,0,-1,0, 16,"SCH MASTER HASH",21,"SChannel Master Hash"},
233 {CALG_SCHANNEL_MAC_KEY,0,0,-1,0, 12,"SCH MAC KEY",17,"SChannel MAC Key"},
234 {CALG_SCHANNEL_ENC_KEY,0,0,-1,0, 12,"SCH ENC KEY",24,"SChannel Encryption Key"},
235 {CALG_TLS1PRF, 0, 0, -1,0, 9,"TLS1 PRF", 28,"TLS1 Pseudo Random Function"},
236 {0, 0, 0, 0,0, 1,"", 1,""}
239 {CALG_RC2, 128, 40, 128,0, 4,"RC2", 24,"RSA Data Security's RC2"},
240 {CALG_RC4, 128, 40, 128,0, 4,"RC4", 24,"RSA Data Security's RC4"},
241 {CALG_DES, 56, 56, 56,0, 4,"DES", 31,"Data Encryption Standard (DES)"},
242 {CALG_3DES_112, 112,112, 112,0, 13,"3DES TWO KEY",19,"Two Key Triple DES"},
243 {CALG_3DES, 168,168, 168,0, 5,"3DES", 21,"Three Key Triple DES"},
244 {CALG_AES, 128,128, 128,0, 4,"AES", 35,"Advanced Encryption Standard (AES)"},
245 {CALG_AES_128, 128,128, 128,0, 8,"AES-128", 39,"Advanced Encryption Standard (AES-128)"},
246 {CALG_AES_192, 192,192, 192,0, 8,"AES-192", 39,"Advanced Encryption Standard (AES-192)"},
247 {CALG_AES_256, 256,256, 256,0, 8,"AES-256", 39,"Advanced Encryption Standard (AES-256)"},
248 {CALG_SHA, 160,160, 160,CRYPT_FLAG_SIGNING, 6,"SHA-1", 30,"Secure Hash Algorithm (SHA-1)"},
249 {CALG_SHA_256, 256,256, 256,CRYPT_FLAG_SIGNING, 6,"SHA-256", 30,"Secure Hash Algorithm (SHA-256)"},
250 {CALG_SHA_384, 384,384, 384,CRYPT_FLAG_SIGNING, 6,"SHA-384", 30,"Secure Hash Algorithm (SHA-384)"},
251 {CALG_SHA_512, 512,512, 512,CRYPT_FLAG_SIGNING, 6,"SHA-512", 30,"Secure Hash Algorithm (SHA-512)"},
252 {CALG_MD2, 128,128, 128,CRYPT_FLAG_SIGNING, 4,"MD2", 23,"Message Digest 2 (MD2)"},
253 {CALG_MD4, 128,128, 128,CRYPT_FLAG_SIGNING, 4,"MD4", 23,"Message Digest 4 (MD4)"},
254 {CALG_MD5, 128,128, 128,CRYPT_FLAG_SIGNING, 4,"MD5", 23,"Message Digest 5 (MD5)"},
255 {CALG_SSL3_SHAMD5,288,288,288,0, 12,"SSL3 SHAMD5",12,"SSL3 SHAMD5"},
256 {CALG_MAC, 0, 0, 0,0, 4,"MAC", 28,"Message Authentication Code"},
257 {CALG_RSA_SIGN,1024,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_SIGN",14,"RSA Signature"},
258 {CALG_RSA_KEYX,1024,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_KEYX",17,"RSA Key Exchange"},
259 {CALG_HMAC, 0, 0, 0,0, 5,"HMAC", 18,"Hugo's MAC (HMAC)"},
260 {0, 0, 0, 0,0, 1,"", 1,""}
264 /******************************************************************************
265 * API forward declarations
267 BOOL WINAPI
268 RSAENH_CPGetKeyParam(
269 HCRYPTPROV hProv,
270 HCRYPTKEY hKey,
271 DWORD dwParam,
272 BYTE *pbData,
273 DWORD *pdwDataLen,
274 DWORD dwFlags
277 BOOL WINAPI
278 RSAENH_CPEncrypt(
279 HCRYPTPROV hProv,
280 HCRYPTKEY hKey,
281 HCRYPTHASH hHash,
282 BOOL Final,
283 DWORD dwFlags,
284 BYTE *pbData,
285 DWORD *pdwDataLen,
286 DWORD dwBufLen
289 BOOL WINAPI
290 RSAENH_CPCreateHash(
291 HCRYPTPROV hProv,
292 ALG_ID Algid,
293 HCRYPTKEY hKey,
294 DWORD dwFlags,
295 HCRYPTHASH *phHash
298 BOOL WINAPI
299 RSAENH_CPSetHashParam(
300 HCRYPTPROV hProv,
301 HCRYPTHASH hHash,
302 DWORD dwParam,
303 BYTE *pbData, DWORD dwFlags
306 BOOL WINAPI
307 RSAENH_CPGetHashParam(
308 HCRYPTPROV hProv,
309 HCRYPTHASH hHash,
310 DWORD dwParam,
311 BYTE *pbData,
312 DWORD *pdwDataLen,
313 DWORD dwFlags
316 BOOL WINAPI
317 RSAENH_CPDestroyHash(
318 HCRYPTPROV hProv,
319 HCRYPTHASH hHash
322 static BOOL crypt_export_key(
323 CRYPTKEY *pCryptKey,
324 HCRYPTKEY hPubKey,
325 DWORD dwBlobType,
326 DWORD dwFlags,
327 BOOL force,
328 BYTE *pbData,
329 DWORD *pdwDataLen
332 static BOOL import_key(
333 HCRYPTPROV hProv,
334 const BYTE *pbData,
335 DWORD dwDataLen,
336 HCRYPTKEY hPubKey,
337 DWORD dwFlags,
338 BOOL fStoreKey,
339 HCRYPTKEY *phKey
342 BOOL WINAPI
343 RSAENH_CPHashData(
344 HCRYPTPROV hProv,
345 HCRYPTHASH hHash,
346 const BYTE *pbData,
347 DWORD dwDataLen,
348 DWORD dwFlags
351 /******************************************************************************
352 * CSP's handle table (used by all acquired key containers)
354 static struct handle_table handle_table;
356 /******************************************************************************
357 * DllMain (RSAENH.@)
359 * Initializes and destroys the handle table for the CSP's handles.
361 BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD fdwReason, PVOID reserved)
363 switch (fdwReason)
365 case DLL_PROCESS_ATTACH:
366 instance = hInstance;
367 DisableThreadLibraryCalls(hInstance);
368 init_handle_table(&handle_table);
369 break;
371 case DLL_PROCESS_DETACH:
372 if (reserved) break;
373 destroy_handle_table(&handle_table);
374 break;
376 return TRUE;
379 /******************************************************************************
380 * copy_param [Internal]
382 * Helper function that supports the standard WINAPI protocol for querying data
383 * of dynamic size.
385 * PARAMS
386 * pbBuffer [O] Buffer where the queried parameter is copied to, if it is large enough.
387 * May be NUL if the required buffer size is to be queried only.
388 * pdwBufferSize [I/O] In: Size of the buffer at pbBuffer
389 * Out: Size of parameter pbParam
390 * pbParam [I] Parameter value.
391 * dwParamSize [I] Size of pbParam
393 * RETURN
394 * Success: TRUE (pbParam was copied into pbBuffer or pbBuffer is NULL)
395 * Failure: FALSE (pbBuffer is not large enough to hold pbParam). Last error: ERROR_MORE_DATA
397 static inline BOOL copy_param(BYTE *pbBuffer, DWORD *pdwBufferSize, const BYTE *pbParam,
398 DWORD dwParamSize)
400 if (pbBuffer)
402 if (dwParamSize > *pdwBufferSize)
404 SetLastError(ERROR_MORE_DATA);
405 *pdwBufferSize = dwParamSize;
406 return FALSE;
408 memcpy(pbBuffer, pbParam, dwParamSize);
410 *pdwBufferSize = dwParamSize;
411 return TRUE;
414 static inline KEYCONTAINER* get_key_container(HCRYPTPROV hProv)
416 KEYCONTAINER *pKeyContainer;
418 if (!lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER,
419 (OBJECTHDR**)&pKeyContainer))
421 SetLastError(NTE_BAD_UID);
422 return NULL;
424 return pKeyContainer;
427 /******************************************************************************
428 * get_algid_info [Internal]
430 * Query CSP capabilities for a given crypto algorithm.
432 * PARAMS
433 * hProv [I] Handle to a key container of the CSP whose capabilities are to be queried.
434 * algid [I] Identifier of the crypto algorithm about which information is requested.
436 * RETURNS
437 * Success: Pointer to a PROV_ENUMALGS_EX struct containing information about the crypto algorithm.
438 * Failure: NULL (algid not supported)
440 static inline const PROV_ENUMALGS_EX* get_algid_info(HCRYPTPROV hProv, ALG_ID algid) {
441 const PROV_ENUMALGS_EX *iterator;
442 KEYCONTAINER *pKeyContainer;
444 if (!(pKeyContainer = get_key_container(hProv))) return NULL;
446 for (iterator = aProvEnumAlgsEx[pKeyContainer->dwPersonality]; iterator->aiAlgid; iterator++) {
447 if (iterator->aiAlgid == algid) return iterator;
450 SetLastError(NTE_BAD_ALGID);
451 return NULL;
454 /******************************************************************************
455 * copy_data_blob [Internal]
457 * deeply copies a DATA_BLOB
459 * PARAMS
460 * dst [O] That's where the blob will be copied to
461 * src [I] Source blob
463 * RETURNS
464 * Success: TRUE
465 * Failure: FALSE (GetLastError() == NTE_NO_MEMORY
467 * NOTES
468 * Use free_data_blob to release resources occupied by copy_data_blob.
470 static inline BOOL copy_data_blob(PCRYPT_DATA_BLOB dst, const PCRYPT_DATA_BLOB src)
472 dst->pbData = HeapAlloc(GetProcessHeap(), 0, src->cbData);
473 if (!dst->pbData) {
474 SetLastError(NTE_NO_MEMORY);
475 return FALSE;
477 dst->cbData = src->cbData;
478 memcpy(dst->pbData, src->pbData, src->cbData);
479 return TRUE;
482 /******************************************************************************
483 * concat_data_blobs [Internal]
485 * Concatenates two blobs
487 * PARAMS
488 * dst [O] The new blob will be copied here
489 * src1 [I] Prefix blob
490 * src2 [I] Appendix blob
492 * RETURNS
493 * Success: TRUE
494 * Failure: FALSE (GetLastError() == NTE_NO_MEMORY)
496 * NOTES
497 * Release resources occupied by concat_data_blobs with free_data_blobs
499 static inline BOOL concat_data_blobs(PCRYPT_DATA_BLOB dst, const PCRYPT_DATA_BLOB src1,
500 const PCRYPT_DATA_BLOB src2)
502 dst->cbData = src1->cbData + src2->cbData;
503 dst->pbData = HeapAlloc(GetProcessHeap(), 0, dst->cbData);
504 if (!dst->pbData) {
505 SetLastError(NTE_NO_MEMORY);
506 return FALSE;
508 memcpy(dst->pbData, src1->pbData, src1->cbData);
509 memcpy(dst->pbData + src1->cbData, src2->pbData, src2->cbData);
510 return TRUE;
513 /******************************************************************************
514 * free_data_blob [Internal]
516 * releases resource occupied by a dynamically allocated CRYPT_DATA_BLOB
518 * PARAMS
519 * pBlob [I] Heap space occupied by pBlob->pbData is released
521 static inline void free_data_blob(PCRYPT_DATA_BLOB pBlob) {
522 HeapFree(GetProcessHeap(), 0, pBlob->pbData);
525 /******************************************************************************
526 * init_data_blob [Internal]
528 static inline void init_data_blob(PCRYPT_DATA_BLOB pBlob) {
529 pBlob->pbData = NULL;
530 pBlob->cbData = 0;
533 /******************************************************************************
534 * free_hmac_info [Internal]
536 * Deeply free an HMAC_INFO struct.
538 * PARAMS
539 * hmac_info [I] Pointer to the HMAC_INFO struct to be freed.
541 * NOTES
542 * See Internet RFC 2104 for details on the HMAC algorithm.
544 static inline void free_hmac_info(PHMAC_INFO hmac_info) {
545 if (!hmac_info) return;
546 HeapFree(GetProcessHeap(), 0, hmac_info->pbInnerString);
547 HeapFree(GetProcessHeap(), 0, hmac_info->pbOuterString);
548 HeapFree(GetProcessHeap(), 0, hmac_info);
551 /******************************************************************************
552 * copy_hmac_info [Internal]
554 * Deeply copy an HMAC_INFO struct
556 * PARAMS
557 * dst [O] Pointer to a location where the pointer to the HMAC_INFO copy will be stored.
558 * src [I] Pointer to the HMAC_INFO struct to be copied.
560 * RETURNS
561 * Success: TRUE
562 * Failure: FALSE
564 * NOTES
565 * See Internet RFC 2104 for details on the HMAC algorithm.
567 static BOOL copy_hmac_info(PHMAC_INFO *dst, const HMAC_INFO *src) {
568 if (!src) return FALSE;
569 *dst = HeapAlloc(GetProcessHeap(), 0, sizeof(HMAC_INFO));
570 if (!*dst) return FALSE;
571 **dst = *src;
572 (*dst)->pbInnerString = NULL;
573 (*dst)->pbOuterString = NULL;
574 if ((*dst)->cbInnerString == 0) (*dst)->cbInnerString = RSAENH_HMAC_DEF_PAD_LEN;
575 (*dst)->pbInnerString = HeapAlloc(GetProcessHeap(), 0, (*dst)->cbInnerString);
576 if (!(*dst)->pbInnerString) {
577 free_hmac_info(*dst);
578 return FALSE;
580 if (src->cbInnerString)
581 memcpy((*dst)->pbInnerString, src->pbInnerString, src->cbInnerString);
582 else
583 memset((*dst)->pbInnerString, RSAENH_HMAC_DEF_IPAD_CHAR, RSAENH_HMAC_DEF_PAD_LEN);
584 if ((*dst)->cbOuterString == 0) (*dst)->cbOuterString = RSAENH_HMAC_DEF_PAD_LEN;
585 (*dst)->pbOuterString = HeapAlloc(GetProcessHeap(), 0, (*dst)->cbOuterString);
586 if (!(*dst)->pbOuterString) {
587 free_hmac_info(*dst);
588 return FALSE;
590 if (src->cbOuterString)
591 memcpy((*dst)->pbOuterString, src->pbOuterString, src->cbOuterString);
592 else
593 memset((*dst)->pbOuterString, RSAENH_HMAC_DEF_OPAD_CHAR, RSAENH_HMAC_DEF_PAD_LEN);
594 return TRUE;
597 /******************************************************************************
598 * destroy_hash [Internal]
600 * Destructor for hash objects
602 * PARAMS
603 * pCryptHash [I] Pointer to the hash object to be destroyed.
604 * Will be invalid after function returns!
606 static void destroy_hash(OBJECTHDR *pObject)
608 CRYPTHASH *pCryptHash = (CRYPTHASH*)pObject;
610 free_hmac_info(pCryptHash->pHMACInfo);
611 free_data_blob(&pCryptHash->tpPRFParams.blobLabel);
612 free_data_blob(&pCryptHash->tpPRFParams.blobSeed);
613 HeapFree(GetProcessHeap(), 0, pCryptHash);
616 /******************************************************************************
617 * init_hash [Internal]
619 * Initialize (or reset) a hash object
621 * PARAMS
622 * pCryptHash [I] The hash object to be initialized.
624 static inline BOOL init_hash(CRYPTHASH *pCryptHash) {
625 DWORD dwLen;
627 switch (pCryptHash->aiAlgid)
629 case CALG_HMAC:
630 if (pCryptHash->pHMACInfo) {
631 const PROV_ENUMALGS_EX *pAlgInfo;
633 pAlgInfo = get_algid_info(pCryptHash->hProv, pCryptHash->pHMACInfo->HashAlgid);
634 if (!pAlgInfo) return FALSE;
635 pCryptHash->dwHashSize = pAlgInfo->dwDefaultLen >> 3;
636 init_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context);
637 update_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
638 pCryptHash->pHMACInfo->pbInnerString,
639 pCryptHash->pHMACInfo->cbInnerString);
641 return TRUE;
643 case CALG_MAC:
644 dwLen = sizeof(DWORD);
645 RSAENH_CPGetKeyParam(pCryptHash->hProv, pCryptHash->hKey, KP_BLOCKLEN,
646 (BYTE*)&pCryptHash->dwHashSize, &dwLen, 0);
647 pCryptHash->dwHashSize >>= 3;
648 return TRUE;
650 default:
651 return init_hash_impl(pCryptHash->aiAlgid, &pCryptHash->context);
655 /******************************************************************************
656 * update_hash [Internal]
658 * Hashes the given data and updates the hash object's state accordingly
660 * PARAMS
661 * pCryptHash [I] Hash object to be updated.
662 * pbData [I] Pointer to data stream to be hashed.
663 * dwDataLen [I] Length of data stream.
665 static inline void update_hash(CRYPTHASH *pCryptHash, const BYTE *pbData, DWORD dwDataLen)
667 BYTE *pbTemp;
669 switch (pCryptHash->aiAlgid)
671 case CALG_HMAC:
672 if (pCryptHash->pHMACInfo)
673 update_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
674 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->aiAlgid, &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->pHMACInfo->HashAlgid, &pCryptHash->context,
710 pCryptHash->abHashValue);
711 memcpy(abHashValue, pCryptHash->abHashValue, pCryptHash->dwHashSize);
712 init_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context);
713 update_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
714 pCryptHash->pHMACInfo->pbOuterString,
715 pCryptHash->pHMACInfo->cbOuterString);
716 update_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
717 abHashValue, pCryptHash->dwHashSize);
718 finalize_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
719 pCryptHash->abHashValue);
721 break;
723 case CALG_MAC:
724 dwDataLen = 0;
725 RSAENH_CPEncrypt(pCryptHash->hProv, pCryptHash->hKey, 0, TRUE, 0,
726 pCryptHash->abHashValue, &dwDataLen, pCryptHash->dwHashSize);
727 break;
729 default:
730 finalize_hash_impl(pCryptHash->aiAlgid, &pCryptHash->context, pCryptHash->abHashValue);
734 /******************************************************************************
735 * destroy_key [Internal]
737 * Destructor for key objects
739 * PARAMS
740 * pCryptKey [I] Pointer to the key object to be destroyed.
741 * Will be invalid after function returns!
743 static void destroy_key(OBJECTHDR *pObject)
745 CRYPTKEY *pCryptKey = (CRYPTKEY*)pObject;
747 free_key_impl(pCryptKey->aiAlgid, &pCryptKey->context);
748 free_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom);
749 free_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom);
750 free_data_blob(&pCryptKey->blobHmacKey);
751 HeapFree(GetProcessHeap(), 0, pCryptKey);
754 /******************************************************************************
755 * setup_key [Internal]
757 * Initialize (or reset) a key object
759 * PARAMS
760 * pCryptKey [I] The key object to be initialized.
762 static inline void setup_key(CRYPTKEY *pCryptKey) {
763 pCryptKey->dwState = RSAENH_KEYSTATE_IDLE;
764 memcpy(pCryptKey->abChainVector, pCryptKey->abInitVector, sizeof(pCryptKey->abChainVector));
765 setup_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen,
766 pCryptKey->dwEffectiveKeyLen, pCryptKey->dwSaltLen,
767 pCryptKey->abKeyValue);
770 /******************************************************************************
771 * new_key [Internal]
773 * Creates a new key object without assigning the actual binary key value.
774 * This is done by CPDeriveKey, CPGenKey or CPImportKey, which call this function.
776 * PARAMS
777 * hProv [I] Handle to the provider to which the created key will belong.
778 * aiAlgid [I] The new key shall use the crypto algorithm identified by aiAlgid.
779 * dwFlags [I] Upper 16 bits give the key length.
780 * Lower 16 bits: CRYPT_EXPORTABLE, CRYPT_CREATE_SALT,
781 * CRYPT_NO_SALT
782 * ppCryptKey [O] Pointer to the created key
784 * RETURNS
785 * Success: Handle to the created key.
786 * Failure: INVALID_HANDLE_VALUE
788 static HCRYPTKEY new_key(HCRYPTPROV hProv, ALG_ID aiAlgid, DWORD dwFlags, CRYPTKEY **ppCryptKey)
790 HCRYPTKEY hCryptKey;
791 CRYPTKEY *pCryptKey;
792 DWORD dwKeyLen = HIWORD(dwFlags), bKeyLen = dwKeyLen;
793 const PROV_ENUMALGS_EX *peaAlgidInfo;
795 *ppCryptKey = NULL;
798 * Retrieve the CSP's capabilities for the given ALG_ID value
800 peaAlgidInfo = get_algid_info(hProv, aiAlgid);
801 if (!peaAlgidInfo) return (HCRYPTKEY)INVALID_HANDLE_VALUE;
803 TRACE("alg = %s, dwKeyLen = %d\n", debugstr_a(peaAlgidInfo->szName),
804 dwKeyLen);
806 * Assume the default key length, if none is specified explicitly
808 if (dwKeyLen == 0) dwKeyLen = peaAlgidInfo->dwDefaultLen;
811 * Check if the requested key length is supported by the current CSP.
812 * Adjust key length's for DES algorithms.
814 switch (aiAlgid) {
815 case CALG_DES:
816 if (dwKeyLen == RSAENH_DES_EFFECTIVE_KEYLEN) {
817 dwKeyLen = RSAENH_DES_STORAGE_KEYLEN;
819 if (dwKeyLen != RSAENH_DES_STORAGE_KEYLEN) {
820 SetLastError(NTE_BAD_FLAGS);
821 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
823 break;
825 case CALG_3DES_112:
826 if (dwKeyLen == RSAENH_3DES112_EFFECTIVE_KEYLEN) {
827 dwKeyLen = RSAENH_3DES112_STORAGE_KEYLEN;
829 if (dwKeyLen != RSAENH_3DES112_STORAGE_KEYLEN) {
830 SetLastError(NTE_BAD_FLAGS);
831 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
833 break;
835 case CALG_3DES:
836 if (dwKeyLen == RSAENH_3DES_EFFECTIVE_KEYLEN) {
837 dwKeyLen = RSAENH_3DES_STORAGE_KEYLEN;
839 if (dwKeyLen != RSAENH_3DES_STORAGE_KEYLEN) {
840 SetLastError(NTE_BAD_FLAGS);
841 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
843 break;
845 case CALG_HMAC:
846 /* Avoid the key length check for HMAC keys, which have unlimited
847 * length.
849 break;
851 case CALG_AES:
852 if (!bKeyLen)
854 TRACE("missing key len for CALG_AES\n");
855 SetLastError(NTE_BAD_ALGID);
856 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
858 /* fall through */
859 default:
860 if (dwKeyLen % 8 ||
861 dwKeyLen > peaAlgidInfo->dwMaxLen ||
862 dwKeyLen < peaAlgidInfo->dwMinLen)
864 TRACE("key len %d out of bounds (%d, %d)\n", dwKeyLen,
865 peaAlgidInfo->dwMinLen, peaAlgidInfo->dwMaxLen);
866 SetLastError(NTE_BAD_DATA);
867 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
871 hCryptKey = new_object(&handle_table, sizeof(CRYPTKEY), RSAENH_MAGIC_KEY,
872 destroy_key, (OBJECTHDR**)&pCryptKey);
873 if (hCryptKey != (HCRYPTKEY)INVALID_HANDLE_VALUE)
875 KEYCONTAINER *pKeyContainer = get_key_container(hProv);
876 pCryptKey->aiAlgid = aiAlgid;
877 pCryptKey->hProv = hProv;
878 pCryptKey->dwModeBits = 0;
879 pCryptKey->dwPermissions = CRYPT_ENCRYPT | CRYPT_DECRYPT | CRYPT_READ | CRYPT_WRITE |
880 CRYPT_MAC;
881 if (dwFlags & CRYPT_EXPORTABLE)
882 pCryptKey->dwPermissions |= CRYPT_EXPORT;
883 pCryptKey->dwKeyLen = dwKeyLen >> 3;
884 pCryptKey->dwEffectiveKeyLen = 0;
887 * For compatibility reasons a 40 bit key on the Enhanced
888 * provider will not have salt
890 if (pKeyContainer->dwPersonality == RSAENH_PERSONALITY_ENHANCED
891 && (aiAlgid == CALG_RC2 || aiAlgid == CALG_RC4)
892 && (dwFlags & CRYPT_CREATE_SALT) && dwKeyLen == 40)
893 pCryptKey->dwSaltLen = 0;
894 else if ((dwFlags & CRYPT_CREATE_SALT) || (dwKeyLen == 40 && !(dwFlags & CRYPT_NO_SALT)))
895 pCryptKey->dwSaltLen = 16 /*FIXME*/ - pCryptKey->dwKeyLen;
896 else
897 pCryptKey->dwSaltLen = 0;
898 memset(pCryptKey->abKeyValue, 0, sizeof(pCryptKey->abKeyValue));
899 memset(pCryptKey->abInitVector, 0, sizeof(pCryptKey->abInitVector));
900 memset(&pCryptKey->siSChannelInfo.saEncAlg, 0, sizeof(pCryptKey->siSChannelInfo.saEncAlg));
901 memset(&pCryptKey->siSChannelInfo.saMACAlg, 0, sizeof(pCryptKey->siSChannelInfo.saMACAlg));
902 init_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom);
903 init_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom);
904 init_data_blob(&pCryptKey->blobHmacKey);
906 switch(aiAlgid)
908 case CALG_PCT1_MASTER:
909 case CALG_SSL2_MASTER:
910 case CALG_SSL3_MASTER:
911 case CALG_TLS1_MASTER:
912 case CALG_RC4:
913 pCryptKey->dwBlockLen = 0;
914 pCryptKey->dwMode = 0;
915 break;
917 case CALG_RC2:
918 case CALG_DES:
919 case CALG_3DES_112:
920 case CALG_3DES:
921 pCryptKey->dwBlockLen = 8;
922 pCryptKey->dwMode = CRYPT_MODE_CBC;
923 break;
925 case CALG_AES:
926 case CALG_AES_128:
927 case CALG_AES_192:
928 case CALG_AES_256:
929 pCryptKey->dwBlockLen = 16;
930 pCryptKey->dwMode = CRYPT_MODE_CBC;
931 break;
933 case CALG_RSA_KEYX:
934 case CALG_RSA_SIGN:
935 pCryptKey->dwBlockLen = dwKeyLen >> 3;
936 pCryptKey->dwMode = 0;
937 break;
939 case CALG_HMAC:
940 pCryptKey->dwBlockLen = 0;
941 pCryptKey->dwMode = 0;
942 break;
945 *ppCryptKey = pCryptKey;
948 return hCryptKey;
951 /******************************************************************************
952 * map_key_spec_to_key_pair_name [Internal]
954 * Returns the name of the registry value associated with a key spec.
956 * PARAMS
957 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
959 * RETURNS
960 * Success: Name of registry value.
961 * Failure: NULL
963 static LPCSTR map_key_spec_to_key_pair_name(DWORD dwKeySpec)
965 LPCSTR szValueName;
967 switch (dwKeySpec)
969 case AT_KEYEXCHANGE:
970 szValueName = "KeyExchangeKeyPair";
971 break;
972 case AT_SIGNATURE:
973 szValueName = "SignatureKeyPair";
974 break;
975 default:
976 WARN("invalid key spec %d\n", dwKeySpec);
977 szValueName = NULL;
979 return szValueName;
982 /******************************************************************************
983 * store_key_pair [Internal]
985 * Stores a key pair to the registry
987 * PARAMS
988 * hCryptKey [I] Handle to the key to be stored
989 * hKey [I] Registry key where the key pair is to be stored
990 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
991 * dwFlags [I] Flags for protecting the key
993 static void store_key_pair(HCRYPTKEY hCryptKey, HKEY hKey, DWORD dwKeySpec, DWORD dwFlags)
995 LPCSTR szValueName;
996 DATA_BLOB blobIn, blobOut;
997 CRYPTKEY *pKey;
998 DWORD dwLen;
999 BYTE *pbKey;
1001 if (!(szValueName = map_key_spec_to_key_pair_name(dwKeySpec)))
1002 return;
1003 if (lookup_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY,
1004 (OBJECTHDR**)&pKey))
1006 if (crypt_export_key(pKey, 0, PRIVATEKEYBLOB, 0, TRUE, 0, &dwLen))
1008 pbKey = HeapAlloc(GetProcessHeap(), 0, dwLen);
1009 if (pbKey)
1011 if (crypt_export_key(pKey, 0, PRIVATEKEYBLOB, 0, TRUE, pbKey,
1012 &dwLen))
1014 blobIn.pbData = pbKey;
1015 blobIn.cbData = dwLen;
1017 if (CryptProtectData(&blobIn, NULL, NULL, NULL, NULL,
1018 dwFlags, &blobOut))
1020 RegSetValueExA(hKey, szValueName, 0, REG_BINARY,
1021 blobOut.pbData, blobOut.cbData);
1022 LocalFree(blobOut.pbData);
1025 HeapFree(GetProcessHeap(), 0, pbKey);
1031 /******************************************************************************
1032 * map_key_spec_to_permissions_name [Internal]
1034 * Returns the name of the registry value associated with the permissions for
1035 * a key spec.
1037 * PARAMS
1038 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
1040 * RETURNS
1041 * Success: Name of registry value.
1042 * Failure: NULL
1044 static LPCSTR map_key_spec_to_permissions_name(DWORD dwKeySpec)
1046 LPCSTR szValueName;
1048 switch (dwKeySpec)
1050 case AT_KEYEXCHANGE:
1051 szValueName = "KeyExchangePermissions";
1052 break;
1053 case AT_SIGNATURE:
1054 szValueName = "SignaturePermissions";
1055 break;
1056 default:
1057 WARN("invalid key spec %d\n", dwKeySpec);
1058 szValueName = NULL;
1060 return szValueName;
1063 /******************************************************************************
1064 * store_key_permissions [Internal]
1066 * Stores a key's permissions to the registry
1068 * PARAMS
1069 * hCryptKey [I] Handle to the key whose permissions are to be stored
1070 * hKey [I] Registry key where the key permissions are to be stored
1071 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
1073 static void store_key_permissions(HCRYPTKEY hCryptKey, HKEY hKey, DWORD dwKeySpec)
1075 LPCSTR szValueName;
1076 CRYPTKEY *pKey;
1078 if (!(szValueName = map_key_spec_to_permissions_name(dwKeySpec)))
1079 return;
1080 if (lookup_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY,
1081 (OBJECTHDR**)&pKey))
1082 RegSetValueExA(hKey, szValueName, 0, REG_DWORD,
1083 (BYTE *)&pKey->dwPermissions,
1084 sizeof(pKey->dwPermissions));
1087 /******************************************************************************
1088 * create_container_key [Internal]
1090 * Creates the registry key for a key container's persistent storage.
1092 * PARAMS
1093 * pKeyContainer [I] Pointer to the key container
1094 * sam [I] Desired registry access
1095 * phKey [O] Returned key
1097 static BOOL create_container_key(KEYCONTAINER *pKeyContainer, REGSAM sam, HKEY *phKey)
1099 CHAR szRSABase[sizeof(RSAENH_REGKEY) + MAX_PATH];
1100 HKEY hRootKey;
1102 sprintf(szRSABase, RSAENH_REGKEY, pKeyContainer->szName);
1104 if (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET)
1105 hRootKey = HKEY_LOCAL_MACHINE;
1106 else
1107 hRootKey = HKEY_CURRENT_USER;
1109 /* @@ Wine registry key: HKLM\Software\Wine\Crypto\RSA */
1110 /* @@ Wine registry key: HKCU\Software\Wine\Crypto\RSA */
1111 return RegCreateKeyExA(hRootKey, szRSABase, 0, NULL,
1112 REG_OPTION_NON_VOLATILE, sam, NULL, phKey, NULL)
1113 == ERROR_SUCCESS;
1116 /******************************************************************************
1117 * open_container_key [Internal]
1119 * Opens a key container's persistent storage for reading.
1121 * PARAMS
1122 * pszContainerName [I] Name of the container to be opened. May be the empty
1123 * string if the parent key of all containers is to be
1124 * opened.
1125 * dwFlags [I] Flags indicating which keyset to be opened.
1126 * phKey [O] Returned key
1128 static BOOL open_container_key(LPCSTR pszContainerName, DWORD dwFlags, REGSAM access, HKEY *phKey)
1130 CHAR szRSABase[sizeof(RSAENH_REGKEY) + MAX_PATH];
1131 HKEY hRootKey;
1133 sprintf(szRSABase, RSAENH_REGKEY, pszContainerName);
1135 if (dwFlags & CRYPT_MACHINE_KEYSET)
1136 hRootKey = HKEY_LOCAL_MACHINE;
1137 else
1138 hRootKey = HKEY_CURRENT_USER;
1140 /* @@ Wine registry key: HKLM\Software\Wine\Crypto\RSA */
1141 /* @@ Wine registry key: HKCU\Software\Wine\Crypto\RSA */
1142 return RegOpenKeyExA(hRootKey, szRSABase, 0, access, phKey) ==
1143 ERROR_SUCCESS;
1146 /******************************************************************************
1147 * delete_container_key [Internal]
1149 * Deletes a key container's persistent storage.
1151 * PARAMS
1152 * pszContainerName [I] Name of the container to be opened.
1153 * dwFlags [I] Flags indicating which keyset to be opened.
1155 static BOOL delete_container_key(LPCSTR pszContainerName, DWORD dwFlags)
1157 CHAR szRegKey[sizeof(RSAENH_REGKEY) + MAX_PATH];
1158 HKEY hRootKey;
1160 sprintf(szRegKey, RSAENH_REGKEY, pszContainerName);
1162 if (dwFlags & CRYPT_MACHINE_KEYSET)
1163 hRootKey = HKEY_LOCAL_MACHINE;
1164 else
1165 hRootKey = HKEY_CURRENT_USER;
1166 if (!RegDeleteKeyA(hRootKey, szRegKey)) {
1167 SetLastError(ERROR_SUCCESS);
1168 return TRUE;
1169 } else {
1170 SetLastError(NTE_BAD_KEYSET);
1171 return FALSE;
1175 /******************************************************************************
1176 * store_key_container_keys [Internal]
1178 * Stores key container's keys in a persistent location.
1180 * PARAMS
1181 * pKeyContainer [I] Pointer to the key container whose keys are to be saved
1183 static void store_key_container_keys(KEYCONTAINER *pKeyContainer)
1185 HKEY hKey;
1186 DWORD dwFlags;
1188 /* On WinXP, persistent keys are stored in a file located at:
1189 * $AppData$\\Microsoft\\Crypto\\RSA\\$SID$\\some_hex_string
1192 if (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET)
1193 dwFlags = CRYPTPROTECT_LOCAL_MACHINE;
1194 else
1195 dwFlags = 0;
1197 if (create_container_key(pKeyContainer, KEY_WRITE, &hKey))
1199 store_key_pair(pKeyContainer->hKeyExchangeKeyPair, hKey,
1200 AT_KEYEXCHANGE, dwFlags);
1201 store_key_pair(pKeyContainer->hSignatureKeyPair, hKey,
1202 AT_SIGNATURE, dwFlags);
1203 RegCloseKey(hKey);
1207 /******************************************************************************
1208 * store_key_container_permissions [Internal]
1210 * Stores key container's key permissions in a persistent location.
1212 * PARAMS
1213 * pKeyContainer [I] Pointer to the key container whose key permissions are to
1214 * be saved
1216 static void store_key_container_permissions(KEYCONTAINER *pKeyContainer)
1218 HKEY hKey;
1220 if (create_container_key(pKeyContainer, KEY_WRITE, &hKey))
1222 store_key_permissions(pKeyContainer->hKeyExchangeKeyPair, hKey,
1223 AT_KEYEXCHANGE);
1224 store_key_permissions(pKeyContainer->hSignatureKeyPair, hKey,
1225 AT_SIGNATURE);
1226 RegCloseKey(hKey);
1230 /******************************************************************************
1231 * release_key_container_keys [Internal]
1233 * Releases key container's keys.
1235 * PARAMS
1236 * pKeyContainer [I] Pointer to the key container whose keys are to be released.
1238 static void release_key_container_keys(KEYCONTAINER *pKeyContainer)
1240 release_handle(&handle_table, pKeyContainer->hKeyExchangeKeyPair,
1241 RSAENH_MAGIC_KEY);
1242 release_handle(&handle_table, pKeyContainer->hSignatureKeyPair,
1243 RSAENH_MAGIC_KEY);
1246 /******************************************************************************
1247 * destroy_key_container [Internal]
1249 * Destructor for key containers.
1251 * PARAMS
1252 * pObjectHdr [I] Pointer to the key container to be destroyed.
1254 static void destroy_key_container(OBJECTHDR *pObjectHdr)
1256 KEYCONTAINER *pKeyContainer = (KEYCONTAINER*)pObjectHdr;
1258 if (!(pKeyContainer->dwFlags & CRYPT_VERIFYCONTEXT))
1260 store_key_container_keys(pKeyContainer);
1261 store_key_container_permissions(pKeyContainer);
1262 release_key_container_keys(pKeyContainer);
1264 else
1265 release_key_container_keys(pKeyContainer);
1266 HeapFree( GetProcessHeap(), 0, pKeyContainer );
1269 /******************************************************************************
1270 * new_key_container [Internal]
1272 * Create a new key container. The personality (RSA Base, Strong or Enhanced CP)
1273 * of the CSP is determined via the pVTable->pszProvName string.
1275 * PARAMS
1276 * pszContainerName [I] Name of the key container.
1277 * pVTable [I] Callback functions and context info provided by the OS
1279 * RETURNS
1280 * Success: Handle to the new key container.
1281 * Failure: INVALID_HANDLE_VALUE
1283 static HCRYPTPROV new_key_container(PCCH pszContainerName, DWORD dwFlags, const VTableProvStruc *pVTable)
1285 KEYCONTAINER *pKeyContainer;
1286 HCRYPTPROV hKeyContainer;
1288 hKeyContainer = new_object(&handle_table, sizeof(KEYCONTAINER), RSAENH_MAGIC_CONTAINER,
1289 destroy_key_container, (OBJECTHDR**)&pKeyContainer);
1290 if (hKeyContainer != (HCRYPTPROV)INVALID_HANDLE_VALUE)
1292 lstrcpynA(pKeyContainer->szName, pszContainerName, MAX_PATH);
1293 pKeyContainer->dwFlags = dwFlags;
1294 pKeyContainer->dwEnumAlgsCtr = 0;
1295 pKeyContainer->hKeyExchangeKeyPair = (HCRYPTKEY)INVALID_HANDLE_VALUE;
1296 pKeyContainer->hSignatureKeyPair = (HCRYPTKEY)INVALID_HANDLE_VALUE;
1297 if (pVTable && pVTable->pszProvName) {
1298 lstrcpynA(pKeyContainer->szProvName, pVTable->pszProvName, MAX_PATH);
1299 if (!strcmp(pVTable->pszProvName, MS_DEF_PROV_A)) {
1300 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_BASE;
1301 } else if (!strcmp(pVTable->pszProvName, MS_ENHANCED_PROV_A)) {
1302 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_ENHANCED;
1303 } else if (!strcmp(pVTable->pszProvName, MS_DEF_RSA_SCHANNEL_PROV_A)) {
1304 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_SCHANNEL;
1305 } else if (!strcmp(pVTable->pszProvName, MS_ENH_RSA_AES_PROV_A) ||
1306 !strcmp(pVTable->pszProvName, MS_ENH_RSA_AES_PROV_XP_A)) {
1307 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_AES;
1308 } else {
1309 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_STRONG;
1313 /* The new key container has to be inserted into the CSP immediately
1314 * after creation to be available for CPGetProvParam's PP_ENUMCONTAINERS. */
1315 if (!(dwFlags & CRYPT_VERIFYCONTEXT)) {
1316 HKEY hKey;
1318 if (create_container_key(pKeyContainer, KEY_WRITE, &hKey))
1319 RegCloseKey(hKey);
1323 return hKeyContainer;
1326 /******************************************************************************
1327 * read_key_value [Internal]
1329 * Reads a key pair value from the registry
1331 * PARAMS
1332 * hKeyContainer [I] Crypt provider to use to import the key
1333 * hKey [I] Registry key from which to read the key pair
1334 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
1335 * dwFlags [I] Flags for unprotecting the key
1336 * phCryptKey [O] Returned key
1338 static BOOL read_key_value(HCRYPTPROV hKeyContainer, HKEY hKey, DWORD dwKeySpec, DWORD dwFlags, HCRYPTKEY *phCryptKey)
1340 LPCSTR szValueName;
1341 DWORD dwValueType, dwLen;
1342 BYTE *pbKey;
1343 DATA_BLOB blobIn, blobOut;
1344 BOOL ret = FALSE;
1346 if (!(szValueName = map_key_spec_to_key_pair_name(dwKeySpec)))
1347 return FALSE;
1348 if (RegQueryValueExA(hKey, szValueName, 0, &dwValueType, NULL, &dwLen) ==
1349 ERROR_SUCCESS)
1351 pbKey = HeapAlloc(GetProcessHeap(), 0, dwLen);
1352 if (pbKey)
1354 if (RegQueryValueExA(hKey, szValueName, 0, &dwValueType, pbKey, &dwLen) ==
1355 ERROR_SUCCESS)
1357 blobIn.pbData = pbKey;
1358 blobIn.cbData = dwLen;
1360 if (CryptUnprotectData(&blobIn, NULL, NULL, NULL, NULL,
1361 dwFlags, &blobOut))
1363 ret = import_key(hKeyContainer, blobOut.pbData, blobOut.cbData, 0, 0,
1364 FALSE, phCryptKey);
1365 LocalFree(blobOut.pbData);
1368 HeapFree(GetProcessHeap(), 0, pbKey);
1371 if (ret)
1373 CRYPTKEY *pKey;
1375 if (lookup_handle(&handle_table, *phCryptKey, RSAENH_MAGIC_KEY,
1376 (OBJECTHDR**)&pKey))
1378 if ((szValueName = map_key_spec_to_permissions_name(dwKeySpec)))
1380 dwLen = sizeof(pKey->dwPermissions);
1381 RegQueryValueExA(hKey, szValueName, 0, NULL,
1382 (BYTE *)&pKey->dwPermissions, &dwLen);
1386 return ret;
1389 /******************************************************************************
1390 * read_key_container [Internal]
1392 * Tries to read the persistent state of the key container (mainly the signature
1393 * and key exchange private keys) given by pszContainerName.
1395 * PARAMS
1396 * pszContainerName [I] Name of the key container to read from the registry
1397 * pVTable [I] Pointer to context data provided by the operating system
1399 * RETURNS
1400 * Success: Handle to the key container read from the registry
1401 * Failure: INVALID_HANDLE_VALUE
1403 static HCRYPTPROV read_key_container(PCHAR pszContainerName, DWORD dwFlags, const VTableProvStruc *pVTable)
1405 HKEY hKey;
1406 KEYCONTAINER *pKeyContainer;
1407 HCRYPTPROV hKeyContainer;
1408 HCRYPTKEY hCryptKey;
1410 if (!open_container_key(pszContainerName, dwFlags, KEY_READ, &hKey))
1412 SetLastError(NTE_BAD_KEYSET);
1413 return (HCRYPTPROV)INVALID_HANDLE_VALUE;
1416 hKeyContainer = new_key_container(pszContainerName, dwFlags, pVTable);
1417 if (hKeyContainer != (HCRYPTPROV)INVALID_HANDLE_VALUE)
1419 DWORD dwProtectFlags = (dwFlags & CRYPT_MACHINE_KEYSET) ?
1420 CRYPTPROTECT_LOCAL_MACHINE : 0;
1422 if (!lookup_handle(&handle_table, hKeyContainer, RSAENH_MAGIC_CONTAINER,
1423 (OBJECTHDR**)&pKeyContainer))
1424 return (HCRYPTPROV)INVALID_HANDLE_VALUE;
1426 /* read_key_value calls import_key, which calls import_private_key,
1427 * which implicitly installs the key value into the appropriate key
1428 * container key. Thus the ref count is incremented twice, once for
1429 * the output key value, and once for the implicit install, and needs
1430 * to be decremented to balance the two.
1432 if (read_key_value(hKeyContainer, hKey, AT_KEYEXCHANGE,
1433 dwProtectFlags, &hCryptKey))
1434 release_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY);
1435 if (read_key_value(hKeyContainer, hKey, AT_SIGNATURE,
1436 dwProtectFlags, &hCryptKey))
1437 release_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY);
1440 return hKeyContainer;
1443 /******************************************************************************
1444 * build_hash_signature [Internal]
1446 * Builds a padded version of a hash to match the length of the RSA key modulus.
1448 * PARAMS
1449 * pbSignature [O] The padded hash object is stored here.
1450 * dwLen [I] Length of the pbSignature buffer.
1451 * aiAlgid [I] Algorithm identifier of the hash to be padded.
1452 * abHashValue [I] The value of the hash object.
1453 * dwHashLen [I] Length of the hash value.
1454 * dwFlags [I] Selection of padding algorithm.
1456 * RETURNS
1457 * Success: TRUE
1458 * Failure: FALSE (NTE_BAD_ALGID)
1460 static BOOL build_hash_signature(BYTE *pbSignature, DWORD dwLen, ALG_ID aiAlgid,
1461 const BYTE *abHashValue, DWORD dwHashLen, DWORD dwFlags)
1463 /* These prefixes are meant to be concatenated with hash values of the
1464 * respective kind to form a PKCS #7 DigestInfo. */
1465 static const struct tagOIDDescriptor {
1466 ALG_ID aiAlgid;
1467 DWORD dwLen;
1468 const BYTE abOID[19];
1469 } aOIDDescriptor[] = {
1470 { CALG_MD2, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48,
1471 0x86, 0xf7, 0x0d, 0x02, 0x02, 0x05, 0x00, 0x04, 0x10 } },
1472 { CALG_MD4, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48,
1473 0x86, 0xf7, 0x0d, 0x02, 0x04, 0x05, 0x00, 0x04, 0x10 } },
1474 { CALG_MD5, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48,
1475 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10 } },
1476 { CALG_SHA, 15, { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
1477 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 } },
1478 { CALG_SHA_256, 19, { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
1479 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01,
1480 0x05, 0x00, 0x04, 0x20 } },
1481 { CALG_SHA_384, 19, { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
1482 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02,
1483 0x05, 0x00, 0x04, 0x30 } },
1484 { CALG_SHA_512, 19, { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
1485 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03,
1486 0x05, 0x00, 0x04, 0x40 } },
1487 { CALG_SSL3_SHAMD5, 0, { 0 } },
1488 { 0, 0, { 0 } }
1490 DWORD dwIdxOID, i, j;
1492 for (dwIdxOID = 0; aOIDDescriptor[dwIdxOID].aiAlgid; dwIdxOID++) {
1493 if (aOIDDescriptor[dwIdxOID].aiAlgid == aiAlgid) break;
1496 if (!aOIDDescriptor[dwIdxOID].aiAlgid) {
1497 SetLastError(NTE_BAD_ALGID);
1498 return FALSE;
1501 /* Build the padded signature */
1502 if (dwFlags & CRYPT_X931_FORMAT) {
1503 pbSignature[0] = 0x6b;
1504 for (i=1; i < dwLen - dwHashLen - 3; i++) {
1505 pbSignature[i] = 0xbb;
1507 pbSignature[i++] = 0xba;
1508 for (j=0; j < dwHashLen; j++, i++) {
1509 pbSignature[i] = abHashValue[j];
1511 pbSignature[i++] = 0x33;
1512 pbSignature[i++] = 0xcc;
1513 } else {
1514 pbSignature[0] = 0x00;
1515 pbSignature[1] = 0x01;
1516 if (dwFlags & CRYPT_NOHASHOID) {
1517 for (i=2; i < dwLen - 1 - dwHashLen; i++) {
1518 pbSignature[i] = 0xff;
1520 pbSignature[i++] = 0x00;
1521 } else {
1522 for (i=2; i < dwLen - 1 - aOIDDescriptor[dwIdxOID].dwLen - dwHashLen; i++) {
1523 pbSignature[i] = 0xff;
1525 pbSignature[i++] = 0x00;
1526 for (j=0; j < aOIDDescriptor[dwIdxOID].dwLen; j++) {
1527 pbSignature[i++] = aOIDDescriptor[dwIdxOID].abOID[j];
1530 for (j=0; j < dwHashLen; j++) {
1531 pbSignature[i++] = abHashValue[j];
1535 return TRUE;
1538 /******************************************************************************
1539 * tls1_p [Internal]
1541 * This is an implementation of the 'P_hash' helper function for TLS1's PRF.
1542 * It is used exclusively by tls1_prf. For details see RFC 2246, chapter 5.
1543 * The pseudo random stream generated by this function is exclusive or'ed with
1544 * the data in pbBuffer.
1546 * PARAMS
1547 * hHMAC [I] HMAC object, which will be used in pseudo random generation
1548 * pblobSeed [I] Seed value
1549 * pbBuffer [I/O] Pseudo random stream will be xor'ed to the provided data
1550 * dwBufferLen [I] Number of pseudo random bytes desired
1552 * RETURNS
1553 * Success: TRUE
1554 * Failure: FALSE
1556 static BOOL tls1_p(HCRYPTHASH hHMAC, const PCRYPT_DATA_BLOB pblobSeed, BYTE *pbBuffer,
1557 DWORD dwBufferLen)
1559 CRYPTHASH *pHMAC;
1560 BYTE abAi[RSAENH_MAX_HASH_SIZE];
1561 DWORD i = 0;
1563 if (!lookup_handle(&handle_table, hHMAC, RSAENH_MAGIC_HASH, (OBJECTHDR**)&pHMAC)) {
1564 SetLastError(NTE_BAD_HASH);
1565 return FALSE;
1568 /* compute A_1 = HMAC(seed) */
1569 init_hash(pHMAC);
1570 update_hash(pHMAC, pblobSeed->pbData, pblobSeed->cbData);
1571 finalize_hash(pHMAC);
1572 memcpy(abAi, pHMAC->abHashValue, pHMAC->dwHashSize);
1574 do {
1575 /* compute HMAC(A_i + seed) */
1576 init_hash(pHMAC);
1577 update_hash(pHMAC, abAi, pHMAC->dwHashSize);
1578 update_hash(pHMAC, pblobSeed->pbData, pblobSeed->cbData);
1579 finalize_hash(pHMAC);
1581 /* pseudo random stream := CONCAT_{i=1..n} ( HMAC(A_i + seed) ) */
1582 do {
1583 if (i >= dwBufferLen) break;
1584 pbBuffer[i] ^= pHMAC->abHashValue[i % pHMAC->dwHashSize];
1585 i++;
1586 } while (i % pHMAC->dwHashSize);
1588 /* compute A_{i+1} = HMAC(A_i) */
1589 init_hash(pHMAC);
1590 update_hash(pHMAC, abAi, pHMAC->dwHashSize);
1591 finalize_hash(pHMAC);
1592 memcpy(abAi, pHMAC->abHashValue, pHMAC->dwHashSize);
1593 } while (i < dwBufferLen);
1595 return TRUE;
1598 /******************************************************************************
1599 * tls1_prf [Internal]
1601 * TLS1 pseudo random function as specified in RFC 2246, chapter 5
1603 * PARAMS
1604 * hProv [I] Key container used to compute the pseudo random stream
1605 * hSecret [I] Key that holds the (pre-)master secret
1606 * pblobLabel [I] Descriptive label
1607 * pblobSeed [I] Seed value
1608 * pbBuffer [O] Pseudo random numbers will be stored here
1609 * dwBufferLen [I] Number of pseudo random bytes desired
1611 * RETURNS
1612 * Success: TRUE
1613 * Failure: FALSE
1615 static BOOL tls1_prf(HCRYPTPROV hProv, HCRYPTPROV hSecret, const PCRYPT_DATA_BLOB pblobLabel,
1616 const PCRYPT_DATA_BLOB pblobSeed, BYTE *pbBuffer, DWORD dwBufferLen)
1618 HMAC_INFO hmacInfo = { 0, NULL, 0, NULL, 0 };
1619 HCRYPTHASH hHMAC = (HCRYPTHASH)INVALID_HANDLE_VALUE;
1620 HCRYPTKEY hHalfSecret = (HCRYPTKEY)INVALID_HANDLE_VALUE;
1621 CRYPTKEY *pHalfSecret, *pSecret;
1622 DWORD dwHalfSecretLen;
1623 BOOL result = FALSE;
1624 CRYPT_DATA_BLOB blobLabelSeed;
1626 TRACE("(hProv=%08lx, hSecret=%08lx, pblobLabel=%p, pblobSeed=%p, pbBuffer=%p, dwBufferLen=%d)\n",
1627 hProv, hSecret, pblobLabel, pblobSeed, pbBuffer, dwBufferLen);
1629 if (!lookup_handle(&handle_table, hSecret, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pSecret)) {
1630 SetLastError(NTE_FAIL);
1631 return FALSE;
1634 dwHalfSecretLen = (pSecret->dwKeyLen+1)/2;
1636 /* concatenation of the label and the seed */
1637 if (!concat_data_blobs(&blobLabelSeed, pblobLabel, pblobSeed)) goto exit;
1639 /* zero out the buffer, since two random streams will be xor'ed into it. */
1640 memset(pbBuffer, 0, dwBufferLen);
1642 /* build a 'fake' key, to hold the secret. CALG_SSL2_MASTER is used since it provides
1643 * the biggest range of valid key lengths. */
1644 hHalfSecret = new_key(hProv, CALG_SSL2_MASTER, MAKELONG(0,dwHalfSecretLen*8), &pHalfSecret);
1645 if (hHalfSecret == (HCRYPTKEY)INVALID_HANDLE_VALUE) goto exit;
1647 /* Derive an HMAC_MD5 hash and call the helper function. */
1648 memcpy(pHalfSecret->abKeyValue, pSecret->abKeyValue, dwHalfSecretLen);
1649 if (!RSAENH_CPCreateHash(hProv, CALG_HMAC, hHalfSecret, 0, &hHMAC)) goto exit;
1650 hmacInfo.HashAlgid = CALG_MD5;
1651 if (!RSAENH_CPSetHashParam(hProv, hHMAC, HP_HMAC_INFO, (BYTE*)&hmacInfo, 0)) goto exit;
1652 if (!tls1_p(hHMAC, &blobLabelSeed, pbBuffer, dwBufferLen)) goto exit;
1654 /* Reconfigure to HMAC_SHA hash and call helper function again. */
1655 memcpy(pHalfSecret->abKeyValue, pSecret->abKeyValue + (pSecret->dwKeyLen/2), dwHalfSecretLen);
1656 hmacInfo.HashAlgid = CALG_SHA;
1657 if (!RSAENH_CPSetHashParam(hProv, hHMAC, HP_HMAC_INFO, (BYTE*)&hmacInfo, 0)) goto exit;
1658 if (!tls1_p(hHMAC, &blobLabelSeed, pbBuffer, dwBufferLen)) goto exit;
1660 result = TRUE;
1661 exit:
1662 release_handle(&handle_table, hHalfSecret, RSAENH_MAGIC_KEY);
1663 if (hHMAC != (HCRYPTHASH)INVALID_HANDLE_VALUE) RSAENH_CPDestroyHash(hProv, hHMAC);
1664 free_data_blob(&blobLabelSeed);
1665 return result;
1668 /******************************************************************************
1669 * pad_data [Internal]
1671 * Helper function for data padding according to PKCS1 #2
1673 * PARAMS
1674 * abData [I] The data to be padded
1675 * dwDataLen [I] Length of the data
1676 * abBuffer [O] Padded data will be stored here
1677 * dwBufferLen [I] Length of the buffer (also length of padded data)
1678 * dwFlags [I] Padding format (CRYPT_SSL2_FALLBACK)
1680 * RETURN
1681 * Success: TRUE
1682 * Failure: FALSE (NTE_BAD_LEN, too much data to pad)
1684 static BOOL pad_data(const BYTE *abData, DWORD dwDataLen, BYTE *abBuffer, DWORD dwBufferLen,
1685 DWORD dwFlags)
1687 DWORD i;
1689 /* Ensure there is enough space for PKCS1 #2 padding */
1690 if (dwDataLen > dwBufferLen-11) {
1691 SetLastError(NTE_BAD_LEN);
1692 return FALSE;
1695 memmove(abBuffer + dwBufferLen - dwDataLen, abData, dwDataLen);
1697 abBuffer[0] = 0x00;
1698 abBuffer[1] = RSAENH_PKC_BLOCKTYPE;
1699 for (i=2; i < dwBufferLen - dwDataLen - 1; i++)
1700 do gen_rand_impl(&abBuffer[i], 1); while (!abBuffer[i]);
1701 if (dwFlags & CRYPT_SSL2_FALLBACK)
1702 for (i-=8; i < dwBufferLen - dwDataLen - 1; i++)
1703 abBuffer[i] = 0x03;
1704 abBuffer[i] = 0x00;
1706 return TRUE;
1709 /******************************************************************************
1710 * unpad_data [Internal]
1712 * Remove the PKCS1 padding from RSA decrypted data
1714 * PARAMS
1715 * abData [I] The padded data
1716 * dwDataLen [I] Length of the padded data
1717 * abBuffer [O] Data without padding will be stored here
1718 * dwBufferLen [I/O] I: Length of the buffer, O: Length of unpadded data
1719 * dwFlags [I] Currently none defined
1721 * RETURNS
1722 * Success: TRUE
1723 * Failure: FALSE, (NTE_BAD_DATA, no valid PKCS1 padding or buffer too small)
1725 static BOOL unpad_data(const BYTE *abData, DWORD dwDataLen, BYTE *abBuffer, DWORD *dwBufferLen,
1726 DWORD dwFlags)
1728 DWORD i;
1730 if (dwDataLen < 3)
1732 SetLastError(NTE_BAD_DATA);
1733 return FALSE;
1735 for (i=2; i<dwDataLen; i++)
1736 if (!abData[i])
1737 break;
1739 if ((i == dwDataLen) || (*dwBufferLen < dwDataLen - i - 1) ||
1740 (abData[0] != 0x00) || (abData[1] != RSAENH_PKC_BLOCKTYPE))
1742 SetLastError(NTE_BAD_DATA);
1743 return FALSE;
1746 *dwBufferLen = dwDataLen - i - 1;
1747 memmove(abBuffer, abData + i + 1, *dwBufferLen);
1748 return TRUE;
1751 /******************************************************************************
1752 * CPAcquireContext (RSAENH.@)
1754 * Acquire a handle to the key container specified by pszContainer
1756 * PARAMS
1757 * phProv [O] Pointer to the location the acquired handle will be written to.
1758 * pszContainer [I] Name of the desired key container. See Notes
1759 * dwFlags [I] Flags. See Notes.
1760 * pVTable [I] Pointer to a PVTableProvStruct containing callbacks.
1762 * RETURNS
1763 * Success: TRUE
1764 * Failure: FALSE
1766 * NOTES
1767 * If pszContainer is NULL or points to a zero length string the user's login
1768 * name will be used as the key container name.
1770 * If the CRYPT_NEW_KEYSET flag is set in dwFlags a new keyset will be created.
1771 * If a keyset with the given name already exists, the function fails and sets
1772 * last error to NTE_EXISTS. If CRYPT_NEW_KEYSET is not set and the specified
1773 * key container does not exist, function fails and sets last error to
1774 * NTE_BAD_KEYSET.
1776 BOOL WINAPI RSAENH_CPAcquireContext(HCRYPTPROV *phProv, LPSTR pszContainer,
1777 DWORD dwFlags, PVTableProvStruc pVTable)
1779 CHAR szKeyContainerName[MAX_PATH];
1781 TRACE("(phProv=%p, pszContainer=%s, dwFlags=%08x, pVTable=%p)\n", phProv,
1782 debugstr_a(pszContainer), dwFlags, pVTable);
1784 if (pszContainer && *pszContainer)
1786 lstrcpynA(szKeyContainerName, pszContainer, MAX_PATH);
1788 else
1790 DWORD dwLen = sizeof(szKeyContainerName);
1791 if (!GetUserNameA(szKeyContainerName, &dwLen)) return FALSE;
1794 switch (dwFlags & (CRYPT_NEWKEYSET|CRYPT_VERIFYCONTEXT|CRYPT_DELETEKEYSET))
1796 case 0:
1797 *phProv = read_key_container(szKeyContainerName, dwFlags, pVTable);
1798 break;
1800 case CRYPT_DELETEKEYSET:
1801 return delete_container_key(szKeyContainerName, dwFlags);
1803 case CRYPT_NEWKEYSET:
1804 *phProv = read_key_container(szKeyContainerName, dwFlags, pVTable);
1805 if (*phProv != (HCRYPTPROV)INVALID_HANDLE_VALUE)
1807 release_handle(&handle_table, *phProv, RSAENH_MAGIC_CONTAINER);
1808 TRACE("Can't create new keyset, already exists\n");
1809 SetLastError(NTE_EXISTS);
1810 return FALSE;
1812 *phProv = new_key_container(szKeyContainerName, dwFlags, pVTable);
1813 break;
1815 case CRYPT_VERIFYCONTEXT|CRYPT_NEWKEYSET:
1816 case CRYPT_VERIFYCONTEXT:
1817 if (pszContainer && *pszContainer) {
1818 TRACE("pszContainer should be empty\n");
1819 SetLastError(NTE_BAD_FLAGS);
1820 return FALSE;
1822 *phProv = new_key_container("", dwFlags, pVTable);
1823 break;
1825 default:
1826 *phProv = (HCRYPTPROV)INVALID_HANDLE_VALUE;
1827 SetLastError(NTE_BAD_FLAGS);
1828 return FALSE;
1831 if (*phProv != (HCRYPTPROV)INVALID_HANDLE_VALUE) {
1832 SetLastError(ERROR_SUCCESS);
1833 return TRUE;
1834 } else {
1835 return FALSE;
1839 /******************************************************************************
1840 * CPCreateHash (RSAENH.@)
1842 * CPCreateHash creates and initializes a new hash object.
1844 * PARAMS
1845 * hProv [I] Handle to the key container to which the new hash will belong.
1846 * Algid [I] Identifies the hash algorithm, which will be used for the hash.
1847 * hKey [I] Handle to a session key applied for keyed hashes.
1848 * dwFlags [I] Currently no flags defined. Must be zero.
1849 * phHash [O] Points to the location where a handle to the new hash will be stored.
1851 * RETURNS
1852 * Success: TRUE
1853 * Failure: FALSE
1855 * NOTES
1856 * hKey is a handle to a session key applied in keyed hashes like MAC and HMAC.
1857 * If a normal hash object is to be created (like e.g. MD2 or SHA1) hKey must be zero.
1859 BOOL WINAPI RSAENH_CPCreateHash(HCRYPTPROV hProv, ALG_ID Algid, HCRYPTKEY hKey, DWORD dwFlags,
1860 HCRYPTHASH *phHash)
1862 CRYPTKEY *pCryptKey;
1863 CRYPTHASH *pCryptHash;
1864 const PROV_ENUMALGS_EX *peaAlgidInfo;
1866 TRACE("(hProv=%08lx, Algid=%08x, hKey=%08lx, dwFlags=%08x, phHash=%p)\n", hProv, Algid, hKey,
1867 dwFlags, phHash);
1869 peaAlgidInfo = get_algid_info(hProv, Algid);
1870 if (!peaAlgidInfo) return FALSE;
1872 if (dwFlags)
1874 SetLastError(NTE_BAD_FLAGS);
1875 return FALSE;
1878 if (Algid == CALG_MAC || Algid == CALG_HMAC || Algid == CALG_SCHANNEL_MASTER_HASH ||
1879 Algid == CALG_TLS1PRF)
1881 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey)) {
1882 SetLastError(NTE_BAD_KEY);
1883 return FALSE;
1886 if ((Algid == CALG_MAC) && (GET_ALG_TYPE(pCryptKey->aiAlgid) != ALG_TYPE_BLOCK)) {
1887 SetLastError(NTE_BAD_KEY);
1888 return FALSE;
1891 if ((Algid == CALG_SCHANNEL_MASTER_HASH || Algid == CALG_TLS1PRF) &&
1892 (pCryptKey->aiAlgid != CALG_TLS1_MASTER))
1894 SetLastError(NTE_BAD_KEY);
1895 return FALSE;
1897 if (Algid == CALG_SCHANNEL_MASTER_HASH &&
1898 ((!pCryptKey->siSChannelInfo.blobClientRandom.cbData) ||
1899 (!pCryptKey->siSChannelInfo.blobServerRandom.cbData)))
1901 SetLastError(ERROR_INVALID_PARAMETER);
1902 return FALSE;
1905 if ((Algid == CALG_TLS1PRF) && (pCryptKey->dwState != RSAENH_KEYSTATE_MASTERKEY)) {
1906 SetLastError(NTE_BAD_KEY_STATE);
1907 return FALSE;
1911 *phHash = new_object(&handle_table, sizeof(CRYPTHASH), RSAENH_MAGIC_HASH,
1912 destroy_hash, (OBJECTHDR**)&pCryptHash);
1913 if (!pCryptHash) return FALSE;
1915 pCryptHash->aiAlgid = Algid;
1916 pCryptHash->hKey = hKey;
1917 pCryptHash->hProv = hProv;
1918 pCryptHash->dwState = RSAENH_HASHSTATE_HASHING;
1919 pCryptHash->pHMACInfo = NULL;
1920 pCryptHash->dwHashSize = peaAlgidInfo->dwDefaultLen >> 3;
1921 init_data_blob(&pCryptHash->tpPRFParams.blobLabel);
1922 init_data_blob(&pCryptHash->tpPRFParams.blobSeed);
1924 if (Algid == CALG_SCHANNEL_MASTER_HASH) {
1925 static const char keyex[] = "key expansion";
1926 BYTE key_expansion[sizeof keyex];
1927 CRYPT_DATA_BLOB blobRandom, blobKeyExpansion = { 13, key_expansion };
1929 memcpy( key_expansion, keyex, sizeof keyex );
1931 if (pCryptKey->dwState != RSAENH_KEYSTATE_MASTERKEY) {
1932 static const char msec[] = "master secret";
1933 BYTE master_secret[sizeof msec];
1934 CRYPT_DATA_BLOB blobLabel = { 13, master_secret };
1935 BYTE abKeyValue[48];
1937 memcpy( master_secret, msec, sizeof msec );
1939 /* See RFC 2246, chapter 8.1 */
1940 if (!concat_data_blobs(&blobRandom,
1941 &pCryptKey->siSChannelInfo.blobClientRandom,
1942 &pCryptKey->siSChannelInfo.blobServerRandom))
1944 return FALSE;
1946 tls1_prf(hProv, hKey, &blobLabel, &blobRandom, abKeyValue, 48);
1947 pCryptKey->dwState = RSAENH_KEYSTATE_MASTERKEY;
1948 memcpy(pCryptKey->abKeyValue, abKeyValue, 48);
1949 free_data_blob(&blobRandom);
1952 /* See RFC 2246, chapter 6.3 */
1953 if (!concat_data_blobs(&blobRandom,
1954 &pCryptKey->siSChannelInfo.blobServerRandom,
1955 &pCryptKey->siSChannelInfo.blobClientRandom))
1957 return FALSE;
1959 tls1_prf(hProv, hKey, &blobKeyExpansion, &blobRandom, pCryptHash->abHashValue,
1960 RSAENH_MAX_HASH_SIZE);
1961 free_data_blob(&blobRandom);
1964 return init_hash(pCryptHash);
1967 /******************************************************************************
1968 * CPDestroyHash (RSAENH.@)
1970 * Releases the handle to a hash object. The object is destroyed if its reference
1971 * count reaches zero.
1973 * PARAMS
1974 * hProv [I] Handle to the key container to which the hash object belongs.
1975 * hHash [I] Handle to the hash object to be released.
1977 * RETURNS
1978 * Success: TRUE
1979 * Failure: FALSE
1981 BOOL WINAPI RSAENH_CPDestroyHash(HCRYPTPROV hProv, HCRYPTHASH hHash)
1983 TRACE("(hProv=%08lx, hHash=%08lx)\n", hProv, hHash);
1985 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
1987 SetLastError(NTE_BAD_UID);
1988 return FALSE;
1991 if (!release_handle(&handle_table, hHash, RSAENH_MAGIC_HASH))
1993 SetLastError(NTE_BAD_HASH);
1994 return FALSE;
1997 return TRUE;
2000 /******************************************************************************
2001 * CPDestroyKey (RSAENH.@)
2003 * Releases the handle to a key object. The object is destroyed if its reference
2004 * count reaches zero.
2006 * PARAMS
2007 * hProv [I] Handle to the key container to which the key object belongs.
2008 * hKey [I] Handle to the key object to be released.
2010 * RETURNS
2011 * Success: TRUE
2012 * Failure: FALSE
2014 BOOL WINAPI RSAENH_CPDestroyKey(HCRYPTPROV hProv, HCRYPTKEY hKey)
2016 TRACE("(hProv=%08lx, hKey=%08lx)\n", hProv, hKey);
2018 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2020 SetLastError(NTE_BAD_UID);
2021 return FALSE;
2024 if (!release_handle(&handle_table, hKey, RSAENH_MAGIC_KEY))
2026 SetLastError(NTE_BAD_KEY);
2027 return FALSE;
2030 return TRUE;
2033 /******************************************************************************
2034 * CPDuplicateHash (RSAENH.@)
2036 * Clones a hash object including its current state.
2038 * PARAMS
2039 * hUID [I] Handle to the key container the hash belongs to.
2040 * hHash [I] Handle to the hash object to be cloned.
2041 * pdwReserved [I] Reserved. Must be NULL.
2042 * dwFlags [I] No flags are currently defined. Must be 0.
2043 * phHash [O] Handle to the cloned hash object.
2045 * RETURNS
2046 * Success: TRUE.
2047 * Failure: FALSE.
2049 BOOL WINAPI RSAENH_CPDuplicateHash(HCRYPTPROV hUID, HCRYPTHASH hHash, DWORD *pdwReserved,
2050 DWORD dwFlags, HCRYPTHASH *phHash)
2052 CRYPTHASH *pSrcHash, *pDestHash;
2054 TRACE("(hUID=%08lx, hHash=%08lx, pdwReserved=%p, dwFlags=%08x, phHash=%p)\n", hUID, hHash,
2055 pdwReserved, dwFlags, phHash);
2057 if (!is_valid_handle(&handle_table, hUID, RSAENH_MAGIC_CONTAINER))
2059 SetLastError(NTE_BAD_UID);
2060 return FALSE;
2063 if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH, (OBJECTHDR**)&pSrcHash))
2065 SetLastError(NTE_BAD_HASH);
2066 return FALSE;
2069 if (!phHash || pdwReserved || dwFlags)
2071 SetLastError(ERROR_INVALID_PARAMETER);
2072 return FALSE;
2075 *phHash = new_object(&handle_table, sizeof(CRYPTHASH), RSAENH_MAGIC_HASH,
2076 destroy_hash, (OBJECTHDR**)&pDestHash);
2077 if (*phHash != (HCRYPTHASH)INVALID_HANDLE_VALUE)
2079 *pDestHash = *pSrcHash;
2080 duplicate_hash_impl(pSrcHash->aiAlgid, &pSrcHash->context, &pDestHash->context);
2081 copy_hmac_info(&pDestHash->pHMACInfo, pSrcHash->pHMACInfo);
2082 copy_data_blob(&pDestHash->tpPRFParams.blobLabel, &pSrcHash->tpPRFParams.blobLabel);
2083 copy_data_blob(&pDestHash->tpPRFParams.blobSeed, &pSrcHash->tpPRFParams.blobSeed);
2086 return *phHash != (HCRYPTHASH)INVALID_HANDLE_VALUE;
2089 /******************************************************************************
2090 * CPDuplicateKey (RSAENH.@)
2092 * Clones a key object including its current state.
2094 * PARAMS
2095 * hUID [I] Handle to the key container the hash belongs to.
2096 * hKey [I] Handle to the key object to be cloned.
2097 * pdwReserved [I] Reserved. Must be NULL.
2098 * dwFlags [I] No flags are currently defined. Must be 0.
2099 * phHash [O] Handle to the cloned key object.
2101 * RETURNS
2102 * Success: TRUE.
2103 * Failure: FALSE.
2105 BOOL WINAPI RSAENH_CPDuplicateKey(HCRYPTPROV hUID, HCRYPTKEY hKey, DWORD *pdwReserved,
2106 DWORD dwFlags, HCRYPTKEY *phKey)
2108 CRYPTKEY *pSrcKey, *pDestKey;
2110 TRACE("(hUID=%08lx, hKey=%08lx, pdwReserved=%p, dwFlags=%08x, phKey=%p)\n", hUID, hKey,
2111 pdwReserved, dwFlags, phKey);
2113 if (!is_valid_handle(&handle_table, hUID, RSAENH_MAGIC_CONTAINER))
2115 SetLastError(NTE_BAD_UID);
2116 return FALSE;
2119 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pSrcKey))
2121 SetLastError(NTE_BAD_KEY);
2122 return FALSE;
2125 if (!phKey || pdwReserved || dwFlags)
2127 SetLastError(ERROR_INVALID_PARAMETER);
2128 return FALSE;
2131 *phKey = new_object(&handle_table, sizeof(CRYPTKEY), RSAENH_MAGIC_KEY, destroy_key,
2132 (OBJECTHDR**)&pDestKey);
2133 if (*phKey != (HCRYPTKEY)INVALID_HANDLE_VALUE)
2135 *pDestKey = *pSrcKey;
2136 copy_data_blob(&pDestKey->siSChannelInfo.blobServerRandom,
2137 &pSrcKey->siSChannelInfo.blobServerRandom);
2138 copy_data_blob(&pDestKey->siSChannelInfo.blobClientRandom,
2139 &pSrcKey->siSChannelInfo.blobClientRandom);
2140 duplicate_key_impl(pSrcKey->aiAlgid, &pSrcKey->context, &pDestKey->context);
2141 return TRUE;
2143 else
2145 return FALSE;
2149 /******************************************************************************
2150 * CPEncrypt (RSAENH.@)
2152 * Encrypt data.
2154 * PARAMS
2155 * hProv [I] The key container hKey and hHash belong to.
2156 * hKey [I] The key used to encrypt the data.
2157 * hHash [I] An optional hash object for parallel hashing. See notes.
2158 * Final [I] Indicates if this is the last block of data to encrypt.
2159 * dwFlags [I] Currently no flags defined. Must be zero.
2160 * pbData [I/O] Pointer to the data to encrypt. Encrypted data will also be stored there.
2161 * pdwDataLen [I/O] I: Length of data to encrypt, O: Length of encrypted data.
2162 * dwBufLen [I] Size of the buffer at pbData.
2164 * RETURNS
2165 * Success: TRUE.
2166 * Failure: FALSE.
2168 * NOTES
2169 * If a hash object handle is provided in hHash, it will be updated with the plaintext.
2170 * This is useful for message signatures.
2172 * This function uses the standard WINAPI protocol for querying data of dynamic length.
2174 BOOL WINAPI RSAENH_CPEncrypt(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final,
2175 DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen, DWORD dwBufLen)
2177 CRYPTKEY *pCryptKey;
2178 BYTE *in, out[RSAENH_MAX_BLOCK_SIZE], o[RSAENH_MAX_BLOCK_SIZE];
2179 DWORD dwEncryptedLen, i, j, k;
2181 TRACE("(hProv=%08lx, hKey=%08lx, hHash=%08lx, Final=%d, dwFlags=%08x, pbData=%p, "
2182 "pdwDataLen=%p, dwBufLen=%d)\n", hProv, hKey, hHash, Final, dwFlags, pbData, pdwDataLen,
2183 dwBufLen);
2185 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2187 SetLastError(NTE_BAD_UID);
2188 return FALSE;
2191 if (dwFlags)
2193 SetLastError(NTE_BAD_FLAGS);
2194 return FALSE;
2197 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2199 SetLastError(NTE_BAD_KEY);
2200 return FALSE;
2203 if (pCryptKey->dwState == RSAENH_KEYSTATE_IDLE)
2204 pCryptKey->dwState = RSAENH_KEYSTATE_ENCRYPTING;
2206 if (pCryptKey->dwState != RSAENH_KEYSTATE_ENCRYPTING)
2208 SetLastError(NTE_BAD_DATA);
2209 return FALSE;
2212 if (is_valid_handle(&handle_table, hHash, RSAENH_MAGIC_HASH)) {
2213 if (!RSAENH_CPHashData(hProv, hHash, pbData, *pdwDataLen, 0)) return FALSE;
2216 if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_BLOCK) {
2217 if (!Final && (*pdwDataLen % pCryptKey->dwBlockLen)) {
2218 SetLastError(NTE_BAD_DATA);
2219 return FALSE;
2222 dwEncryptedLen = (*pdwDataLen/pCryptKey->dwBlockLen+(Final?1:0))*pCryptKey->dwBlockLen;
2224 if (pbData == NULL) {
2225 *pdwDataLen = dwEncryptedLen;
2226 return TRUE;
2228 else if (dwEncryptedLen > dwBufLen) {
2229 *pdwDataLen = dwEncryptedLen;
2230 SetLastError(ERROR_MORE_DATA);
2231 return FALSE;
2234 /* Pad final block with length bytes */
2235 for (i=*pdwDataLen; i<dwEncryptedLen; i++) pbData[i] = dwEncryptedLen - *pdwDataLen;
2236 *pdwDataLen = dwEncryptedLen;
2238 for (i=0, in=pbData; i<*pdwDataLen; i+=pCryptKey->dwBlockLen, in+=pCryptKey->dwBlockLen) {
2239 switch (pCryptKey->dwMode) {
2240 case CRYPT_MODE_ECB:
2241 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out,
2242 RSAENH_ENCRYPT);
2243 break;
2245 case CRYPT_MODE_CBC:
2246 for (j=0; j<pCryptKey->dwBlockLen; j++) in[j] ^= pCryptKey->abChainVector[j];
2247 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out,
2248 RSAENH_ENCRYPT);
2249 memcpy(pCryptKey->abChainVector, out, pCryptKey->dwBlockLen);
2250 break;
2252 case CRYPT_MODE_CFB:
2253 for (j=0; j<pCryptKey->dwBlockLen; j++) {
2254 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context,
2255 pCryptKey->abChainVector, o, RSAENH_ENCRYPT);
2256 out[j] = in[j] ^ o[0];
2257 for (k=0; k<pCryptKey->dwBlockLen-1; k++)
2258 pCryptKey->abChainVector[k] = pCryptKey->abChainVector[k+1];
2259 pCryptKey->abChainVector[k] = out[j];
2261 break;
2263 default:
2264 SetLastError(NTE_BAD_ALGID);
2265 return FALSE;
2267 memcpy(in, out, pCryptKey->dwBlockLen);
2269 } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_STREAM) {
2270 if (pbData == NULL) {
2271 *pdwDataLen = dwBufLen;
2272 return TRUE;
2274 encrypt_stream_impl(pCryptKey->aiAlgid, &pCryptKey->context, pbData, *pdwDataLen);
2275 } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_RSA) {
2276 if (pCryptKey->aiAlgid == CALG_RSA_SIGN) {
2277 SetLastError(NTE_BAD_KEY);
2278 return FALSE;
2280 if (!pbData) {
2281 *pdwDataLen = pCryptKey->dwBlockLen;
2282 return TRUE;
2284 if (dwBufLen < pCryptKey->dwBlockLen) {
2285 SetLastError(ERROR_MORE_DATA);
2286 return FALSE;
2288 if (!pad_data(pbData, *pdwDataLen, pbData, pCryptKey->dwBlockLen, dwFlags)) return FALSE;
2289 encrypt_block_impl(pCryptKey->aiAlgid, PK_PUBLIC, &pCryptKey->context, pbData, pbData, RSAENH_ENCRYPT);
2290 *pdwDataLen = pCryptKey->dwBlockLen;
2291 Final = TRUE;
2292 } else {
2293 SetLastError(NTE_BAD_TYPE);
2294 return FALSE;
2297 if (Final) setup_key(pCryptKey);
2299 return TRUE;
2302 /******************************************************************************
2303 * CPDecrypt (RSAENH.@)
2305 * Decrypt data.
2307 * PARAMS
2308 * hProv [I] The key container hKey and hHash belong to.
2309 * hKey [I] The key used to decrypt the data.
2310 * hHash [I] An optional hash object for parallel hashing. See notes.
2311 * Final [I] Indicates if this is the last block of data to decrypt.
2312 * dwFlags [I] Currently no flags defined. Must be zero.
2313 * pbData [I/O] Pointer to the data to decrypt. Plaintext will also be stored there.
2314 * pdwDataLen [I/O] I: Length of ciphertext, O: Length of plaintext.
2316 * RETURNS
2317 * Success: TRUE.
2318 * Failure: FALSE.
2320 * NOTES
2321 * If a hash object handle is provided in hHash, it will be updated with the plaintext.
2322 * This is useful for message signatures.
2324 * This function uses the standard WINAPI protocol for querying data of dynamic length.
2326 BOOL WINAPI RSAENH_CPDecrypt(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final,
2327 DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2329 CRYPTKEY *pCryptKey;
2330 BYTE *in, out[RSAENH_MAX_BLOCK_SIZE], o[RSAENH_MAX_BLOCK_SIZE];
2331 DWORD i, j, k;
2332 DWORD dwMax;
2334 TRACE("(hProv=%08lx, hKey=%08lx, hHash=%08lx, Final=%d, dwFlags=%08x, pbData=%p, "
2335 "pdwDataLen=%p)\n", hProv, hKey, hHash, Final, dwFlags, pbData, pdwDataLen);
2337 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2339 SetLastError(NTE_BAD_UID);
2340 return FALSE;
2343 if (dwFlags)
2345 SetLastError(NTE_BAD_FLAGS);
2346 return FALSE;
2349 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2351 SetLastError(NTE_BAD_KEY);
2352 return FALSE;
2355 if (pCryptKey->dwState == RSAENH_KEYSTATE_IDLE)
2356 pCryptKey->dwState = RSAENH_KEYSTATE_ENCRYPTING;
2358 if (pCryptKey->dwState != RSAENH_KEYSTATE_ENCRYPTING)
2360 SetLastError(NTE_BAD_DATA);
2361 return FALSE;
2364 dwMax=*pdwDataLen;
2366 if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_BLOCK) {
2367 for (i=0, in=pbData; i<*pdwDataLen; i+=pCryptKey->dwBlockLen, in+=pCryptKey->dwBlockLen) {
2368 switch (pCryptKey->dwMode) {
2369 case CRYPT_MODE_ECB:
2370 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out,
2371 RSAENH_DECRYPT);
2372 break;
2374 case CRYPT_MODE_CBC:
2375 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out,
2376 RSAENH_DECRYPT);
2377 for (j=0; j<pCryptKey->dwBlockLen; j++) out[j] ^= pCryptKey->abChainVector[j];
2378 memcpy(pCryptKey->abChainVector, in, pCryptKey->dwBlockLen);
2379 break;
2381 case CRYPT_MODE_CFB:
2382 for (j=0; j<pCryptKey->dwBlockLen; j++) {
2383 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context,
2384 pCryptKey->abChainVector, o, RSAENH_ENCRYPT);
2385 out[j] = in[j] ^ o[0];
2386 for (k=0; k<pCryptKey->dwBlockLen-1; k++)
2387 pCryptKey->abChainVector[k] = pCryptKey->abChainVector[k+1];
2388 pCryptKey->abChainVector[k] = in[j];
2390 break;
2392 default:
2393 SetLastError(NTE_BAD_ALGID);
2394 return FALSE;
2396 memcpy(in, out, pCryptKey->dwBlockLen);
2398 if (Final) {
2399 if (pbData[*pdwDataLen-1] &&
2400 pbData[*pdwDataLen-1] <= pCryptKey->dwBlockLen &&
2401 pbData[*pdwDataLen-1] <= *pdwDataLen) {
2402 BOOL padOkay = TRUE;
2404 /* check that every bad byte has the same value */
2405 for (i = 1; padOkay && i < pbData[*pdwDataLen-1]; i++)
2406 if (pbData[*pdwDataLen - i - 1] != pbData[*pdwDataLen - 1])
2407 padOkay = FALSE;
2408 if (padOkay)
2409 *pdwDataLen -= pbData[*pdwDataLen-1];
2410 else {
2411 SetLastError(NTE_BAD_DATA);
2412 setup_key(pCryptKey);
2413 return FALSE;
2416 else {
2417 SetLastError(NTE_BAD_DATA);
2418 setup_key(pCryptKey);
2419 return FALSE;
2423 } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_STREAM) {
2424 encrypt_stream_impl(pCryptKey->aiAlgid, &pCryptKey->context, pbData, *pdwDataLen);
2425 } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_RSA) {
2426 if (pCryptKey->aiAlgid == CALG_RSA_SIGN) {
2427 SetLastError(NTE_BAD_KEY);
2428 return FALSE;
2430 encrypt_block_impl(pCryptKey->aiAlgid, PK_PRIVATE, &pCryptKey->context, pbData, pbData, RSAENH_DECRYPT);
2431 if (!unpad_data(pbData, pCryptKey->dwBlockLen, pbData, pdwDataLen, dwFlags)) return FALSE;
2432 Final = TRUE;
2433 } else {
2434 SetLastError(NTE_BAD_TYPE);
2435 return FALSE;
2438 if (Final) setup_key(pCryptKey);
2440 if (is_valid_handle(&handle_table, hHash, RSAENH_MAGIC_HASH)) {
2441 if (*pdwDataLen>dwMax ||
2442 !RSAENH_CPHashData(hProv, hHash, pbData, *pdwDataLen, 0)) return FALSE;
2445 return TRUE;
2448 static BOOL crypt_export_simple(CRYPTKEY *pCryptKey, CRYPTKEY *pPubKey,
2449 DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2451 BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2452 ALG_ID *pAlgid = (ALG_ID*)(pBlobHeader+1);
2453 DWORD dwDataLen;
2455 if (!(GET_ALG_CLASS(pCryptKey->aiAlgid)&(ALG_CLASS_DATA_ENCRYPT|ALG_CLASS_MSG_ENCRYPT))) {
2456 SetLastError(NTE_BAD_KEY); /* FIXME: error code? */
2457 return FALSE;
2460 dwDataLen = sizeof(BLOBHEADER) + sizeof(ALG_ID) + pPubKey->dwBlockLen;
2461 if (pbData) {
2462 if (*pdwDataLen < dwDataLen) {
2463 SetLastError(ERROR_MORE_DATA);
2464 *pdwDataLen = dwDataLen;
2465 return FALSE;
2468 pBlobHeader->bType = SIMPLEBLOB;
2469 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2470 pBlobHeader->reserved = 0;
2471 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2473 *pAlgid = pPubKey->aiAlgid;
2475 if (!pad_data(pCryptKey->abKeyValue, pCryptKey->dwKeyLen, (BYTE*)(pAlgid+1),
2476 pPubKey->dwBlockLen, dwFlags))
2478 return FALSE;
2481 encrypt_block_impl(pPubKey->aiAlgid, PK_PUBLIC, &pPubKey->context, (BYTE*)(pAlgid+1),
2482 (BYTE*)(pAlgid+1), RSAENH_ENCRYPT);
2484 *pdwDataLen = dwDataLen;
2485 return TRUE;
2488 static BOOL crypt_export_public_key(CRYPTKEY *pCryptKey, BYTE *pbData,
2489 DWORD *pdwDataLen)
2491 BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2492 RSAPUBKEY *pRSAPubKey = (RSAPUBKEY*)(pBlobHeader+1);
2493 DWORD dwDataLen;
2495 if ((pCryptKey->aiAlgid != CALG_RSA_KEYX) && (pCryptKey->aiAlgid != CALG_RSA_SIGN)) {
2496 SetLastError(NTE_BAD_KEY);
2497 return FALSE;
2500 dwDataLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) + pCryptKey->dwKeyLen;
2501 if (pbData) {
2502 if (*pdwDataLen < dwDataLen) {
2503 SetLastError(ERROR_MORE_DATA);
2504 *pdwDataLen = dwDataLen;
2505 return FALSE;
2508 pBlobHeader->bType = PUBLICKEYBLOB;
2509 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2510 pBlobHeader->reserved = 0;
2511 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2513 pRSAPubKey->magic = RSAENH_MAGIC_RSA1;
2514 pRSAPubKey->bitlen = pCryptKey->dwKeyLen << 3;
2516 export_public_key_impl((BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2517 pCryptKey->dwKeyLen, &pRSAPubKey->pubexp);
2519 *pdwDataLen = dwDataLen;
2520 return TRUE;
2523 static BOOL crypt_export_private_key(CRYPTKEY *pCryptKey, BOOL force,
2524 BYTE *pbData, DWORD *pdwDataLen)
2526 BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2527 RSAPUBKEY *pRSAPubKey = (RSAPUBKEY*)(pBlobHeader+1);
2528 DWORD dwDataLen;
2530 if ((pCryptKey->aiAlgid != CALG_RSA_KEYX) && (pCryptKey->aiAlgid != CALG_RSA_SIGN)) {
2531 SetLastError(NTE_BAD_KEY);
2532 return FALSE;
2534 if (!force && !(pCryptKey->dwPermissions & CRYPT_EXPORT))
2536 SetLastError(NTE_BAD_KEY_STATE);
2537 return FALSE;
2540 dwDataLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) +
2541 2 * pCryptKey->dwKeyLen + 5 * ((pCryptKey->dwKeyLen + 1) >> 1);
2542 if (pbData) {
2543 if (*pdwDataLen < dwDataLen) {
2544 SetLastError(ERROR_MORE_DATA);
2545 *pdwDataLen = dwDataLen;
2546 return FALSE;
2549 pBlobHeader->bType = PRIVATEKEYBLOB;
2550 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2551 pBlobHeader->reserved = 0;
2552 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2554 pRSAPubKey->magic = RSAENH_MAGIC_RSA2;
2555 pRSAPubKey->bitlen = pCryptKey->dwKeyLen << 3;
2557 export_private_key_impl((BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2558 pCryptKey->dwKeyLen, &pRSAPubKey->pubexp);
2560 *pdwDataLen = dwDataLen;
2561 return TRUE;
2564 static BOOL crypt_export_plaintext_key(CRYPTKEY *pCryptKey, BYTE *pbData,
2565 DWORD *pdwDataLen)
2567 BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2568 DWORD *pKeyLen = (DWORD*)(pBlobHeader+1);
2569 BYTE *pbKey = (BYTE*)(pKeyLen+1);
2570 DWORD dwDataLen;
2572 dwDataLen = sizeof(BLOBHEADER) + sizeof(DWORD) + pCryptKey->dwKeyLen;
2573 if (pbData) {
2574 if (*pdwDataLen < dwDataLen) {
2575 SetLastError(ERROR_MORE_DATA);
2576 *pdwDataLen = dwDataLen;
2577 return FALSE;
2580 pBlobHeader->bType = PLAINTEXTKEYBLOB;
2581 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2582 pBlobHeader->reserved = 0;
2583 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2585 *pKeyLen = pCryptKey->dwKeyLen;
2586 memcpy(pbKey, pCryptKey->abKeyValue, pCryptKey->dwKeyLen);
2588 *pdwDataLen = dwDataLen;
2589 return TRUE;
2591 /******************************************************************************
2592 * crypt_export_key [Internal]
2594 * Export a key into a binary large object (BLOB). Called by CPExportKey and
2595 * by store_key_pair.
2597 * PARAMS
2598 * pCryptKey [I] Key to be exported.
2599 * hPubKey [I] Key used to encrypt sensitive BLOB data.
2600 * dwBlobType [I] SIMPLEBLOB, PUBLICKEYBLOB or PRIVATEKEYBLOB.
2601 * dwFlags [I] Currently none defined.
2602 * force [I] If TRUE, the key is written no matter what the key's
2603 * permissions are. Otherwise the key's permissions are
2604 * checked before exporting.
2605 * pbData [O] Pointer to a buffer where the BLOB will be written to.
2606 * pdwDataLen [I/O] I: Size of buffer at pbData, O: Size of BLOB
2608 * RETURNS
2609 * Success: TRUE.
2610 * Failure: FALSE.
2612 static BOOL crypt_export_key(CRYPTKEY *pCryptKey, HCRYPTKEY hPubKey,
2613 DWORD dwBlobType, DWORD dwFlags, BOOL force,
2614 BYTE *pbData, DWORD *pdwDataLen)
2616 CRYPTKEY *pPubKey;
2618 if (dwFlags & CRYPT_SSL2_FALLBACK) {
2619 if (pCryptKey->aiAlgid != CALG_SSL2_MASTER) {
2620 SetLastError(NTE_BAD_KEY);
2621 return FALSE;
2625 switch ((BYTE)dwBlobType)
2627 case SIMPLEBLOB:
2628 if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pPubKey)){
2629 SetLastError(NTE_BAD_PUBLIC_KEY); /* FIXME: error_code? */
2630 return FALSE;
2632 return crypt_export_simple(pCryptKey, pPubKey, dwFlags, pbData,
2633 pdwDataLen);
2635 case PUBLICKEYBLOB:
2636 if (is_valid_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY)) {
2637 SetLastError(NTE_BAD_KEY); /* FIXME: error code? */
2638 return FALSE;
2641 return crypt_export_public_key(pCryptKey, pbData, pdwDataLen);
2643 case PRIVATEKEYBLOB:
2644 return crypt_export_private_key(pCryptKey, force, pbData, pdwDataLen);
2646 case PLAINTEXTKEYBLOB:
2647 return crypt_export_plaintext_key(pCryptKey, pbData, pdwDataLen);
2649 default:
2650 SetLastError(NTE_BAD_TYPE); /* FIXME: error code? */
2651 return FALSE;
2655 /******************************************************************************
2656 * CPExportKey (RSAENH.@)
2658 * Export a key into a binary large object (BLOB).
2660 * PARAMS
2661 * hProv [I] Key container from which a key is to be exported.
2662 * hKey [I] Key to be exported.
2663 * hPubKey [I] Key used to encrypt sensitive BLOB data.
2664 * dwBlobType [I] SIMPLEBLOB, PUBLICKEYBLOB or PRIVATEKEYBLOB.
2665 * dwFlags [I] Currently none defined.
2666 * pbData [O] Pointer to a buffer where the BLOB will be written to.
2667 * pdwDataLen [I/O] I: Size of buffer at pbData, O: Size of BLOB
2669 * RETURNS
2670 * Success: TRUE.
2671 * Failure: FALSE.
2673 BOOL WINAPI RSAENH_CPExportKey(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTKEY hPubKey,
2674 DWORD dwBlobType, DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2676 CRYPTKEY *pCryptKey;
2678 TRACE("(hProv=%08lx, hKey=%08lx, hPubKey=%08lx, dwBlobType=%08x, dwFlags=%08x, pbData=%p,"
2679 "pdwDataLen=%p)\n", hProv, hKey, hPubKey, dwBlobType, dwFlags, pbData, pdwDataLen);
2681 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2683 SetLastError(NTE_BAD_UID);
2684 return FALSE;
2687 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2689 SetLastError(NTE_BAD_KEY);
2690 return FALSE;
2693 return crypt_export_key(pCryptKey, hPubKey, dwBlobType, dwFlags, FALSE,
2694 pbData, pdwDataLen);
2697 /******************************************************************************
2698 * release_and_install_key [Internal]
2700 * Release an existing key, if present, and replaces it with a new one.
2702 * PARAMS
2703 * hProv [I] Key container into which the key is to be imported.
2704 * src [I] Key which will replace *dest
2705 * dest [I] Points to key to be released and replaced with src
2706 * fStoreKey [I] If TRUE, the newly installed key is stored to the registry.
2708 static void release_and_install_key(HCRYPTPROV hProv, HCRYPTKEY src,
2709 HCRYPTKEY *dest, DWORD fStoreKey)
2711 RSAENH_CPDestroyKey(hProv, *dest);
2712 copy_handle(&handle_table, src, RSAENH_MAGIC_KEY, dest);
2713 if (fStoreKey)
2715 KEYCONTAINER *pKeyContainer;
2717 if ((pKeyContainer = get_key_container(hProv)))
2719 store_key_container_keys(pKeyContainer);
2720 store_key_container_permissions(pKeyContainer);
2725 /******************************************************************************
2726 * import_private_key [Internal]
2728 * Import a BLOB'ed private key into a key container.
2730 * PARAMS
2731 * hProv [I] Key container into which the private key is to be imported.
2732 * pbData [I] Pointer to a buffer which holds the private key BLOB.
2733 * dwDataLen [I] Length of data in buffer at pbData.
2734 * dwFlags [I] One of:
2735 * CRYPT_EXPORTABLE: the imported key is marked exportable
2736 * fStoreKey [I] If TRUE, the imported key is stored to the registry.
2737 * phKey [O] Handle to the imported key.
2740 * NOTES
2741 * Assumes the caller has already checked the BLOBHEADER at pbData to ensure
2742 * it's a PRIVATEKEYBLOB.
2744 * RETURNS
2745 * Success: TRUE.
2746 * Failure: FALSE.
2748 static BOOL import_private_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
2749 DWORD dwFlags, BOOL fStoreKey, HCRYPTKEY *phKey)
2751 KEYCONTAINER *pKeyContainer;
2752 CRYPTKEY *pCryptKey;
2753 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
2754 const RSAPUBKEY *pRSAPubKey = (const RSAPUBKEY*)(pBlobHeader+1);
2755 BOOL ret;
2757 if (dwFlags & CRYPT_IPSEC_HMAC_KEY)
2759 FIXME("unimplemented for CRYPT_IPSEC_HMAC_KEY\n");
2760 SetLastError(NTE_BAD_FLAGS);
2761 return FALSE;
2763 if (!(pKeyContainer = get_key_container(hProv)))
2764 return FALSE;
2766 if ((dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY)))
2768 ERR("datalen %d not long enough for a BLOBHEADER + RSAPUBKEY\n",
2769 dwDataLen);
2770 SetLastError(NTE_BAD_DATA);
2771 return FALSE;
2773 if (pRSAPubKey->magic != RSAENH_MAGIC_RSA2)
2775 ERR("unexpected magic %08x\n", pRSAPubKey->magic);
2776 SetLastError(NTE_BAD_DATA);
2777 return FALSE;
2779 if ((dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) +
2780 (pRSAPubKey->bitlen >> 3) + (5 * ((pRSAPubKey->bitlen+8)>>4))))
2782 DWORD expectedLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) +
2783 (pRSAPubKey->bitlen >> 3) + (5 * ((pRSAPubKey->bitlen+8)>>4));
2785 ERR("blob too short for pub key: expect %d, got %d\n",
2786 expectedLen, dwDataLen);
2787 SetLastError(NTE_BAD_DATA);
2788 return FALSE;
2791 *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, MAKELONG(0,pRSAPubKey->bitlen), &pCryptKey);
2792 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
2793 setup_key(pCryptKey);
2794 ret = import_private_key_impl((const BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2795 pRSAPubKey->bitlen/8, dwDataLen, pRSAPubKey->pubexp);
2796 if (ret) {
2797 if (dwFlags & CRYPT_EXPORTABLE)
2798 pCryptKey->dwPermissions |= CRYPT_EXPORT;
2799 switch (pBlobHeader->aiKeyAlg)
2801 case AT_SIGNATURE:
2802 case CALG_RSA_SIGN:
2803 TRACE("installing signing key\n");
2804 release_and_install_key(hProv, *phKey, &pKeyContainer->hSignatureKeyPair,
2805 fStoreKey);
2806 break;
2807 case AT_KEYEXCHANGE:
2808 case CALG_RSA_KEYX:
2809 TRACE("installing key exchange key\n");
2810 release_and_install_key(hProv, *phKey, &pKeyContainer->hKeyExchangeKeyPair,
2811 fStoreKey);
2812 break;
2815 return ret;
2818 /******************************************************************************
2819 * import_public_key [Internal]
2821 * Import a BLOB'ed public key.
2823 * PARAMS
2824 * hProv [I] A CSP.
2825 * pbData [I] Pointer to a buffer which holds the public key BLOB.
2826 * dwDataLen [I] Length of data in buffer at pbData.
2827 * dwFlags [I] One of:
2828 * CRYPT_EXPORTABLE: the imported key is marked exportable
2829 * phKey [O] Handle to the imported key.
2832 * NOTES
2833 * Assumes the caller has already checked the BLOBHEADER at pbData to ensure
2834 * it's a PUBLICKEYBLOB.
2836 * RETURNS
2837 * Success: TRUE.
2838 * Failure: FALSE.
2840 static BOOL import_public_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
2841 DWORD dwFlags, HCRYPTKEY *phKey)
2843 CRYPTKEY *pCryptKey;
2844 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
2845 const RSAPUBKEY *pRSAPubKey = (const RSAPUBKEY*)(pBlobHeader+1);
2846 ALG_ID algID;
2847 BOOL ret;
2849 if (dwFlags & CRYPT_IPSEC_HMAC_KEY)
2851 FIXME("unimplemented for CRYPT_IPSEC_HMAC_KEY\n");
2852 SetLastError(NTE_BAD_FLAGS);
2853 return FALSE;
2856 if ((dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY)) ||
2857 (pRSAPubKey->magic != RSAENH_MAGIC_RSA1) ||
2858 (dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) + (pRSAPubKey->bitlen >> 3)))
2860 SetLastError(NTE_BAD_DATA);
2861 return FALSE;
2864 /* Since this is a public key blob, only the public key is
2865 * available, so only signature verification is possible.
2867 algID = pBlobHeader->aiKeyAlg;
2868 *phKey = new_key(hProv, algID, MAKELONG(0,pRSAPubKey->bitlen), &pCryptKey);
2869 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
2870 setup_key(pCryptKey);
2871 ret = import_public_key_impl((const BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2872 pRSAPubKey->bitlen >> 3, pRSAPubKey->pubexp);
2873 if (ret) {
2874 if (dwFlags & CRYPT_EXPORTABLE)
2875 pCryptKey->dwPermissions |= CRYPT_EXPORT;
2877 return ret;
2880 /******************************************************************************
2881 * import_symmetric_key [Internal]
2883 * Import a BLOB'ed symmetric key into a key container.
2885 * PARAMS
2886 * hProv [I] Key container into which the symmetric key is to be imported.
2887 * pbData [I] Pointer to a buffer which holds the symmetric key BLOB.
2888 * dwDataLen [I] Length of data in buffer at pbData.
2889 * hPubKey [I] Key used to decrypt sensitive BLOB data.
2890 * dwFlags [I] One of:
2891 * CRYPT_EXPORTABLE: the imported key is marked exportable
2892 * phKey [O] Handle to the imported key.
2895 * NOTES
2896 * Assumes the caller has already checked the BLOBHEADER at pbData to ensure
2897 * it's a SIMPLEBLOB.
2899 * RETURNS
2900 * Success: TRUE.
2901 * Failure: FALSE.
2903 static BOOL import_symmetric_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
2904 HCRYPTKEY hPubKey, DWORD dwFlags, HCRYPTKEY *phKey)
2906 CRYPTKEY *pCryptKey, *pPubKey;
2907 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
2908 const ALG_ID *pAlgid = (const ALG_ID*)(pBlobHeader+1);
2909 const BYTE *pbKeyStream = (const BYTE*)(pAlgid + 1);
2910 BYTE *pbDecrypted;
2911 DWORD dwKeyLen;
2913 if (dwFlags & CRYPT_IPSEC_HMAC_KEY)
2915 FIXME("unimplemented for CRYPT_IPSEC_HMAC_KEY\n");
2916 SetLastError(NTE_BAD_FLAGS);
2917 return FALSE;
2919 if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pPubKey) ||
2920 pPubKey->aiAlgid != CALG_RSA_KEYX)
2922 SetLastError(NTE_BAD_PUBLIC_KEY); /* FIXME: error code? */
2923 return FALSE;
2926 if (dwDataLen < sizeof(BLOBHEADER)+sizeof(ALG_ID)+pPubKey->dwBlockLen)
2928 SetLastError(NTE_BAD_DATA); /* FIXME: error code */
2929 return FALSE;
2932 pbDecrypted = HeapAlloc(GetProcessHeap(), 0, pPubKey->dwBlockLen);
2933 if (!pbDecrypted) return FALSE;
2934 encrypt_block_impl(pPubKey->aiAlgid, PK_PRIVATE, &pPubKey->context, pbKeyStream, pbDecrypted,
2935 RSAENH_DECRYPT);
2937 dwKeyLen = RSAENH_MAX_KEY_SIZE;
2938 if (!unpad_data(pbDecrypted, pPubKey->dwBlockLen, pbDecrypted, &dwKeyLen, dwFlags)) {
2939 HeapFree(GetProcessHeap(), 0, pbDecrypted);
2940 return FALSE;
2943 *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, dwKeyLen<<19, &pCryptKey);
2944 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
2946 HeapFree(GetProcessHeap(), 0, pbDecrypted);
2947 return FALSE;
2949 memcpy(pCryptKey->abKeyValue, pbDecrypted, dwKeyLen);
2950 HeapFree(GetProcessHeap(), 0, pbDecrypted);
2951 setup_key(pCryptKey);
2952 if (dwFlags & CRYPT_EXPORTABLE)
2953 pCryptKey->dwPermissions |= CRYPT_EXPORT;
2954 return TRUE;
2957 /******************************************************************************
2958 * import_plaintext_key [Internal]
2960 * Import a plaintext key into a key container.
2962 * PARAMS
2963 * hProv [I] Key container into which the symmetric key is to be imported.
2964 * pbData [I] Pointer to a buffer which holds the plaintext key BLOB.
2965 * dwDataLen [I] Length of data in buffer at pbData.
2966 * dwFlags [I] One of:
2967 * CRYPT_EXPORTABLE: the imported key is marked exportable
2968 * phKey [O] Handle to the imported key.
2971 * NOTES
2972 * Assumes the caller has already checked the BLOBHEADER at pbData to ensure
2973 * it's a PLAINTEXTKEYBLOB.
2975 * RETURNS
2976 * Success: TRUE.
2977 * Failure: FALSE.
2979 static BOOL import_plaintext_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
2980 DWORD dwFlags, HCRYPTKEY *phKey)
2982 CRYPTKEY *pCryptKey;
2983 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
2984 const DWORD *pKeyLen = (const DWORD *)(pBlobHeader + 1);
2985 const BYTE *pbKeyStream = (const BYTE*)(pKeyLen + 1);
2987 if (dwDataLen < sizeof(BLOBHEADER)+sizeof(DWORD)+*pKeyLen)
2989 SetLastError(NTE_BAD_DATA); /* FIXME: error code */
2990 return FALSE;
2993 if (dwFlags & CRYPT_IPSEC_HMAC_KEY)
2995 *phKey = new_key(hProv, CALG_HMAC, 0, &pCryptKey);
2996 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
2997 return FALSE;
2998 if (*pKeyLen <= RSAENH_MIN(sizeof(pCryptKey->abKeyValue), RSAENH_HMAC_BLOCK_LEN))
3000 memcpy(pCryptKey->abKeyValue, pbKeyStream, *pKeyLen);
3001 pCryptKey->dwKeyLen = *pKeyLen;
3003 else
3005 CRYPT_DATA_BLOB blobHmacKey = { *pKeyLen, (BYTE *)pbKeyStream };
3007 /* In order to initialize an HMAC key, the key material is hashed,
3008 * and the output of the hash function is used as the key material.
3009 * Unfortunately, the way the Crypto API is designed, we don't know
3010 * the hash algorithm yet, so we have to copy the entire key
3011 * material.
3013 if (!copy_data_blob(&pCryptKey->blobHmacKey, &blobHmacKey))
3015 release_handle(&handle_table, *phKey, RSAENH_MAGIC_KEY);
3016 *phKey = (HCRYPTKEY)INVALID_HANDLE_VALUE;
3017 return FALSE;
3020 setup_key(pCryptKey);
3021 if (dwFlags & CRYPT_EXPORTABLE)
3022 pCryptKey->dwPermissions |= CRYPT_EXPORT;
3024 else
3026 *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, *pKeyLen<<19, &pCryptKey);
3027 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
3028 return FALSE;
3029 memcpy(pCryptKey->abKeyValue, pbKeyStream, *pKeyLen);
3030 setup_key(pCryptKey);
3031 if (dwFlags & CRYPT_EXPORTABLE)
3032 pCryptKey->dwPermissions |= CRYPT_EXPORT;
3034 return TRUE;
3037 /******************************************************************************
3038 * import_key [Internal]
3040 * Import a BLOB'ed key into a key container, optionally storing the key's
3041 * value to the registry.
3043 * PARAMS
3044 * hProv [I] Key container into which the key is to be imported.
3045 * pbData [I] Pointer to a buffer which holds the BLOB.
3046 * dwDataLen [I] Length of data in buffer at pbData.
3047 * hPubKey [I] Key used to decrypt sensitive BLOB data.
3048 * dwFlags [I] One of:
3049 * CRYPT_EXPORTABLE: the imported key is marked exportable
3050 * fStoreKey [I] If TRUE, the imported key is stored to the registry.
3051 * phKey [O] Handle to the imported key.
3053 * RETURNS
3054 * Success: TRUE.
3055 * Failure: FALSE.
3057 static BOOL import_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen, HCRYPTKEY hPubKey,
3058 DWORD dwFlags, BOOL fStoreKey, HCRYPTKEY *phKey)
3060 KEYCONTAINER *pKeyContainer;
3061 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
3063 if (!(pKeyContainer = get_key_container(hProv)))
3064 return FALSE;
3066 if (dwDataLen < sizeof(BLOBHEADER) ||
3067 pBlobHeader->bVersion != CUR_BLOB_VERSION ||
3068 pBlobHeader->reserved != 0)
3070 TRACE("bVersion = %d, reserved = %d\n", pBlobHeader->bVersion,
3071 pBlobHeader->reserved);
3072 SetLastError(NTE_BAD_DATA);
3073 return FALSE;
3076 /* If this is a verify-only context, the key is not persisted regardless of
3077 * fStoreKey's original value.
3079 fStoreKey = fStoreKey && !(dwFlags & CRYPT_VERIFYCONTEXT);
3080 TRACE("blob type: %x\n", pBlobHeader->bType);
3081 switch (pBlobHeader->bType)
3083 case PRIVATEKEYBLOB:
3084 return import_private_key(hProv, pbData, dwDataLen, dwFlags,
3085 fStoreKey, phKey);
3087 case PUBLICKEYBLOB:
3088 return import_public_key(hProv, pbData, dwDataLen, dwFlags,
3089 phKey);
3091 case SIMPLEBLOB:
3092 return import_symmetric_key(hProv, pbData, dwDataLen, hPubKey,
3093 dwFlags, phKey);
3095 case PLAINTEXTKEYBLOB:
3096 return import_plaintext_key(hProv, pbData, dwDataLen, dwFlags,
3097 phKey);
3099 default:
3100 SetLastError(NTE_BAD_TYPE); /* FIXME: error code? */
3101 return FALSE;
3105 /******************************************************************************
3106 * CPImportKey (RSAENH.@)
3108 * Import a BLOB'ed key into a key container.
3110 * PARAMS
3111 * hProv [I] Key container into which the key is to be imported.
3112 * pbData [I] Pointer to a buffer which holds the BLOB.
3113 * dwDataLen [I] Length of data in buffer at pbData.
3114 * hPubKey [I] Key used to decrypt sensitive BLOB data.
3115 * dwFlags [I] One of:
3116 * CRYPT_EXPORTABLE: the imported key is marked exportable
3117 * phKey [O] Handle to the imported key.
3119 * RETURNS
3120 * Success: TRUE.
3121 * Failure: FALSE.
3123 BOOL WINAPI RSAENH_CPImportKey(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
3124 HCRYPTKEY hPubKey, DWORD dwFlags, HCRYPTKEY *phKey)
3126 TRACE("(hProv=%08lx, pbData=%p, dwDataLen=%d, hPubKey=%08lx, dwFlags=%08x, phKey=%p)\n",
3127 hProv, pbData, dwDataLen, hPubKey, dwFlags, phKey);
3129 return import_key(hProv, pbData, dwDataLen, hPubKey, dwFlags, TRUE, phKey);
3132 /******************************************************************************
3133 * CPGenKey (RSAENH.@)
3135 * Generate a key in the key container
3137 * PARAMS
3138 * hProv [I] Key container for which a key is to be generated.
3139 * Algid [I] Crypto algorithm identifier for the key to be generated.
3140 * dwFlags [I] Upper 16 bits: Binary length of key. Lower 16 bits: Flags. See Notes
3141 * phKey [O] Handle to the generated key.
3143 * RETURNS
3144 * Success: TRUE.
3145 * Failure: FALSE.
3147 * FIXME
3148 * Flags currently not considered.
3150 * NOTES
3151 * Private key-exchange- and signature-keys can be generated with Algid AT_KEYEXCHANGE
3152 * and AT_SIGNATURE values.
3154 BOOL WINAPI RSAENH_CPGenKey(HCRYPTPROV hProv, ALG_ID Algid, DWORD dwFlags, HCRYPTKEY *phKey)
3156 KEYCONTAINER *pKeyContainer;
3157 CRYPTKEY *pCryptKey;
3159 TRACE("(hProv=%08lx, aiAlgid=%d, dwFlags=%08x, phKey=%p)\n", hProv, Algid, dwFlags, phKey);
3161 if (!(pKeyContainer = get_key_container(hProv)))
3163 /* MSDN: hProv not containing valid context handle */
3164 return FALSE;
3167 switch (Algid)
3169 case AT_SIGNATURE:
3170 case CALG_RSA_SIGN:
3171 *phKey = new_key(hProv, CALG_RSA_SIGN, dwFlags, &pCryptKey);
3172 if (pCryptKey) {
3173 new_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen);
3174 setup_key(pCryptKey);
3175 release_and_install_key(hProv, *phKey,
3176 &pKeyContainer->hSignatureKeyPair,
3177 FALSE);
3179 break;
3181 case AT_KEYEXCHANGE:
3182 case CALG_RSA_KEYX:
3183 *phKey = new_key(hProv, CALG_RSA_KEYX, dwFlags, &pCryptKey);
3184 if (pCryptKey) {
3185 new_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen);
3186 setup_key(pCryptKey);
3187 release_and_install_key(hProv, *phKey,
3188 &pKeyContainer->hKeyExchangeKeyPair,
3189 FALSE);
3191 break;
3193 case CALG_RC2:
3194 case CALG_RC4:
3195 case CALG_DES:
3196 case CALG_3DES_112:
3197 case CALG_3DES:
3198 case CALG_AES:
3199 case CALG_AES_128:
3200 case CALG_AES_192:
3201 case CALG_AES_256:
3202 case CALG_PCT1_MASTER:
3203 case CALG_SSL2_MASTER:
3204 case CALG_SSL3_MASTER:
3205 case CALG_TLS1_MASTER:
3206 *phKey = new_key(hProv, Algid, dwFlags, &pCryptKey);
3207 if (pCryptKey) {
3208 gen_rand_impl(pCryptKey->abKeyValue, RSAENH_MAX_KEY_SIZE);
3209 switch (Algid) {
3210 case CALG_SSL3_MASTER:
3211 pCryptKey->abKeyValue[0] = RSAENH_SSL3_VERSION_MAJOR;
3212 pCryptKey->abKeyValue[1] = RSAENH_SSL3_VERSION_MINOR;
3213 break;
3215 case CALG_TLS1_MASTER:
3216 pCryptKey->abKeyValue[0] = RSAENH_TLS1_VERSION_MAJOR;
3217 pCryptKey->abKeyValue[1] = RSAENH_TLS1_VERSION_MINOR;
3218 break;
3220 setup_key(pCryptKey);
3222 break;
3224 default:
3225 /* MSDN: Algorithm not supported specified by Algid */
3226 SetLastError(NTE_BAD_ALGID);
3227 return FALSE;
3230 return *phKey != (HCRYPTKEY)INVALID_HANDLE_VALUE;
3233 /******************************************************************************
3234 * CPGenRandom (RSAENH.@)
3236 * Generate a random byte stream.
3238 * PARAMS
3239 * hProv [I] Key container that is used to generate random bytes.
3240 * dwLen [I] Specifies the number of requested random data bytes.
3241 * pbBuffer [O] Random bytes will be stored here.
3243 * RETURNS
3244 * Success: TRUE
3245 * Failure: FALSE
3247 BOOL WINAPI RSAENH_CPGenRandom(HCRYPTPROV hProv, DWORD dwLen, BYTE *pbBuffer)
3249 TRACE("(hProv=%08lx, dwLen=%d, pbBuffer=%p)\n", hProv, dwLen, pbBuffer);
3251 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3253 /* MSDN: hProv not containing valid context handle */
3254 SetLastError(NTE_BAD_UID);
3255 return FALSE;
3258 return gen_rand_impl(pbBuffer, dwLen);
3261 /******************************************************************************
3262 * CPGetHashParam (RSAENH.@)
3264 * Query parameters of an hash object.
3266 * PARAMS
3267 * hProv [I] The kea container, which the hash belongs to.
3268 * hHash [I] The hash object that is to be queried.
3269 * dwParam [I] Specifies the parameter that is to be queried.
3270 * pbData [I] Pointer to the buffer where the parameter value will be stored.
3271 * pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
3272 * dwFlags [I] None currently defined.
3274 * RETURNS
3275 * Success: TRUE
3276 * Failure: FALSE
3278 * NOTES
3279 * Valid dwParams are: HP_ALGID, HP_HASHSIZE, HP_HASHVALUE. The hash will be
3280 * finalized if HP_HASHVALUE is queried.
3282 BOOL WINAPI RSAENH_CPGetHashParam(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwParam, BYTE *pbData,
3283 DWORD *pdwDataLen, DWORD dwFlags)
3285 CRYPTHASH *pCryptHash;
3287 TRACE("(hProv=%08lx, hHash=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p, dwFlags=%08x)\n",
3288 hProv, hHash, dwParam, pbData, pdwDataLen, dwFlags);
3290 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3292 SetLastError(NTE_BAD_UID);
3293 return FALSE;
3296 if (dwFlags)
3298 SetLastError(NTE_BAD_FLAGS);
3299 return FALSE;
3302 if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH,
3303 (OBJECTHDR**)&pCryptHash))
3305 SetLastError(NTE_BAD_HASH);
3306 return FALSE;
3309 if (!pdwDataLen)
3311 SetLastError(ERROR_INVALID_PARAMETER);
3312 return FALSE;
3315 switch (dwParam)
3317 case HP_ALGID:
3318 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptHash->aiAlgid,
3319 sizeof(ALG_ID));
3321 case HP_HASHSIZE:
3322 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptHash->dwHashSize,
3323 sizeof(DWORD));
3325 case HP_HASHVAL:
3326 if (pCryptHash->aiAlgid == CALG_TLS1PRF) {
3327 return tls1_prf(hProv, pCryptHash->hKey, &pCryptHash->tpPRFParams.blobLabel,
3328 &pCryptHash->tpPRFParams.blobSeed, pbData, *pdwDataLen);
3331 if ( pbData == NULL ) {
3332 *pdwDataLen = pCryptHash->dwHashSize;
3333 return TRUE;
3336 if (pbData && (pCryptHash->dwState != RSAENH_HASHSTATE_FINISHED))
3338 finalize_hash(pCryptHash);
3339 pCryptHash->dwState = RSAENH_HASHSTATE_FINISHED;
3342 return copy_param(pbData, pdwDataLen, pCryptHash->abHashValue,
3343 pCryptHash->dwHashSize);
3345 default:
3346 SetLastError(NTE_BAD_TYPE);
3347 return FALSE;
3351 /******************************************************************************
3352 * CPSetKeyParam (RSAENH.@)
3354 * Set a parameter of a key object
3356 * PARAMS
3357 * hProv [I] The key container to which the key belongs.
3358 * hKey [I] The key for which a parameter is to be set.
3359 * dwParam [I] Parameter type. See Notes.
3360 * pbData [I] Pointer to the parameter value.
3361 * dwFlags [I] Currently none defined.
3363 * RETURNS
3364 * Success: TRUE.
3365 * Failure: FALSE.
3367 * NOTES:
3368 * Defined dwParam types are:
3369 * - KP_MODE: Values MODE_CBC, MODE_ECB, MODE_CFB.
3370 * - KP_MODE_BITS: Shift width for cipher feedback mode. (Currently ignored by MS CSP's)
3371 * - KP_PERMISSIONS: Or'ed combination of CRYPT_ENCRYPT, CRYPT_DECRYPT,
3372 * CRYPT_EXPORT, CRYPT_READ, CRYPT_WRITE, CRYPT_MAC
3373 * - KP_IV: Initialization vector
3375 BOOL WINAPI RSAENH_CPSetKeyParam(HCRYPTPROV hProv, HCRYPTKEY hKey, DWORD dwParam, BYTE *pbData,
3376 DWORD dwFlags)
3378 CRYPTKEY *pCryptKey;
3380 TRACE("(hProv=%08lx, hKey=%08lx, dwParam=%08x, pbData=%p, dwFlags=%08x)\n", hProv, hKey,
3381 dwParam, pbData, dwFlags);
3383 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3385 SetLastError(NTE_BAD_UID);
3386 return FALSE;
3389 if (dwFlags) {
3390 SetLastError(NTE_BAD_FLAGS);
3391 return FALSE;
3394 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
3396 SetLastError(NTE_BAD_KEY);
3397 return FALSE;
3400 switch (dwParam) {
3401 case KP_PADDING:
3402 /* The MS providers only support PKCS5_PADDING */
3403 if (*(DWORD *)pbData != PKCS5_PADDING) {
3404 SetLastError(NTE_BAD_DATA);
3405 return FALSE;
3407 return TRUE;
3409 case KP_MODE:
3410 pCryptKey->dwMode = *(DWORD*)pbData;
3411 return TRUE;
3413 case KP_MODE_BITS:
3414 pCryptKey->dwModeBits = *(DWORD*)pbData;
3415 return TRUE;
3417 case KP_PERMISSIONS:
3419 DWORD perms = *(DWORD *)pbData;
3421 if ((perms & CRYPT_EXPORT) &&
3422 !(pCryptKey->dwPermissions & CRYPT_EXPORT))
3424 SetLastError(NTE_BAD_DATA);
3425 return FALSE;
3427 else if (!(perms & CRYPT_EXPORT) &&
3428 (pCryptKey->dwPermissions & CRYPT_EXPORT))
3430 /* Clearing the export permission appears to be ignored,
3431 * see tests.
3433 perms |= CRYPT_EXPORT;
3435 pCryptKey->dwPermissions = perms;
3436 return TRUE;
3439 case KP_IV:
3440 memcpy(pCryptKey->abInitVector, pbData, pCryptKey->dwBlockLen);
3441 setup_key(pCryptKey);
3442 return TRUE;
3444 case KP_SALT:
3445 switch (pCryptKey->aiAlgid) {
3446 case CALG_RC2:
3447 case CALG_RC4:
3449 KEYCONTAINER *pKeyContainer = get_key_container(pCryptKey->hProv);
3450 if (!pbData)
3452 SetLastError(ERROR_INVALID_PARAMETER);
3453 return FALSE;
3455 /* MSDN: the base provider always sets eleven bytes of
3456 * salt value.
3458 memcpy(pCryptKey->abKeyValue + pCryptKey->dwKeyLen,
3459 pbData, 11);
3460 pCryptKey->dwSaltLen = 11;
3461 setup_key(pCryptKey);
3462 /* After setting the salt value if the provider is not base or
3463 * strong the salt length will be reset. */
3464 if (pKeyContainer->dwPersonality != RSAENH_PERSONALITY_BASE &&
3465 pKeyContainer->dwPersonality != RSAENH_PERSONALITY_STRONG)
3466 pCryptKey->dwSaltLen = 0;
3467 break;
3469 default:
3470 SetLastError(NTE_BAD_KEY);
3471 return FALSE;
3473 return TRUE;
3475 case KP_SALT_EX:
3477 CRYPT_INTEGER_BLOB *blob = (CRYPT_INTEGER_BLOB *)pbData;
3479 /* salt length can't be greater than 184 bits = 24 bytes */
3480 if (blob->cbData > 24)
3482 SetLastError(NTE_BAD_DATA);
3483 return FALSE;
3485 memcpy(pCryptKey->abKeyValue + pCryptKey->dwKeyLen, blob->pbData,
3486 blob->cbData);
3487 pCryptKey->dwSaltLen = blob->cbData;
3488 setup_key(pCryptKey);
3489 return TRUE;
3492 case KP_EFFECTIVE_KEYLEN:
3493 switch (pCryptKey->aiAlgid) {
3494 case CALG_RC2:
3496 DWORD keylen, deflen;
3497 BOOL ret = TRUE;
3498 KEYCONTAINER *pKeyContainer = get_key_container(pCryptKey->hProv);
3500 if (!pbData)
3502 SetLastError(ERROR_INVALID_PARAMETER);
3503 return FALSE;
3505 keylen = *(DWORD *)pbData;
3506 if (!keylen || keylen > 1024)
3508 SetLastError(NTE_BAD_DATA);
3509 return FALSE;
3513 * The Base provider will force the key length to default
3514 * and set an error state if a key length different from
3515 * the default is tried.
3517 deflen = aProvEnumAlgsEx[pKeyContainer->dwPersonality]->dwDefaultLen;
3518 if (pKeyContainer->dwPersonality == RSAENH_PERSONALITY_BASE
3519 && keylen != deflen)
3521 keylen = deflen;
3522 SetLastError(NTE_BAD_DATA);
3523 ret = FALSE;
3525 pCryptKey->dwEffectiveKeyLen = keylen;
3526 setup_key(pCryptKey);
3527 return ret;
3529 default:
3530 SetLastError(NTE_BAD_TYPE);
3531 return FALSE;
3533 return TRUE;
3535 case KP_SCHANNEL_ALG:
3536 switch (((PSCHANNEL_ALG)pbData)->dwUse) {
3537 case SCHANNEL_ENC_KEY:
3538 memcpy(&pCryptKey->siSChannelInfo.saEncAlg, pbData, sizeof(SCHANNEL_ALG));
3539 break;
3541 case SCHANNEL_MAC_KEY:
3542 memcpy(&pCryptKey->siSChannelInfo.saMACAlg, pbData, sizeof(SCHANNEL_ALG));
3543 break;
3545 default:
3546 SetLastError(NTE_FAIL); /* FIXME: error code */
3547 return FALSE;
3549 return TRUE;
3551 case KP_CLIENT_RANDOM:
3552 return copy_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom, (PCRYPT_DATA_BLOB)pbData);
3554 case KP_SERVER_RANDOM:
3555 return copy_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom, (PCRYPT_DATA_BLOB)pbData);
3557 default:
3558 SetLastError(NTE_BAD_TYPE);
3559 return FALSE;
3563 /******************************************************************************
3564 * CPGetKeyParam (RSAENH.@)
3566 * Query a key parameter.
3568 * PARAMS
3569 * hProv [I] The key container, which the key belongs to.
3570 * hHash [I] The key object that is to be queried.
3571 * dwParam [I] Specifies the parameter that is to be queried.
3572 * pbData [I] Pointer to the buffer where the parameter value will be stored.
3573 * pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
3574 * dwFlags [I] None currently defined.
3576 * RETURNS
3577 * Success: TRUE
3578 * Failure: FALSE
3580 * NOTES
3581 * Defined dwParam types are:
3582 * - KP_MODE: Values MODE_CBC, MODE_ECB, MODE_CFB.
3583 * - KP_MODE_BITS: Shift width for cipher feedback mode.
3584 * (Currently ignored by MS CSP's - always eight)
3585 * - KP_PERMISSIONS: Or'ed combination of CRYPT_ENCRYPT, CRYPT_DECRYPT,
3586 * CRYPT_EXPORT, CRYPT_READ, CRYPT_WRITE, CRYPT_MAC
3587 * - KP_IV: Initialization vector.
3588 * - KP_KEYLEN: Bitwidth of the key.
3589 * - KP_BLOCKLEN: Size of a block cipher block.
3590 * - KP_SALT: Salt value.
3592 BOOL WINAPI RSAENH_CPGetKeyParam(HCRYPTPROV hProv, HCRYPTKEY hKey, DWORD dwParam, BYTE *pbData,
3593 DWORD *pdwDataLen, DWORD dwFlags)
3595 CRYPTKEY *pCryptKey;
3596 DWORD dwValue;
3598 TRACE("(hProv=%08lx, hKey=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p dwFlags=%08x)\n",
3599 hProv, hKey, dwParam, pbData, pdwDataLen, dwFlags);
3601 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3603 SetLastError(NTE_BAD_UID);
3604 return FALSE;
3607 if (dwFlags) {
3608 SetLastError(NTE_BAD_FLAGS);
3609 return FALSE;
3612 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
3614 SetLastError(NTE_BAD_KEY);
3615 return FALSE;
3618 switch (dwParam)
3620 case KP_IV:
3621 return copy_param(pbData, pdwDataLen, pCryptKey->abInitVector,
3622 pCryptKey->dwBlockLen);
3624 case KP_SALT:
3625 switch (pCryptKey->aiAlgid) {
3626 case CALG_RC2:
3627 case CALG_RC4:
3628 return copy_param(pbData, pdwDataLen,
3629 &pCryptKey->abKeyValue[pCryptKey->dwKeyLen],
3630 pCryptKey->dwSaltLen);
3631 default:
3632 SetLastError(NTE_BAD_KEY);
3633 return FALSE;
3636 case KP_PADDING:
3637 dwValue = PKCS5_PADDING;
3638 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwValue, sizeof(DWORD));
3640 case KP_KEYLEN:
3641 dwValue = pCryptKey->dwKeyLen << 3;
3642 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwValue, sizeof(DWORD));
3644 case KP_EFFECTIVE_KEYLEN:
3645 if (pCryptKey->dwEffectiveKeyLen)
3646 dwValue = pCryptKey->dwEffectiveKeyLen;
3647 else
3648 dwValue = pCryptKey->dwKeyLen << 3;
3649 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwValue, sizeof(DWORD));
3651 case KP_BLOCKLEN:
3652 dwValue = pCryptKey->dwBlockLen << 3;
3653 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwValue, sizeof(DWORD));
3655 case KP_MODE:
3656 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptKey->dwMode, sizeof(DWORD));
3658 case KP_MODE_BITS:
3659 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptKey->dwModeBits,
3660 sizeof(DWORD));
3662 case KP_PERMISSIONS:
3663 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptKey->dwPermissions,
3664 sizeof(DWORD));
3666 case KP_ALGID:
3667 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptKey->aiAlgid, sizeof(DWORD));
3669 default:
3670 SetLastError(NTE_BAD_TYPE);
3671 return FALSE;
3675 /******************************************************************************
3676 * CPGetProvParam (RSAENH.@)
3678 * Query a CSP parameter.
3680 * PARAMS
3681 * hProv [I] The key container that is to be queried.
3682 * dwParam [I] Specifies the parameter that is to be queried.
3683 * pbData [I] Pointer to the buffer where the parameter value will be stored.
3684 * pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
3685 * dwFlags [I] CRYPT_FIRST: Start enumeration (for PP_ENUMALGS{_EX}).
3687 * RETURNS
3688 * Success: TRUE
3689 * Failure: FALSE
3690 * NOTES:
3691 * Defined dwParam types:
3692 * - PP_CONTAINER: Name of the key container.
3693 * - PP_NAME: Name of the cryptographic service provider.
3694 * - PP_SIG_KEYSIZE_INC: RSA signature keywidth granularity in bits.
3695 * - PP_KEYX_KEYSIZE_INC: RSA key-exchange keywidth granularity in bits.
3696 * - PP_ENUMALGS{_EX}: Query provider capabilities.
3697 * - PP_KEYSET_SEC_DESCR: Retrieve security descriptor on container.
3699 BOOL WINAPI RSAENH_CPGetProvParam(HCRYPTPROV hProv, DWORD dwParam, BYTE *pbData,
3700 DWORD *pdwDataLen, DWORD dwFlags)
3702 KEYCONTAINER *pKeyContainer;
3703 PROV_ENUMALGS provEnumalgs;
3704 DWORD dwTemp;
3705 HKEY hKey;
3707 /* This is for dwParam PP_CRYPT_COUNT_KEY_USE.
3708 * IE6 SP1 asks for it in the 'About' dialog.
3709 * Returning this BLOB seems to satisfy IE. The marked 0x00 seem
3710 * to be 'don't care's. If you know anything more specific about
3711 * this provider parameter, please report to wine-devel@winehq.org */
3712 static const BYTE abWTF[96] = {
3713 0xb0, 0x25, 0x63, 0x86, 0x9c, 0xab, 0xb6, 0x37,
3714 0xe8, 0x82, /**/0x00,/**/ 0x72, 0x06, 0xb2, /**/0x00,/**/ 0x3b,
3715 0x60, 0x35, /**/0x00,/**/ 0x3b, 0x88, 0xce, /**/0x00,/**/ 0x82,
3716 0xbc, 0x7a, /**/0x00,/**/ 0xb7, 0x4f, 0x7e, /**/0x00,/**/ 0xde,
3717 0x92, 0xf1, /**/0x00,/**/ 0x83, 0xea, 0x5e, /**/0x00,/**/ 0xc8,
3718 0x12, 0x1e, 0xd4, 0x06, 0xf7, 0x66, /**/0x00,/**/ 0x01,
3719 0x29, 0xa4, /**/0x00,/**/ 0xf8, 0x24, 0x0c, /**/0x00,/**/ 0x33,
3720 0x06, 0x80, /**/0x00,/**/ 0x02, 0x46, 0x0b, /**/0x00,/**/ 0x6d,
3721 0x5b, 0xca, /**/0x00,/**/ 0x9a, 0x10, 0xf0, /**/0x00,/**/ 0x05,
3722 0x19, 0xd0, /**/0x00,/**/ 0x2c, 0xf6, 0x27, /**/0x00,/**/ 0xaa,
3723 0x7c, 0x6f, /**/0x00,/**/ 0xb9, 0xd8, 0x72, /**/0x00,/**/ 0x03,
3724 0xf3, 0x81, /**/0x00,/**/ 0xfa, 0xe8, 0x26, /**/0x00,/**/ 0xca
3727 TRACE("(hProv=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p, dwFlags=%08x)\n",
3728 hProv, dwParam, pbData, pdwDataLen, dwFlags);
3730 if (!pdwDataLen) {
3731 SetLastError(ERROR_INVALID_PARAMETER);
3732 return FALSE;
3735 if (!(pKeyContainer = get_key_container(hProv)))
3737 /* MSDN: hProv not containing valid context handle */
3738 return FALSE;
3741 switch (dwParam)
3743 case PP_CONTAINER:
3744 case PP_UNIQUE_CONTAINER:/* MSDN says we can return the same value as PP_CONTAINER */
3745 return copy_param(pbData, pdwDataLen, (const BYTE*)pKeyContainer->szName,
3746 strlen(pKeyContainer->szName)+1);
3748 case PP_NAME:
3749 return copy_param(pbData, pdwDataLen, (const BYTE*)pKeyContainer->szProvName,
3750 strlen(pKeyContainer->szProvName)+1);
3752 case PP_PROVTYPE:
3753 dwTemp = PROV_RSA_FULL;
3754 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
3756 case PP_KEYSPEC:
3757 dwTemp = AT_SIGNATURE | AT_KEYEXCHANGE;
3758 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
3760 case PP_KEYSET_TYPE:
3761 dwTemp = pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET;
3762 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
3764 case PP_KEYSTORAGE:
3765 dwTemp = CRYPT_SEC_DESCR;
3766 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
3768 case PP_SIG_KEYSIZE_INC:
3769 case PP_KEYX_KEYSIZE_INC:
3770 dwTemp = 8;
3771 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
3773 case PP_IMPTYPE:
3774 dwTemp = CRYPT_IMPL_SOFTWARE;
3775 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
3777 case PP_VERSION:
3778 dwTemp = 0x00000200;
3779 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
3781 case PP_ENUMCONTAINERS:
3782 if ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) pKeyContainer->dwEnumContainersCtr = 0;
3784 if (!pbData) {
3785 *pdwDataLen = (DWORD)MAX_PATH + 1;
3786 return TRUE;
3789 if (!open_container_key("", dwFlags, KEY_READ, &hKey))
3791 SetLastError(ERROR_NO_MORE_ITEMS);
3792 return FALSE;
3795 dwTemp = *pdwDataLen;
3796 switch (RegEnumKeyExA(hKey, pKeyContainer->dwEnumContainersCtr, (LPSTR)pbData, &dwTemp,
3797 NULL, NULL, NULL, NULL))
3799 case ERROR_MORE_DATA:
3800 *pdwDataLen = (DWORD)MAX_PATH + 1;
3802 case ERROR_SUCCESS:
3803 pKeyContainer->dwEnumContainersCtr++;
3804 RegCloseKey(hKey);
3805 return TRUE;
3807 case ERROR_NO_MORE_ITEMS:
3808 default:
3809 SetLastError(ERROR_NO_MORE_ITEMS);
3810 RegCloseKey(hKey);
3811 return FALSE;
3814 case PP_ENUMALGS:
3815 case PP_ENUMALGS_EX:
3816 if (((pKeyContainer->dwEnumAlgsCtr >= RSAENH_MAX_ENUMALGS-1) ||
3817 (!aProvEnumAlgsEx[pKeyContainer->dwPersonality]
3818 [pKeyContainer->dwEnumAlgsCtr+1].aiAlgid)) &&
3819 ((dwFlags & CRYPT_FIRST) != CRYPT_FIRST))
3821 SetLastError(ERROR_NO_MORE_ITEMS);
3822 return FALSE;
3825 if (dwParam == PP_ENUMALGS) {
3826 if (pbData && (*pdwDataLen >= sizeof(PROV_ENUMALGS)))
3827 pKeyContainer->dwEnumAlgsCtr = ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) ?
3828 0 : pKeyContainer->dwEnumAlgsCtr+1;
3830 provEnumalgs.aiAlgid = aProvEnumAlgsEx
3831 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].aiAlgid;
3832 provEnumalgs.dwBitLen = aProvEnumAlgsEx
3833 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].dwDefaultLen;
3834 provEnumalgs.dwNameLen = aProvEnumAlgsEx
3835 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].dwNameLen;
3836 memcpy(provEnumalgs.szName, aProvEnumAlgsEx
3837 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].szName,
3838 20*sizeof(CHAR));
3840 return copy_param(pbData, pdwDataLen, (const BYTE*)&provEnumalgs,
3841 sizeof(PROV_ENUMALGS));
3842 } else {
3843 if (pbData && (*pdwDataLen >= sizeof(PROV_ENUMALGS_EX)))
3844 pKeyContainer->dwEnumAlgsCtr = ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) ?
3845 0 : pKeyContainer->dwEnumAlgsCtr+1;
3847 return copy_param(pbData, pdwDataLen,
3848 (const BYTE*)&aProvEnumAlgsEx
3849 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr],
3850 sizeof(PROV_ENUMALGS_EX));
3853 case PP_CRYPT_COUNT_KEY_USE: /* Asked for by IE About dialog */
3854 return copy_param(pbData, pdwDataLen, abWTF, sizeof(abWTF));
3856 case PP_KEYSET_SEC_DESCR:
3858 SECURITY_DESCRIPTOR *sd;
3859 DWORD err, len, flags = (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET);
3861 if (!open_container_key(pKeyContainer->szName, flags, KEY_READ, &hKey))
3863 SetLastError(NTE_BAD_KEYSET);
3864 return FALSE;
3867 err = GetSecurityInfo(hKey, SE_REGISTRY_KEY, dwFlags, NULL, NULL, NULL, NULL, (void **)&sd);
3868 RegCloseKey(hKey);
3869 if (err)
3871 SetLastError(err);
3872 return FALSE;
3875 len = GetSecurityDescriptorLength(sd);
3876 if (*pdwDataLen >= len) memcpy(pbData, sd, len);
3877 else SetLastError(ERROR_INSUFFICIENT_BUFFER);
3878 *pdwDataLen = len;
3880 LocalFree(sd);
3881 return TRUE;
3884 default:
3885 /* MSDN: Unknown parameter number in dwParam */
3886 SetLastError(NTE_BAD_TYPE);
3887 return FALSE;
3891 /******************************************************************************
3892 * CPDeriveKey (RSAENH.@)
3894 * Derives a key from a hash value.
3896 * PARAMS
3897 * hProv [I] Key container for which a key is to be generated.
3898 * Algid [I] Crypto algorithm identifier for the key to be generated.
3899 * hBaseData [I] Hash from whose value the key will be derived.
3900 * dwFlags [I] See Notes.
3901 * phKey [O] The generated key.
3903 * RETURNS
3904 * Success: TRUE
3905 * Failure: FALSE
3907 * NOTES
3908 * Defined flags:
3909 * - CRYPT_EXPORTABLE: Key can be exported.
3910 * - CRYPT_NO_SALT: No salt is used for 40 bit keys.
3911 * - CRYPT_CREATE_SALT: Use remaining bits as salt value.
3913 BOOL WINAPI RSAENH_CPDeriveKey(HCRYPTPROV hProv, ALG_ID Algid, HCRYPTHASH hBaseData,
3914 DWORD dwFlags, HCRYPTKEY *phKey)
3916 CRYPTKEY *pCryptKey, *pMasterKey;
3917 CRYPTHASH *pCryptHash;
3918 BYTE abHashValue[RSAENH_MAX_HASH_SIZE*2];
3919 DWORD dwLen;
3921 TRACE("(hProv=%08lx, Algid=%d, hBaseData=%08lx, dwFlags=%08x phKey=%p)\n", hProv, Algid,
3922 hBaseData, dwFlags, phKey);
3924 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3926 SetLastError(NTE_BAD_UID);
3927 return FALSE;
3930 if (!lookup_handle(&handle_table, hBaseData, RSAENH_MAGIC_HASH,
3931 (OBJECTHDR**)&pCryptHash))
3933 SetLastError(NTE_BAD_HASH);
3934 return FALSE;
3937 if (!phKey)
3939 SetLastError(ERROR_INVALID_PARAMETER);
3940 return FALSE;
3943 switch (GET_ALG_CLASS(Algid))
3945 case ALG_CLASS_DATA_ENCRYPT:
3947 int need_padding, copy_len;
3948 *phKey = new_key(hProv, Algid, dwFlags, &pCryptKey);
3949 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
3952 * We derive the key material from the hash.
3953 * If the hash value is not large enough for the claimed key, we have to construct
3954 * a larger binary value based on the hash. This is documented in MSDN: CryptDeriveKey.
3956 dwLen = RSAENH_MAX_HASH_SIZE;
3957 RSAENH_CPGetHashParam(pCryptHash->hProv, hBaseData, HP_HASHVAL, abHashValue, &dwLen, 0);
3960 * The usage of padding seems to vary from algorithm to algorithm.
3961 * For now the only different case found was for AES with 128 bit key.
3963 switch(Algid)
3965 case CALG_AES_128:
3966 /* To reduce the chance of regressions we will only deviate
3967 * from the old behavior for the tested hash lengths */
3968 if (dwLen == 16 || dwLen == 20)
3970 need_padding = 1;
3971 break;
3973 default:
3974 need_padding = dwLen < pCryptKey->dwKeyLen;
3977 copy_len = pCryptKey->dwKeyLen;
3978 if (need_padding)
3980 BYTE pad1[RSAENH_HMAC_DEF_PAD_LEN], pad2[RSAENH_HMAC_DEF_PAD_LEN];
3981 BYTE old_hashval[RSAENH_MAX_HASH_SIZE];
3982 DWORD i;
3984 memcpy(old_hashval, pCryptHash->abHashValue, RSAENH_MAX_HASH_SIZE);
3986 for (i=0; i<RSAENH_HMAC_DEF_PAD_LEN; i++) {
3987 pad1[i] = RSAENH_HMAC_DEF_IPAD_CHAR ^ (i<dwLen ? abHashValue[i] : 0);
3988 pad2[i] = RSAENH_HMAC_DEF_OPAD_CHAR ^ (i<dwLen ? abHashValue[i] : 0);
3991 init_hash(pCryptHash);
3992 update_hash(pCryptHash, pad1, RSAENH_HMAC_DEF_PAD_LEN);
3993 finalize_hash(pCryptHash);
3994 memcpy(abHashValue, pCryptHash->abHashValue, pCryptHash->dwHashSize);
3996 init_hash(pCryptHash);
3997 update_hash(pCryptHash, pad2, RSAENH_HMAC_DEF_PAD_LEN);
3998 finalize_hash(pCryptHash);
3999 memcpy(abHashValue+pCryptHash->dwHashSize, pCryptHash->abHashValue,
4000 pCryptHash->dwHashSize);
4002 memcpy(pCryptHash->abHashValue, old_hashval, RSAENH_MAX_HASH_SIZE);
4005 * Padding was not required, we have more hash than needed.
4006 * Do we need to use the remaining hash as salt?
4008 else if((dwFlags & CRYPT_CREATE_SALT) &&
4009 (Algid == CALG_RC2 || Algid == CALG_RC4))
4011 copy_len += pCryptKey->dwSaltLen;
4014 memcpy(pCryptKey->abKeyValue, abHashValue,
4015 RSAENH_MIN(copy_len, sizeof(pCryptKey->abKeyValue)));
4016 break;
4018 case ALG_CLASS_MSG_ENCRYPT:
4019 if (!lookup_handle(&handle_table, pCryptHash->hKey, RSAENH_MAGIC_KEY,
4020 (OBJECTHDR**)&pMasterKey))
4022 SetLastError(NTE_FAIL); /* FIXME error code */
4023 return FALSE;
4026 switch (Algid)
4028 /* See RFC 2246, chapter 6.3 Key calculation */
4029 case CALG_SCHANNEL_ENC_KEY:
4030 if (!pMasterKey->siSChannelInfo.saEncAlg.Algid ||
4031 !pMasterKey->siSChannelInfo.saEncAlg.cBits)
4033 SetLastError(NTE_BAD_FLAGS);
4034 return FALSE;
4036 *phKey = new_key(hProv, pMasterKey->siSChannelInfo.saEncAlg.Algid,
4037 MAKELONG(LOWORD(dwFlags),pMasterKey->siSChannelInfo.saEncAlg.cBits),
4038 &pCryptKey);
4039 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
4040 memcpy(pCryptKey->abKeyValue,
4041 pCryptHash->abHashValue + (
4042 2 * (pMasterKey->siSChannelInfo.saMACAlg.cBits / 8) +
4043 ((dwFlags & CRYPT_SERVER) ?
4044 (pMasterKey->siSChannelInfo.saEncAlg.cBits / 8) : 0)),
4045 pMasterKey->siSChannelInfo.saEncAlg.cBits / 8);
4046 memcpy(pCryptKey->abInitVector,
4047 pCryptHash->abHashValue + (
4048 2 * (pMasterKey->siSChannelInfo.saMACAlg.cBits / 8) +
4049 2 * (pMasterKey->siSChannelInfo.saEncAlg.cBits / 8) +
4050 ((dwFlags & CRYPT_SERVER) ? pCryptKey->dwBlockLen : 0)),
4051 pCryptKey->dwBlockLen);
4052 break;
4054 case CALG_SCHANNEL_MAC_KEY:
4055 *phKey = new_key(hProv, Algid,
4056 MAKELONG(LOWORD(dwFlags),pMasterKey->siSChannelInfo.saMACAlg.cBits),
4057 &pCryptKey);
4058 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
4059 memcpy(pCryptKey->abKeyValue,
4060 pCryptHash->abHashValue + ((dwFlags & CRYPT_SERVER) ?
4061 pMasterKey->siSChannelInfo.saMACAlg.cBits / 8 : 0),
4062 pMasterKey->siSChannelInfo.saMACAlg.cBits / 8);
4063 break;
4065 default:
4066 SetLastError(NTE_BAD_ALGID);
4067 return FALSE;
4069 break;
4071 default:
4072 SetLastError(NTE_BAD_ALGID);
4073 return FALSE;
4076 setup_key(pCryptKey);
4077 return TRUE;
4080 /******************************************************************************
4081 * CPGetUserKey (RSAENH.@)
4083 * Returns a handle to the user's private key-exchange- or signature-key.
4085 * PARAMS
4086 * hProv [I] The key container from which a user key is requested.
4087 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
4088 * phUserKey [O] Handle to the requested key or INVALID_HANDLE_VALUE in case of failure.
4090 * RETURNS
4091 * Success: TRUE.
4092 * Failure: FALSE.
4094 * NOTE
4095 * A newly created key container does not contain private user key. Create them with CPGenKey.
4097 BOOL WINAPI RSAENH_CPGetUserKey(HCRYPTPROV hProv, DWORD dwKeySpec, HCRYPTKEY *phUserKey)
4099 KEYCONTAINER *pKeyContainer;
4101 TRACE("(hProv=%08lx, dwKeySpec=%08x, phUserKey=%p)\n", hProv, dwKeySpec, phUserKey);
4103 if (!(pKeyContainer = get_key_container(hProv)))
4105 /* MSDN: hProv not containing valid context handle */
4106 return FALSE;
4109 switch (dwKeySpec)
4111 case AT_KEYEXCHANGE:
4112 copy_handle(&handle_table, pKeyContainer->hKeyExchangeKeyPair, RSAENH_MAGIC_KEY,
4113 phUserKey);
4114 break;
4116 case AT_SIGNATURE:
4117 copy_handle(&handle_table, pKeyContainer->hSignatureKeyPair, RSAENH_MAGIC_KEY,
4118 phUserKey);
4119 break;
4121 default:
4122 *phUserKey = (HCRYPTKEY)INVALID_HANDLE_VALUE;
4125 if (*phUserKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
4127 /* MSDN: dwKeySpec parameter specifies nonexistent key */
4128 SetLastError(NTE_NO_KEY);
4129 return FALSE;
4132 return TRUE;
4135 /******************************************************************************
4136 * CPHashData (RSAENH.@)
4138 * Updates a hash object with the given data.
4140 * PARAMS
4141 * hProv [I] Key container to which the hash object belongs.
4142 * hHash [I] Hash object which is to be updated.
4143 * pbData [I] Pointer to data with which the hash object is to be updated.
4144 * dwDataLen [I] Length of the data.
4145 * dwFlags [I] Currently none defined.
4147 * RETURNS
4148 * Success: TRUE.
4149 * Failure: FALSE.
4151 * NOTES
4152 * The actual hash value is queried with CPGetHashParam, which will finalize
4153 * the hash. Updating a finalized hash will fail with a last error NTE_BAD_HASH_STATE.
4155 BOOL WINAPI RSAENH_CPHashData(HCRYPTPROV hProv, HCRYPTHASH hHash, const BYTE *pbData,
4156 DWORD dwDataLen, DWORD dwFlags)
4158 CRYPTHASH *pCryptHash;
4160 TRACE("(hProv=%08lx, hHash=%08lx, pbData=%p, dwDataLen=%d, dwFlags=%08x)\n",
4161 hProv, hHash, pbData, dwDataLen, dwFlags);
4163 if (dwFlags & ~CRYPT_USERDATA)
4165 SetLastError(NTE_BAD_FLAGS);
4166 return FALSE;
4169 if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH,
4170 (OBJECTHDR**)&pCryptHash))
4172 SetLastError(NTE_BAD_HASH);
4173 return FALSE;
4176 if (!get_algid_info(hProv, pCryptHash->aiAlgid) || pCryptHash->aiAlgid == CALG_SSL3_SHAMD5)
4178 SetLastError(NTE_BAD_ALGID);
4179 return FALSE;
4182 if (pCryptHash->dwState != RSAENH_HASHSTATE_HASHING)
4184 SetLastError(NTE_BAD_HASH_STATE);
4185 return FALSE;
4188 update_hash(pCryptHash, pbData, dwDataLen);
4189 return TRUE;
4192 /******************************************************************************
4193 * CPHashSessionKey (RSAENH.@)
4195 * Updates a hash object with the binary representation of a symmetric key.
4197 * PARAMS
4198 * hProv [I] Key container to which the hash object belongs.
4199 * hHash [I] Hash object which is to be updated.
4200 * hKey [I] The symmetric key, whose binary value will be added to the hash.
4201 * dwFlags [I] CRYPT_LITTLE_ENDIAN, if the binary key value shall be interpreted as little endian.
4203 * RETURNS
4204 * Success: TRUE.
4205 * Failure: FALSE.
4207 BOOL WINAPI RSAENH_CPHashSessionKey(HCRYPTPROV hProv, HCRYPTHASH hHash, HCRYPTKEY hKey,
4208 DWORD dwFlags)
4210 BYTE abKeyValue[RSAENH_MAX_KEY_SIZE], bTemp;
4211 CRYPTKEY *pKey;
4212 DWORD i;
4214 TRACE("(hProv=%08lx, hHash=%08lx, hKey=%08lx, dwFlags=%08x)\n", hProv, hHash, hKey, dwFlags);
4216 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pKey) ||
4217 (GET_ALG_CLASS(pKey->aiAlgid) != ALG_CLASS_DATA_ENCRYPT))
4219 SetLastError(NTE_BAD_KEY);
4220 return FALSE;
4223 if (dwFlags & ~CRYPT_LITTLE_ENDIAN) {
4224 SetLastError(NTE_BAD_FLAGS);
4225 return FALSE;
4228 memcpy(abKeyValue, pKey->abKeyValue, pKey->dwKeyLen);
4229 if (!(dwFlags & CRYPT_LITTLE_ENDIAN)) {
4230 for (i=0; i<pKey->dwKeyLen/2; i++) {
4231 bTemp = abKeyValue[i];
4232 abKeyValue[i] = abKeyValue[pKey->dwKeyLen-i-1];
4233 abKeyValue[pKey->dwKeyLen-i-1] = bTemp;
4237 return RSAENH_CPHashData(hProv, hHash, abKeyValue, pKey->dwKeyLen, 0);
4240 /******************************************************************************
4241 * CPReleaseContext (RSAENH.@)
4243 * Release a key container.
4245 * PARAMS
4246 * hProv [I] Key container to be released.
4247 * dwFlags [I] Currently none defined.
4249 * RETURNS
4250 * Success: TRUE
4251 * Failure: FALSE
4253 BOOL WINAPI RSAENH_CPReleaseContext(HCRYPTPROV hProv, DWORD dwFlags)
4255 TRACE("(hProv=%08lx, dwFlags=%08x)\n", hProv, dwFlags);
4257 if (!release_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
4259 /* MSDN: hProv not containing valid context handle */
4260 SetLastError(NTE_BAD_UID);
4261 return FALSE;
4264 if (dwFlags) {
4265 SetLastError(NTE_BAD_FLAGS);
4266 return FALSE;
4269 return TRUE;
4272 /******************************************************************************
4273 * CPSetHashParam (RSAENH.@)
4275 * Set a parameter of a hash object
4277 * PARAMS
4278 * hProv [I] The key container to which the key belongs.
4279 * hHash [I] The hash object for which a parameter is to be set.
4280 * dwParam [I] Parameter type. See Notes.
4281 * pbData [I] Pointer to the parameter value.
4282 * dwFlags [I] Currently none defined.
4284 * RETURNS
4285 * Success: TRUE.
4286 * Failure: FALSE.
4288 * NOTES
4289 * Currently only the HP_HMAC_INFO dwParam type is defined.
4290 * The HMAC_INFO struct will be deep copied into the hash object.
4291 * See Internet RFC 2104 for details on the HMAC algorithm.
4293 BOOL WINAPI RSAENH_CPSetHashParam(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwParam,
4294 BYTE *pbData, DWORD dwFlags)
4296 CRYPTHASH *pCryptHash;
4297 CRYPTKEY *pCryptKey;
4298 DWORD i;
4300 TRACE("(hProv=%08lx, hHash=%08lx, dwParam=%08x, pbData=%p, dwFlags=%08x)\n",
4301 hProv, hHash, dwParam, pbData, dwFlags);
4303 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
4305 SetLastError(NTE_BAD_UID);
4306 return FALSE;
4309 if (dwFlags) {
4310 SetLastError(NTE_BAD_FLAGS);
4311 return FALSE;
4314 if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH,
4315 (OBJECTHDR**)&pCryptHash))
4317 SetLastError(NTE_BAD_HASH);
4318 return FALSE;
4321 switch (dwParam) {
4322 case HP_HMAC_INFO:
4323 free_hmac_info(pCryptHash->pHMACInfo);
4324 if (!copy_hmac_info(&pCryptHash->pHMACInfo, (PHMAC_INFO)pbData)) return FALSE;
4326 if (!lookup_handle(&handle_table, pCryptHash->hKey, RSAENH_MAGIC_KEY,
4327 (OBJECTHDR**)&pCryptKey))
4329 SetLastError(NTE_FAIL); /* FIXME: correct error code? */
4330 return FALSE;
4333 if (pCryptKey->aiAlgid == CALG_HMAC && !pCryptKey->dwKeyLen) {
4334 HCRYPTHASH hKeyHash;
4335 DWORD keyLen;
4337 if (!RSAENH_CPCreateHash(hProv, ((PHMAC_INFO)pbData)->HashAlgid, 0, 0,
4338 &hKeyHash))
4339 return FALSE;
4340 if (!RSAENH_CPHashData(hProv, hKeyHash, pCryptKey->blobHmacKey.pbData,
4341 pCryptKey->blobHmacKey.cbData, 0))
4343 RSAENH_CPDestroyHash(hProv, hKeyHash);
4344 return FALSE;
4346 keyLen = sizeof(pCryptKey->abKeyValue);
4347 if (!RSAENH_CPGetHashParam(hProv, hKeyHash, HP_HASHVAL, pCryptKey->abKeyValue,
4348 &keyLen, 0))
4350 RSAENH_CPDestroyHash(hProv, hKeyHash);
4351 return FALSE;
4353 pCryptKey->dwKeyLen = keyLen;
4354 RSAENH_CPDestroyHash(hProv, hKeyHash);
4356 for (i=0; i<RSAENH_MIN(pCryptKey->dwKeyLen,pCryptHash->pHMACInfo->cbInnerString); i++) {
4357 pCryptHash->pHMACInfo->pbInnerString[i] ^= pCryptKey->abKeyValue[i];
4359 for (i=0; i<RSAENH_MIN(pCryptKey->dwKeyLen,pCryptHash->pHMACInfo->cbOuterString); i++) {
4360 pCryptHash->pHMACInfo->pbOuterString[i] ^= pCryptKey->abKeyValue[i];
4363 init_hash(pCryptHash);
4364 return TRUE;
4366 case HP_HASHVAL:
4367 memcpy(pCryptHash->abHashValue, pbData, pCryptHash->dwHashSize);
4368 pCryptHash->dwState = RSAENH_HASHSTATE_FINISHED;
4369 return TRUE;
4371 case HP_TLS1PRF_SEED:
4372 return copy_data_blob(&pCryptHash->tpPRFParams.blobSeed, (PCRYPT_DATA_BLOB)pbData);
4374 case HP_TLS1PRF_LABEL:
4375 return copy_data_blob(&pCryptHash->tpPRFParams.blobLabel, (PCRYPT_DATA_BLOB)pbData);
4377 default:
4378 SetLastError(NTE_BAD_TYPE);
4379 return FALSE;
4383 /******************************************************************************
4384 * CPSetProvParam (RSAENH.@)
4386 BOOL WINAPI RSAENH_CPSetProvParam(HCRYPTPROV hProv, DWORD dwParam, BYTE *pbData, DWORD dwFlags)
4388 KEYCONTAINER *pKeyContainer;
4389 HKEY hKey;
4391 TRACE("(hProv=%08lx, dwParam=%08x, pbData=%p, dwFlags=%08x)\n", hProv, dwParam, pbData, dwFlags);
4393 if (!(pKeyContainer = get_key_container(hProv)))
4394 return FALSE;
4396 switch (dwParam)
4398 case PP_KEYSET_SEC_DESCR:
4400 SECURITY_DESCRIPTOR *sd = (SECURITY_DESCRIPTOR *)pbData;
4401 DWORD err, flags = (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET);
4402 BOOL def, present;
4403 REGSAM access = WRITE_DAC | WRITE_OWNER | ACCESS_SYSTEM_SECURITY;
4404 PSID owner = NULL, group = NULL;
4405 PACL dacl = NULL, sacl = NULL;
4407 if (!open_container_key(pKeyContainer->szName, flags, access, &hKey))
4409 SetLastError(NTE_BAD_KEYSET);
4410 return FALSE;
4413 if ((dwFlags & OWNER_SECURITY_INFORMATION && !GetSecurityDescriptorOwner(sd, &owner, &def)) ||
4414 (dwFlags & GROUP_SECURITY_INFORMATION && !GetSecurityDescriptorGroup(sd, &group, &def)) ||
4415 (dwFlags & DACL_SECURITY_INFORMATION && !GetSecurityDescriptorDacl(sd, &present, &dacl, &def)) ||
4416 (dwFlags & SACL_SECURITY_INFORMATION && !GetSecurityDescriptorSacl(sd, &present, &sacl, &def)))
4418 RegCloseKey(hKey);
4419 return FALSE;
4422 err = SetSecurityInfo(hKey, SE_REGISTRY_KEY, dwFlags, owner, group, dacl, sacl);
4423 RegCloseKey(hKey);
4424 if (err)
4426 SetLastError(err);
4427 return FALSE;
4429 return TRUE;
4431 default:
4432 FIXME("unimplemented parameter %08x\n", dwParam);
4433 return FALSE;
4437 /******************************************************************************
4438 * CPSignHash (RSAENH.@)
4440 * Sign a hash object
4442 * PARAMS
4443 * hProv [I] The key container, to which the hash object belongs.
4444 * hHash [I] The hash object to be signed.
4445 * dwKeySpec [I] AT_SIGNATURE or AT_KEYEXCHANGE: Key used to generate the signature.
4446 * sDescription [I] Should be NULL for security reasons.
4447 * dwFlags [I] 0, CRYPT_NOHASHOID or CRYPT_X931_FORMAT: Format of the signature.
4448 * pbSignature [O] Buffer, to which the signature will be stored. May be NULL to query SigLen.
4449 * pdwSigLen [I/O] Size of the buffer (in), Length of the signature (out)
4451 * RETURNS
4452 * Success: TRUE
4453 * Failure: FALSE
4455 BOOL WINAPI RSAENH_CPSignHash(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwKeySpec,
4456 LPCWSTR sDescription, DWORD dwFlags, BYTE *pbSignature,
4457 DWORD *pdwSigLen)
4459 HCRYPTKEY hCryptKey = (HCRYPTKEY)INVALID_HANDLE_VALUE;
4460 CRYPTKEY *pCryptKey;
4461 DWORD dwHashLen;
4462 BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
4463 ALG_ID aiAlgid;
4464 BOOL ret = FALSE;
4466 TRACE("(hProv=%08lx, hHash=%08lx, dwKeySpec=%08x, sDescription=%s, dwFlags=%08x, "
4467 "pbSignature=%p, pdwSigLen=%p)\n", hProv, hHash, dwKeySpec, debugstr_w(sDescription),
4468 dwFlags, pbSignature, pdwSigLen);
4470 if (dwFlags & ~(CRYPT_NOHASHOID|CRYPT_X931_FORMAT)) {
4471 SetLastError(NTE_BAD_FLAGS);
4472 return FALSE;
4475 if (!RSAENH_CPGetUserKey(hProv, dwKeySpec, &hCryptKey)) return FALSE;
4477 if (!lookup_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY,
4478 (OBJECTHDR**)&pCryptKey))
4480 SetLastError(NTE_NO_KEY);
4481 goto out;
4484 if (!pbSignature) {
4485 *pdwSigLen = pCryptKey->dwKeyLen;
4486 ret = TRUE;
4487 goto out;
4489 if (pCryptKey->dwKeyLen > *pdwSigLen)
4491 SetLastError(ERROR_MORE_DATA);
4492 *pdwSigLen = pCryptKey->dwKeyLen;
4493 goto out;
4495 *pdwSigLen = pCryptKey->dwKeyLen;
4497 if (sDescription) {
4498 if (!RSAENH_CPHashData(hProv, hHash, (const BYTE*)sDescription,
4499 (DWORD)lstrlenW(sDescription)*sizeof(WCHAR), 0))
4501 goto out;
4505 dwHashLen = sizeof(DWORD);
4506 if (!RSAENH_CPGetHashParam(hProv, hHash, HP_ALGID, (BYTE*)&aiAlgid, &dwHashLen, 0)) goto out;
4508 dwHashLen = RSAENH_MAX_HASH_SIZE;
4509 if (!RSAENH_CPGetHashParam(hProv, hHash, HP_HASHVAL, abHashValue, &dwHashLen, 0)) goto out;
4512 if (!build_hash_signature(pbSignature, *pdwSigLen, aiAlgid, abHashValue, dwHashLen, dwFlags)) {
4513 goto out;
4516 ret = encrypt_block_impl(pCryptKey->aiAlgid, PK_PRIVATE, &pCryptKey->context, pbSignature, pbSignature, RSAENH_ENCRYPT);
4517 out:
4518 RSAENH_CPDestroyKey(hProv, hCryptKey);
4519 return ret;
4522 /******************************************************************************
4523 * CPVerifySignature (RSAENH.@)
4525 * Verify the signature of a hash object.
4527 * PARAMS
4528 * hProv [I] The key container, to which the hash belongs.
4529 * hHash [I] The hash for which the signature is verified.
4530 * pbSignature [I] The binary signature.
4531 * dwSigLen [I] Length of the signature BLOB.
4532 * hPubKey [I] Public key used to verify the signature.
4533 * sDescription [I] Should be NULL for security reasons.
4534 * dwFlags [I] 0, CRYPT_NOHASHOID or CRYPT_X931_FORMAT: Format of the signature.
4536 * RETURNS
4537 * Success: TRUE (Signature is valid)
4538 * Failure: FALSE (GetLastError() == NTE_BAD_SIGNATURE, if signature is invalid)
4540 BOOL WINAPI RSAENH_CPVerifySignature(HCRYPTPROV hProv, HCRYPTHASH hHash, const BYTE *pbSignature,
4541 DWORD dwSigLen, HCRYPTKEY hPubKey, LPCWSTR sDescription,
4542 DWORD dwFlags)
4544 BYTE *pbConstructed = NULL, *pbDecrypted = NULL;
4545 CRYPTKEY *pCryptKey;
4546 DWORD dwHashLen;
4547 ALG_ID aiAlgid;
4548 BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
4549 BOOL res = FALSE;
4551 TRACE("(hProv=%08lx, hHash=%08lx, pbSignature=%p, dwSigLen=%d, hPubKey=%08lx, sDescription=%s, "
4552 "dwFlags=%08x)\n", hProv, hHash, pbSignature, dwSigLen, hPubKey, debugstr_w(sDescription),
4553 dwFlags);
4555 if (dwFlags & ~(CRYPT_NOHASHOID|CRYPT_X931_FORMAT)) {
4556 SetLastError(NTE_BAD_FLAGS);
4557 return FALSE;
4560 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
4562 SetLastError(NTE_BAD_UID);
4563 return FALSE;
4566 if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY,
4567 (OBJECTHDR**)&pCryptKey))
4569 SetLastError(NTE_BAD_KEY);
4570 return FALSE;
4573 /* in Microsoft implementation, the signature length is checked before
4574 * the signature pointer.
4576 if (dwSigLen != pCryptKey->dwKeyLen)
4578 SetLastError(NTE_BAD_SIGNATURE);
4579 return FALSE;
4582 if (!hHash || !pbSignature)
4584 SetLastError(ERROR_INVALID_PARAMETER);
4585 return FALSE;
4588 if (sDescription) {
4589 if (!RSAENH_CPHashData(hProv, hHash, (const BYTE*)sDescription,
4590 (DWORD)lstrlenW(sDescription)*sizeof(WCHAR), 0))
4592 return FALSE;
4596 dwHashLen = sizeof(DWORD);
4597 if (!RSAENH_CPGetHashParam(hProv, hHash, HP_ALGID, (BYTE*)&aiAlgid, &dwHashLen, 0)) return FALSE;
4599 dwHashLen = RSAENH_MAX_HASH_SIZE;
4600 if (!RSAENH_CPGetHashParam(hProv, hHash, HP_HASHVAL, abHashValue, &dwHashLen, 0)) return FALSE;
4602 pbConstructed = HeapAlloc(GetProcessHeap(), 0, dwSigLen);
4603 if (!pbConstructed) {
4604 SetLastError(NTE_NO_MEMORY);
4605 goto cleanup;
4608 pbDecrypted = HeapAlloc(GetProcessHeap(), 0, dwSigLen);
4609 if (!pbDecrypted) {
4610 SetLastError(NTE_NO_MEMORY);
4611 goto cleanup;
4614 if (!encrypt_block_impl(pCryptKey->aiAlgid, PK_PUBLIC, &pCryptKey->context, pbSignature, pbDecrypted,
4615 RSAENH_DECRYPT))
4617 goto cleanup;
4620 if (build_hash_signature(pbConstructed, dwSigLen, aiAlgid, abHashValue, dwHashLen, dwFlags) &&
4621 !memcmp(pbDecrypted, pbConstructed, dwSigLen)) {
4622 res = TRUE;
4623 goto cleanup;
4626 if (!(dwFlags & CRYPT_NOHASHOID) &&
4627 build_hash_signature(pbConstructed, dwSigLen, aiAlgid, abHashValue, dwHashLen, dwFlags|CRYPT_NOHASHOID) &&
4628 !memcmp(pbDecrypted, pbConstructed, dwSigLen)) {
4629 res = TRUE;
4630 goto cleanup;
4633 SetLastError(NTE_BAD_SIGNATURE);
4635 cleanup:
4636 HeapFree(GetProcessHeap(), 0, pbConstructed);
4637 HeapFree(GetProcessHeap(), 0, pbDecrypted);
4638 return res;
4641 /******************************************************************************
4642 * DllRegisterServer (RSAENH.@)
4644 HRESULT WINAPI DllRegisterServer(void)
4646 return __wine_register_resources( instance );
4649 /******************************************************************************
4650 * DllUnregisterServer (RSAENH.@)
4652 HRESULT WINAPI DllUnregisterServer(void)
4654 return __wine_unregister_resources( instance );