kernel32/nls: Added LOCALE_SNAN entries.
[wine.git] / dlls / rsaenh / rsaenh.c
blob98bba16680cbe22fed55be765139611a92dc7c03
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[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[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[MAX_PATH];
1159 if (snprintf(szRegKey, MAX_PATH, RSAENH_REGKEY, pszContainerName) >= MAX_PATH) {
1160 SetLastError(NTE_BAD_KEYSET_PARAM);
1161 return FALSE;
1162 } else {
1163 HKEY hRootKey;
1164 if (dwFlags & CRYPT_MACHINE_KEYSET)
1165 hRootKey = HKEY_LOCAL_MACHINE;
1166 else
1167 hRootKey = HKEY_CURRENT_USER;
1168 if (!RegDeleteKeyA(hRootKey, szRegKey)) {
1169 SetLastError(ERROR_SUCCESS);
1170 return TRUE;
1171 } else {
1172 SetLastError(NTE_BAD_KEYSET);
1173 return FALSE;
1178 /******************************************************************************
1179 * store_key_container_keys [Internal]
1181 * Stores key container's keys in a persistent location.
1183 * PARAMS
1184 * pKeyContainer [I] Pointer to the key container whose keys are to be saved
1186 static void store_key_container_keys(KEYCONTAINER *pKeyContainer)
1188 HKEY hKey;
1189 DWORD dwFlags;
1191 /* On WinXP, persistent keys are stored in a file located at:
1192 * $AppData$\\Microsoft\\Crypto\\RSA\\$SID$\\some_hex_string
1195 if (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET)
1196 dwFlags = CRYPTPROTECT_LOCAL_MACHINE;
1197 else
1198 dwFlags = 0;
1200 if (create_container_key(pKeyContainer, KEY_WRITE, &hKey))
1202 store_key_pair(pKeyContainer->hKeyExchangeKeyPair, hKey,
1203 AT_KEYEXCHANGE, dwFlags);
1204 store_key_pair(pKeyContainer->hSignatureKeyPair, hKey,
1205 AT_SIGNATURE, dwFlags);
1206 RegCloseKey(hKey);
1210 /******************************************************************************
1211 * store_key_container_permissions [Internal]
1213 * Stores key container's key permissions in a persistent location.
1215 * PARAMS
1216 * pKeyContainer [I] Pointer to the key container whose key permissions are to
1217 * be saved
1219 static void store_key_container_permissions(KEYCONTAINER *pKeyContainer)
1221 HKEY hKey;
1223 if (create_container_key(pKeyContainer, KEY_WRITE, &hKey))
1225 store_key_permissions(pKeyContainer->hKeyExchangeKeyPair, hKey,
1226 AT_KEYEXCHANGE);
1227 store_key_permissions(pKeyContainer->hSignatureKeyPair, hKey,
1228 AT_SIGNATURE);
1229 RegCloseKey(hKey);
1233 /******************************************************************************
1234 * release_key_container_keys [Internal]
1236 * Releases key container's keys.
1238 * PARAMS
1239 * pKeyContainer [I] Pointer to the key container whose keys are to be released.
1241 static void release_key_container_keys(KEYCONTAINER *pKeyContainer)
1243 release_handle(&handle_table, pKeyContainer->hKeyExchangeKeyPair,
1244 RSAENH_MAGIC_KEY);
1245 release_handle(&handle_table, pKeyContainer->hSignatureKeyPair,
1246 RSAENH_MAGIC_KEY);
1249 /******************************************************************************
1250 * destroy_key_container [Internal]
1252 * Destructor for key containers.
1254 * PARAMS
1255 * pObjectHdr [I] Pointer to the key container to be destroyed.
1257 static void destroy_key_container(OBJECTHDR *pObjectHdr)
1259 KEYCONTAINER *pKeyContainer = (KEYCONTAINER*)pObjectHdr;
1261 if (!(pKeyContainer->dwFlags & CRYPT_VERIFYCONTEXT))
1263 store_key_container_keys(pKeyContainer);
1264 store_key_container_permissions(pKeyContainer);
1265 release_key_container_keys(pKeyContainer);
1267 else
1268 release_key_container_keys(pKeyContainer);
1269 HeapFree( GetProcessHeap(), 0, pKeyContainer );
1272 /******************************************************************************
1273 * new_key_container [Internal]
1275 * Create a new key container. The personality (RSA Base, Strong or Enhanced CP)
1276 * of the CSP is determined via the pVTable->pszProvName string.
1278 * PARAMS
1279 * pszContainerName [I] Name of the key container.
1280 * pVTable [I] Callback functions and context info provided by the OS
1282 * RETURNS
1283 * Success: Handle to the new key container.
1284 * Failure: INVALID_HANDLE_VALUE
1286 static HCRYPTPROV new_key_container(PCCH pszContainerName, DWORD dwFlags, const VTableProvStruc *pVTable)
1288 KEYCONTAINER *pKeyContainer;
1289 HCRYPTPROV hKeyContainer;
1291 hKeyContainer = new_object(&handle_table, sizeof(KEYCONTAINER), RSAENH_MAGIC_CONTAINER,
1292 destroy_key_container, (OBJECTHDR**)&pKeyContainer);
1293 if (hKeyContainer != (HCRYPTPROV)INVALID_HANDLE_VALUE)
1295 lstrcpynA(pKeyContainer->szName, pszContainerName, MAX_PATH);
1296 pKeyContainer->dwFlags = dwFlags;
1297 pKeyContainer->dwEnumAlgsCtr = 0;
1298 pKeyContainer->hKeyExchangeKeyPair = (HCRYPTKEY)INVALID_HANDLE_VALUE;
1299 pKeyContainer->hSignatureKeyPair = (HCRYPTKEY)INVALID_HANDLE_VALUE;
1300 if (pVTable && pVTable->pszProvName) {
1301 lstrcpynA(pKeyContainer->szProvName, pVTable->pszProvName, MAX_PATH);
1302 if (!strcmp(pVTable->pszProvName, MS_DEF_PROV_A)) {
1303 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_BASE;
1304 } else if (!strcmp(pVTable->pszProvName, MS_ENHANCED_PROV_A)) {
1305 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_ENHANCED;
1306 } else if (!strcmp(pVTable->pszProvName, MS_DEF_RSA_SCHANNEL_PROV_A)) {
1307 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_SCHANNEL;
1308 } else if (!strcmp(pVTable->pszProvName, MS_ENH_RSA_AES_PROV_A) ||
1309 !strcmp(pVTable->pszProvName, MS_ENH_RSA_AES_PROV_XP_A)) {
1310 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_AES;
1311 } else {
1312 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_STRONG;
1316 /* The new key container has to be inserted into the CSP immediately
1317 * after creation to be available for CPGetProvParam's PP_ENUMCONTAINERS. */
1318 if (!(dwFlags & CRYPT_VERIFYCONTEXT)) {
1319 HKEY hKey;
1321 if (create_container_key(pKeyContainer, KEY_WRITE, &hKey))
1322 RegCloseKey(hKey);
1326 return hKeyContainer;
1329 /******************************************************************************
1330 * read_key_value [Internal]
1332 * Reads a key pair value from the registry
1334 * PARAMS
1335 * hKeyContainer [I] Crypt provider to use to import the key
1336 * hKey [I] Registry key from which to read the key pair
1337 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
1338 * dwFlags [I] Flags for unprotecting the key
1339 * phCryptKey [O] Returned key
1341 static BOOL read_key_value(HCRYPTPROV hKeyContainer, HKEY hKey, DWORD dwKeySpec, DWORD dwFlags, HCRYPTKEY *phCryptKey)
1343 LPCSTR szValueName;
1344 DWORD dwValueType, dwLen;
1345 BYTE *pbKey;
1346 DATA_BLOB blobIn, blobOut;
1347 BOOL ret = FALSE;
1349 if (!(szValueName = map_key_spec_to_key_pair_name(dwKeySpec)))
1350 return FALSE;
1351 if (RegQueryValueExA(hKey, szValueName, 0, &dwValueType, NULL, &dwLen) ==
1352 ERROR_SUCCESS)
1354 pbKey = HeapAlloc(GetProcessHeap(), 0, dwLen);
1355 if (pbKey)
1357 if (RegQueryValueExA(hKey, szValueName, 0, &dwValueType, pbKey, &dwLen) ==
1358 ERROR_SUCCESS)
1360 blobIn.pbData = pbKey;
1361 blobIn.cbData = dwLen;
1363 if (CryptUnprotectData(&blobIn, NULL, NULL, NULL, NULL,
1364 dwFlags, &blobOut))
1366 ret = import_key(hKeyContainer, blobOut.pbData, blobOut.cbData, 0, 0,
1367 FALSE, phCryptKey);
1368 LocalFree(blobOut.pbData);
1371 HeapFree(GetProcessHeap(), 0, pbKey);
1374 if (ret)
1376 CRYPTKEY *pKey;
1378 if (lookup_handle(&handle_table, *phCryptKey, RSAENH_MAGIC_KEY,
1379 (OBJECTHDR**)&pKey))
1381 if ((szValueName = map_key_spec_to_permissions_name(dwKeySpec)))
1383 dwLen = sizeof(pKey->dwPermissions);
1384 RegQueryValueExA(hKey, szValueName, 0, NULL,
1385 (BYTE *)&pKey->dwPermissions, &dwLen);
1389 return ret;
1392 /******************************************************************************
1393 * read_key_container [Internal]
1395 * Tries to read the persistent state of the key container (mainly the signature
1396 * and key exchange private keys) given by pszContainerName.
1398 * PARAMS
1399 * pszContainerName [I] Name of the key container to read from the registry
1400 * pVTable [I] Pointer to context data provided by the operating system
1402 * RETURNS
1403 * Success: Handle to the key container read from the registry
1404 * Failure: INVALID_HANDLE_VALUE
1406 static HCRYPTPROV read_key_container(PCHAR pszContainerName, DWORD dwFlags, const VTableProvStruc *pVTable)
1408 HKEY hKey;
1409 KEYCONTAINER *pKeyContainer;
1410 HCRYPTPROV hKeyContainer;
1411 HCRYPTKEY hCryptKey;
1413 if (!open_container_key(pszContainerName, dwFlags, KEY_READ, &hKey))
1415 SetLastError(NTE_BAD_KEYSET);
1416 return (HCRYPTPROV)INVALID_HANDLE_VALUE;
1419 hKeyContainer = new_key_container(pszContainerName, dwFlags, pVTable);
1420 if (hKeyContainer != (HCRYPTPROV)INVALID_HANDLE_VALUE)
1422 DWORD dwProtectFlags = (dwFlags & CRYPT_MACHINE_KEYSET) ?
1423 CRYPTPROTECT_LOCAL_MACHINE : 0;
1425 if (!lookup_handle(&handle_table, hKeyContainer, RSAENH_MAGIC_CONTAINER,
1426 (OBJECTHDR**)&pKeyContainer))
1427 return (HCRYPTPROV)INVALID_HANDLE_VALUE;
1429 /* read_key_value calls import_key, which calls import_private_key,
1430 * which implicitly installs the key value into the appropriate key
1431 * container key. Thus the ref count is incremented twice, once for
1432 * the output key value, and once for the implicit install, and needs
1433 * to be decremented to balance the two.
1435 if (read_key_value(hKeyContainer, hKey, AT_KEYEXCHANGE,
1436 dwProtectFlags, &hCryptKey))
1437 release_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY);
1438 if (read_key_value(hKeyContainer, hKey, AT_SIGNATURE,
1439 dwProtectFlags, &hCryptKey))
1440 release_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY);
1443 return hKeyContainer;
1446 /******************************************************************************
1447 * build_hash_signature [Internal]
1449 * Builds a padded version of a hash to match the length of the RSA key modulus.
1451 * PARAMS
1452 * pbSignature [O] The padded hash object is stored here.
1453 * dwLen [I] Length of the pbSignature buffer.
1454 * aiAlgid [I] Algorithm identifier of the hash to be padded.
1455 * abHashValue [I] The value of the hash object.
1456 * dwHashLen [I] Length of the hash value.
1457 * dwFlags [I] Selection of padding algorithm.
1459 * RETURNS
1460 * Success: TRUE
1461 * Failure: FALSE (NTE_BAD_ALGID)
1463 static BOOL build_hash_signature(BYTE *pbSignature, DWORD dwLen, ALG_ID aiAlgid,
1464 const BYTE *abHashValue, DWORD dwHashLen, DWORD dwFlags)
1466 /* These prefixes are meant to be concatenated with hash values of the
1467 * respective kind to form a PKCS #7 DigestInfo. */
1468 static const struct tagOIDDescriptor {
1469 ALG_ID aiAlgid;
1470 DWORD dwLen;
1471 const BYTE abOID[19];
1472 } aOIDDescriptor[] = {
1473 { CALG_MD2, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48,
1474 0x86, 0xf7, 0x0d, 0x02, 0x02, 0x05, 0x00, 0x04, 0x10 } },
1475 { CALG_MD4, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48,
1476 0x86, 0xf7, 0x0d, 0x02, 0x04, 0x05, 0x00, 0x04, 0x10 } },
1477 { CALG_MD5, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48,
1478 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10 } },
1479 { CALG_SHA, 15, { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
1480 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 } },
1481 { CALG_SHA_256, 19, { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
1482 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01,
1483 0x05, 0x00, 0x04, 0x20 } },
1484 { CALG_SHA_384, 19, { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
1485 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02,
1486 0x05, 0x00, 0x04, 0x30 } },
1487 { CALG_SHA_512, 19, { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
1488 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03,
1489 0x05, 0x00, 0x04, 0x40 } },
1490 { CALG_SSL3_SHAMD5, 0, { 0 } },
1491 { 0, 0, { 0 } }
1493 DWORD dwIdxOID, i, j;
1495 for (dwIdxOID = 0; aOIDDescriptor[dwIdxOID].aiAlgid; dwIdxOID++) {
1496 if (aOIDDescriptor[dwIdxOID].aiAlgid == aiAlgid) break;
1499 if (!aOIDDescriptor[dwIdxOID].aiAlgid) {
1500 SetLastError(NTE_BAD_ALGID);
1501 return FALSE;
1504 /* Build the padded signature */
1505 if (dwFlags & CRYPT_X931_FORMAT) {
1506 pbSignature[0] = 0x6b;
1507 for (i=1; i < dwLen - dwHashLen - 3; i++) {
1508 pbSignature[i] = 0xbb;
1510 pbSignature[i++] = 0xba;
1511 for (j=0; j < dwHashLen; j++, i++) {
1512 pbSignature[i] = abHashValue[j];
1514 pbSignature[i++] = 0x33;
1515 pbSignature[i++] = 0xcc;
1516 } else {
1517 pbSignature[0] = 0x00;
1518 pbSignature[1] = 0x01;
1519 if (dwFlags & CRYPT_NOHASHOID) {
1520 for (i=2; i < dwLen - 1 - dwHashLen; i++) {
1521 pbSignature[i] = 0xff;
1523 pbSignature[i++] = 0x00;
1524 } else {
1525 for (i=2; i < dwLen - 1 - aOIDDescriptor[dwIdxOID].dwLen - dwHashLen; i++) {
1526 pbSignature[i] = 0xff;
1528 pbSignature[i++] = 0x00;
1529 for (j=0; j < aOIDDescriptor[dwIdxOID].dwLen; j++) {
1530 pbSignature[i++] = aOIDDescriptor[dwIdxOID].abOID[j];
1533 for (j=0; j < dwHashLen; j++) {
1534 pbSignature[i++] = abHashValue[j];
1538 return TRUE;
1541 /******************************************************************************
1542 * tls1_p [Internal]
1544 * This is an implementation of the 'P_hash' helper function for TLS1's PRF.
1545 * It is used exclusively by tls1_prf. For details see RFC 2246, chapter 5.
1546 * The pseudo random stream generated by this function is exclusive or'ed with
1547 * the data in pbBuffer.
1549 * PARAMS
1550 * hHMAC [I] HMAC object, which will be used in pseudo random generation
1551 * pblobSeed [I] Seed value
1552 * pbBuffer [I/O] Pseudo random stream will be xor'ed to the provided data
1553 * dwBufferLen [I] Number of pseudo random bytes desired
1555 * RETURNS
1556 * Success: TRUE
1557 * Failure: FALSE
1559 static BOOL tls1_p(HCRYPTHASH hHMAC, const PCRYPT_DATA_BLOB pblobSeed, BYTE *pbBuffer,
1560 DWORD dwBufferLen)
1562 CRYPTHASH *pHMAC;
1563 BYTE abAi[RSAENH_MAX_HASH_SIZE];
1564 DWORD i = 0;
1566 if (!lookup_handle(&handle_table, hHMAC, RSAENH_MAGIC_HASH, (OBJECTHDR**)&pHMAC)) {
1567 SetLastError(NTE_BAD_HASH);
1568 return FALSE;
1571 /* compute A_1 = HMAC(seed) */
1572 init_hash(pHMAC);
1573 update_hash(pHMAC, pblobSeed->pbData, pblobSeed->cbData);
1574 finalize_hash(pHMAC);
1575 memcpy(abAi, pHMAC->abHashValue, pHMAC->dwHashSize);
1577 do {
1578 /* compute HMAC(A_i + seed) */
1579 init_hash(pHMAC);
1580 update_hash(pHMAC, abAi, pHMAC->dwHashSize);
1581 update_hash(pHMAC, pblobSeed->pbData, pblobSeed->cbData);
1582 finalize_hash(pHMAC);
1584 /* pseudo random stream := CONCAT_{i=1..n} ( HMAC(A_i + seed) ) */
1585 do {
1586 if (i >= dwBufferLen) break;
1587 pbBuffer[i] ^= pHMAC->abHashValue[i % pHMAC->dwHashSize];
1588 i++;
1589 } while (i % pHMAC->dwHashSize);
1591 /* compute A_{i+1} = HMAC(A_i) */
1592 init_hash(pHMAC);
1593 update_hash(pHMAC, abAi, pHMAC->dwHashSize);
1594 finalize_hash(pHMAC);
1595 memcpy(abAi, pHMAC->abHashValue, pHMAC->dwHashSize);
1596 } while (i < dwBufferLen);
1598 return TRUE;
1601 /******************************************************************************
1602 * tls1_prf [Internal]
1604 * TLS1 pseudo random function as specified in RFC 2246, chapter 5
1606 * PARAMS
1607 * hProv [I] Key container used to compute the pseudo random stream
1608 * hSecret [I] Key that holds the (pre-)master secret
1609 * pblobLabel [I] Descriptive label
1610 * pblobSeed [I] Seed value
1611 * pbBuffer [O] Pseudo random numbers will be stored here
1612 * dwBufferLen [I] Number of pseudo random bytes desired
1614 * RETURNS
1615 * Success: TRUE
1616 * Failure: FALSE
1618 static BOOL tls1_prf(HCRYPTPROV hProv, HCRYPTPROV hSecret, const PCRYPT_DATA_BLOB pblobLabel,
1619 const PCRYPT_DATA_BLOB pblobSeed, BYTE *pbBuffer, DWORD dwBufferLen)
1621 HMAC_INFO hmacInfo = { 0, NULL, 0, NULL, 0 };
1622 HCRYPTHASH hHMAC = (HCRYPTHASH)INVALID_HANDLE_VALUE;
1623 HCRYPTKEY hHalfSecret = (HCRYPTKEY)INVALID_HANDLE_VALUE;
1624 CRYPTKEY *pHalfSecret, *pSecret;
1625 DWORD dwHalfSecretLen;
1626 BOOL result = FALSE;
1627 CRYPT_DATA_BLOB blobLabelSeed;
1629 TRACE("(hProv=%08lx, hSecret=%08lx, pblobLabel=%p, pblobSeed=%p, pbBuffer=%p, dwBufferLen=%d)\n",
1630 hProv, hSecret, pblobLabel, pblobSeed, pbBuffer, dwBufferLen);
1632 if (!lookup_handle(&handle_table, hSecret, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pSecret)) {
1633 SetLastError(NTE_FAIL);
1634 return FALSE;
1637 dwHalfSecretLen = (pSecret->dwKeyLen+1)/2;
1639 /* concatenation of the label and the seed */
1640 if (!concat_data_blobs(&blobLabelSeed, pblobLabel, pblobSeed)) goto exit;
1642 /* zero out the buffer, since two random streams will be xor'ed into it. */
1643 memset(pbBuffer, 0, dwBufferLen);
1645 /* build a 'fake' key, to hold the secret. CALG_SSL2_MASTER is used since it provides
1646 * the biggest range of valid key lengths. */
1647 hHalfSecret = new_key(hProv, CALG_SSL2_MASTER, MAKELONG(0,dwHalfSecretLen*8), &pHalfSecret);
1648 if (hHalfSecret == (HCRYPTKEY)INVALID_HANDLE_VALUE) goto exit;
1650 /* Derive an HMAC_MD5 hash and call the helper function. */
1651 memcpy(pHalfSecret->abKeyValue, pSecret->abKeyValue, dwHalfSecretLen);
1652 if (!RSAENH_CPCreateHash(hProv, CALG_HMAC, hHalfSecret, 0, &hHMAC)) goto exit;
1653 hmacInfo.HashAlgid = CALG_MD5;
1654 if (!RSAENH_CPSetHashParam(hProv, hHMAC, HP_HMAC_INFO, (BYTE*)&hmacInfo, 0)) goto exit;
1655 if (!tls1_p(hHMAC, &blobLabelSeed, pbBuffer, dwBufferLen)) goto exit;
1657 /* Reconfigure to HMAC_SHA hash and call helper function again. */
1658 memcpy(pHalfSecret->abKeyValue, pSecret->abKeyValue + (pSecret->dwKeyLen/2), dwHalfSecretLen);
1659 hmacInfo.HashAlgid = CALG_SHA;
1660 if (!RSAENH_CPSetHashParam(hProv, hHMAC, HP_HMAC_INFO, (BYTE*)&hmacInfo, 0)) goto exit;
1661 if (!tls1_p(hHMAC, &blobLabelSeed, pbBuffer, dwBufferLen)) goto exit;
1663 result = TRUE;
1664 exit:
1665 release_handle(&handle_table, hHalfSecret, RSAENH_MAGIC_KEY);
1666 if (hHMAC != (HCRYPTHASH)INVALID_HANDLE_VALUE) RSAENH_CPDestroyHash(hProv, hHMAC);
1667 free_data_blob(&blobLabelSeed);
1668 return result;
1671 /******************************************************************************
1672 * pad_data [Internal]
1674 * Helper function for data padding according to PKCS1 #2
1676 * PARAMS
1677 * abData [I] The data to be padded
1678 * dwDataLen [I] Length of the data
1679 * abBuffer [O] Padded data will be stored here
1680 * dwBufferLen [I] Length of the buffer (also length of padded data)
1681 * dwFlags [I] Padding format (CRYPT_SSL2_FALLBACK)
1683 * RETURN
1684 * Success: TRUE
1685 * Failure: FALSE (NTE_BAD_LEN, too much data to pad)
1687 static BOOL pad_data(const BYTE *abData, DWORD dwDataLen, BYTE *abBuffer, DWORD dwBufferLen,
1688 DWORD dwFlags)
1690 DWORD i;
1692 /* Ensure there is enough space for PKCS1 #2 padding */
1693 if (dwDataLen > dwBufferLen-11) {
1694 SetLastError(NTE_BAD_LEN);
1695 return FALSE;
1698 memmove(abBuffer + dwBufferLen - dwDataLen, abData, dwDataLen);
1700 abBuffer[0] = 0x00;
1701 abBuffer[1] = RSAENH_PKC_BLOCKTYPE;
1702 for (i=2; i < dwBufferLen - dwDataLen - 1; i++)
1703 do gen_rand_impl(&abBuffer[i], 1); while (!abBuffer[i]);
1704 if (dwFlags & CRYPT_SSL2_FALLBACK)
1705 for (i-=8; i < dwBufferLen - dwDataLen - 1; i++)
1706 abBuffer[i] = 0x03;
1707 abBuffer[i] = 0x00;
1709 return TRUE;
1712 /******************************************************************************
1713 * unpad_data [Internal]
1715 * Remove the PKCS1 padding from RSA decrypted data
1717 * PARAMS
1718 * abData [I] The padded data
1719 * dwDataLen [I] Length of the padded data
1720 * abBuffer [O] Data without padding will be stored here
1721 * dwBufferLen [I/O] I: Length of the buffer, O: Length of unpadded data
1722 * dwFlags [I] Currently none defined
1724 * RETURNS
1725 * Success: TRUE
1726 * Failure: FALSE, (NTE_BAD_DATA, no valid PKCS1 padding or buffer too small)
1728 static BOOL unpad_data(const BYTE *abData, DWORD dwDataLen, BYTE *abBuffer, DWORD *dwBufferLen,
1729 DWORD dwFlags)
1731 DWORD i;
1733 if (dwDataLen < 3)
1735 SetLastError(NTE_BAD_DATA);
1736 return FALSE;
1738 for (i=2; i<dwDataLen; i++)
1739 if (!abData[i])
1740 break;
1742 if ((i == dwDataLen) || (*dwBufferLen < dwDataLen - i - 1) ||
1743 (abData[0] != 0x00) || (abData[1] != RSAENH_PKC_BLOCKTYPE))
1745 SetLastError(NTE_BAD_DATA);
1746 return FALSE;
1749 *dwBufferLen = dwDataLen - i - 1;
1750 memmove(abBuffer, abData + i + 1, *dwBufferLen);
1751 return TRUE;
1754 /******************************************************************************
1755 * CPAcquireContext (RSAENH.@)
1757 * Acquire a handle to the key container specified by pszContainer
1759 * PARAMS
1760 * phProv [O] Pointer to the location the acquired handle will be written to.
1761 * pszContainer [I] Name of the desired key container. See Notes
1762 * dwFlags [I] Flags. See Notes.
1763 * pVTable [I] Pointer to a PVTableProvStruct containing callbacks.
1765 * RETURNS
1766 * Success: TRUE
1767 * Failure: FALSE
1769 * NOTES
1770 * If pszContainer is NULL or points to a zero length string the user's login
1771 * name will be used as the key container name.
1773 * If the CRYPT_NEW_KEYSET flag is set in dwFlags a new keyset will be created.
1774 * If a keyset with the given name already exists, the function fails and sets
1775 * last error to NTE_EXISTS. If CRYPT_NEW_KEYSET is not set and the specified
1776 * key container does not exist, function fails and sets last error to
1777 * NTE_BAD_KEYSET.
1779 BOOL WINAPI RSAENH_CPAcquireContext(HCRYPTPROV *phProv, LPSTR pszContainer,
1780 DWORD dwFlags, PVTableProvStruc pVTable)
1782 CHAR szKeyContainerName[MAX_PATH];
1784 TRACE("(phProv=%p, pszContainer=%s, dwFlags=%08x, pVTable=%p)\n", phProv,
1785 debugstr_a(pszContainer), dwFlags, pVTable);
1787 if (pszContainer && *pszContainer)
1789 lstrcpynA(szKeyContainerName, pszContainer, MAX_PATH);
1791 else
1793 DWORD dwLen = sizeof(szKeyContainerName);
1794 if (!GetUserNameA(szKeyContainerName, &dwLen)) return FALSE;
1797 switch (dwFlags & (CRYPT_NEWKEYSET|CRYPT_VERIFYCONTEXT|CRYPT_DELETEKEYSET))
1799 case 0:
1800 *phProv = read_key_container(szKeyContainerName, dwFlags, pVTable);
1801 break;
1803 case CRYPT_DELETEKEYSET:
1804 return delete_container_key(szKeyContainerName, dwFlags);
1806 case CRYPT_NEWKEYSET:
1807 *phProv = read_key_container(szKeyContainerName, dwFlags, pVTable);
1808 if (*phProv != (HCRYPTPROV)INVALID_HANDLE_VALUE)
1810 release_handle(&handle_table, *phProv, RSAENH_MAGIC_CONTAINER);
1811 TRACE("Can't create new keyset, already exists\n");
1812 SetLastError(NTE_EXISTS);
1813 return FALSE;
1815 *phProv = new_key_container(szKeyContainerName, dwFlags, pVTable);
1816 break;
1818 case CRYPT_VERIFYCONTEXT|CRYPT_NEWKEYSET:
1819 case CRYPT_VERIFYCONTEXT:
1820 if (pszContainer && *pszContainer) {
1821 TRACE("pszContainer should be empty\n");
1822 SetLastError(NTE_BAD_FLAGS);
1823 return FALSE;
1825 *phProv = new_key_container("", dwFlags, pVTable);
1826 break;
1828 default:
1829 *phProv = (HCRYPTPROV)INVALID_HANDLE_VALUE;
1830 SetLastError(NTE_BAD_FLAGS);
1831 return FALSE;
1834 if (*phProv != (HCRYPTPROV)INVALID_HANDLE_VALUE) {
1835 SetLastError(ERROR_SUCCESS);
1836 return TRUE;
1837 } else {
1838 return FALSE;
1842 /******************************************************************************
1843 * CPCreateHash (RSAENH.@)
1845 * CPCreateHash creates and initializes a new hash object.
1847 * PARAMS
1848 * hProv [I] Handle to the key container to which the new hash will belong.
1849 * Algid [I] Identifies the hash algorithm, which will be used for the hash.
1850 * hKey [I] Handle to a session key applied for keyed hashes.
1851 * dwFlags [I] Currently no flags defined. Must be zero.
1852 * phHash [O] Points to the location where a handle to the new hash will be stored.
1854 * RETURNS
1855 * Success: TRUE
1856 * Failure: FALSE
1858 * NOTES
1859 * hKey is a handle to a session key applied in keyed hashes like MAC and HMAC.
1860 * If a normal hash object is to be created (like e.g. MD2 or SHA1) hKey must be zero.
1862 BOOL WINAPI RSAENH_CPCreateHash(HCRYPTPROV hProv, ALG_ID Algid, HCRYPTKEY hKey, DWORD dwFlags,
1863 HCRYPTHASH *phHash)
1865 CRYPTKEY *pCryptKey;
1866 CRYPTHASH *pCryptHash;
1867 const PROV_ENUMALGS_EX *peaAlgidInfo;
1869 TRACE("(hProv=%08lx, Algid=%08x, hKey=%08lx, dwFlags=%08x, phHash=%p)\n", hProv, Algid, hKey,
1870 dwFlags, phHash);
1872 peaAlgidInfo = get_algid_info(hProv, Algid);
1873 if (!peaAlgidInfo) return FALSE;
1875 if (dwFlags)
1877 SetLastError(NTE_BAD_FLAGS);
1878 return FALSE;
1881 if (Algid == CALG_MAC || Algid == CALG_HMAC || Algid == CALG_SCHANNEL_MASTER_HASH ||
1882 Algid == CALG_TLS1PRF)
1884 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey)) {
1885 SetLastError(NTE_BAD_KEY);
1886 return FALSE;
1889 if ((Algid == CALG_MAC) && (GET_ALG_TYPE(pCryptKey->aiAlgid) != ALG_TYPE_BLOCK)) {
1890 SetLastError(NTE_BAD_KEY);
1891 return FALSE;
1894 if ((Algid == CALG_SCHANNEL_MASTER_HASH || Algid == CALG_TLS1PRF) &&
1895 (pCryptKey->aiAlgid != CALG_TLS1_MASTER))
1897 SetLastError(NTE_BAD_KEY);
1898 return FALSE;
1900 if (Algid == CALG_SCHANNEL_MASTER_HASH &&
1901 ((!pCryptKey->siSChannelInfo.blobClientRandom.cbData) ||
1902 (!pCryptKey->siSChannelInfo.blobServerRandom.cbData)))
1904 SetLastError(ERROR_INVALID_PARAMETER);
1905 return FALSE;
1908 if ((Algid == CALG_TLS1PRF) && (pCryptKey->dwState != RSAENH_KEYSTATE_MASTERKEY)) {
1909 SetLastError(NTE_BAD_KEY_STATE);
1910 return FALSE;
1914 *phHash = new_object(&handle_table, sizeof(CRYPTHASH), RSAENH_MAGIC_HASH,
1915 destroy_hash, (OBJECTHDR**)&pCryptHash);
1916 if (!pCryptHash) return FALSE;
1918 pCryptHash->aiAlgid = Algid;
1919 pCryptHash->hKey = hKey;
1920 pCryptHash->hProv = hProv;
1921 pCryptHash->dwState = RSAENH_HASHSTATE_HASHING;
1922 pCryptHash->pHMACInfo = NULL;
1923 pCryptHash->dwHashSize = peaAlgidInfo->dwDefaultLen >> 3;
1924 init_data_blob(&pCryptHash->tpPRFParams.blobLabel);
1925 init_data_blob(&pCryptHash->tpPRFParams.blobSeed);
1927 if (Algid == CALG_SCHANNEL_MASTER_HASH) {
1928 static const char keyex[] = "key expansion";
1929 BYTE key_expansion[sizeof keyex];
1930 CRYPT_DATA_BLOB blobRandom, blobKeyExpansion = { 13, key_expansion };
1932 memcpy( key_expansion, keyex, sizeof keyex );
1934 if (pCryptKey->dwState != RSAENH_KEYSTATE_MASTERKEY) {
1935 static const char msec[] = "master secret";
1936 BYTE master_secret[sizeof msec];
1937 CRYPT_DATA_BLOB blobLabel = { 13, master_secret };
1938 BYTE abKeyValue[48];
1940 memcpy( master_secret, msec, sizeof msec );
1942 /* See RFC 2246, chapter 8.1 */
1943 if (!concat_data_blobs(&blobRandom,
1944 &pCryptKey->siSChannelInfo.blobClientRandom,
1945 &pCryptKey->siSChannelInfo.blobServerRandom))
1947 return FALSE;
1949 tls1_prf(hProv, hKey, &blobLabel, &blobRandom, abKeyValue, 48);
1950 pCryptKey->dwState = RSAENH_KEYSTATE_MASTERKEY;
1951 memcpy(pCryptKey->abKeyValue, abKeyValue, 48);
1952 free_data_blob(&blobRandom);
1955 /* See RFC 2246, chapter 6.3 */
1956 if (!concat_data_blobs(&blobRandom,
1957 &pCryptKey->siSChannelInfo.blobServerRandom,
1958 &pCryptKey->siSChannelInfo.blobClientRandom))
1960 return FALSE;
1962 tls1_prf(hProv, hKey, &blobKeyExpansion, &blobRandom, pCryptHash->abHashValue,
1963 RSAENH_MAX_HASH_SIZE);
1964 free_data_blob(&blobRandom);
1967 return init_hash(pCryptHash);
1970 /******************************************************************************
1971 * CPDestroyHash (RSAENH.@)
1973 * Releases the handle to a hash object. The object is destroyed if its reference
1974 * count reaches zero.
1976 * PARAMS
1977 * hProv [I] Handle to the key container to which the hash object belongs.
1978 * hHash [I] Handle to the hash object to be released.
1980 * RETURNS
1981 * Success: TRUE
1982 * Failure: FALSE
1984 BOOL WINAPI RSAENH_CPDestroyHash(HCRYPTPROV hProv, HCRYPTHASH hHash)
1986 TRACE("(hProv=%08lx, hHash=%08lx)\n", hProv, hHash);
1988 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
1990 SetLastError(NTE_BAD_UID);
1991 return FALSE;
1994 if (!release_handle(&handle_table, hHash, RSAENH_MAGIC_HASH))
1996 SetLastError(NTE_BAD_HASH);
1997 return FALSE;
2000 return TRUE;
2003 /******************************************************************************
2004 * CPDestroyKey (RSAENH.@)
2006 * Releases the handle to a key object. The object is destroyed if its reference
2007 * count reaches zero.
2009 * PARAMS
2010 * hProv [I] Handle to the key container to which the key object belongs.
2011 * hKey [I] Handle to the key object to be released.
2013 * RETURNS
2014 * Success: TRUE
2015 * Failure: FALSE
2017 BOOL WINAPI RSAENH_CPDestroyKey(HCRYPTPROV hProv, HCRYPTKEY hKey)
2019 TRACE("(hProv=%08lx, hKey=%08lx)\n", hProv, hKey);
2021 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2023 SetLastError(NTE_BAD_UID);
2024 return FALSE;
2027 if (!release_handle(&handle_table, hKey, RSAENH_MAGIC_KEY))
2029 SetLastError(NTE_BAD_KEY);
2030 return FALSE;
2033 return TRUE;
2036 /******************************************************************************
2037 * CPDuplicateHash (RSAENH.@)
2039 * Clones a hash object including its current state.
2041 * PARAMS
2042 * hUID [I] Handle to the key container the hash belongs to.
2043 * hHash [I] Handle to the hash object to be cloned.
2044 * pdwReserved [I] Reserved. Must be NULL.
2045 * dwFlags [I] No flags are currently defined. Must be 0.
2046 * phHash [O] Handle to the cloned hash object.
2048 * RETURNS
2049 * Success: TRUE.
2050 * Failure: FALSE.
2052 BOOL WINAPI RSAENH_CPDuplicateHash(HCRYPTPROV hUID, HCRYPTHASH hHash, DWORD *pdwReserved,
2053 DWORD dwFlags, HCRYPTHASH *phHash)
2055 CRYPTHASH *pSrcHash, *pDestHash;
2057 TRACE("(hUID=%08lx, hHash=%08lx, pdwReserved=%p, dwFlags=%08x, phHash=%p)\n", hUID, hHash,
2058 pdwReserved, dwFlags, phHash);
2060 if (!is_valid_handle(&handle_table, hUID, RSAENH_MAGIC_CONTAINER))
2062 SetLastError(NTE_BAD_UID);
2063 return FALSE;
2066 if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH, (OBJECTHDR**)&pSrcHash))
2068 SetLastError(NTE_BAD_HASH);
2069 return FALSE;
2072 if (!phHash || pdwReserved || dwFlags)
2074 SetLastError(ERROR_INVALID_PARAMETER);
2075 return FALSE;
2078 *phHash = new_object(&handle_table, sizeof(CRYPTHASH), RSAENH_MAGIC_HASH,
2079 destroy_hash, (OBJECTHDR**)&pDestHash);
2080 if (*phHash != (HCRYPTHASH)INVALID_HANDLE_VALUE)
2082 *pDestHash = *pSrcHash;
2083 duplicate_hash_impl(pSrcHash->aiAlgid, &pSrcHash->context, &pDestHash->context);
2084 copy_hmac_info(&pDestHash->pHMACInfo, pSrcHash->pHMACInfo);
2085 copy_data_blob(&pDestHash->tpPRFParams.blobLabel, &pSrcHash->tpPRFParams.blobLabel);
2086 copy_data_blob(&pDestHash->tpPRFParams.blobSeed, &pSrcHash->tpPRFParams.blobSeed);
2089 return *phHash != (HCRYPTHASH)INVALID_HANDLE_VALUE;
2092 /******************************************************************************
2093 * CPDuplicateKey (RSAENH.@)
2095 * Clones a key object including its current state.
2097 * PARAMS
2098 * hUID [I] Handle to the key container the hash belongs to.
2099 * hKey [I] Handle to the key object to be cloned.
2100 * pdwReserved [I] Reserved. Must be NULL.
2101 * dwFlags [I] No flags are currently defined. Must be 0.
2102 * phHash [O] Handle to the cloned key object.
2104 * RETURNS
2105 * Success: TRUE.
2106 * Failure: FALSE.
2108 BOOL WINAPI RSAENH_CPDuplicateKey(HCRYPTPROV hUID, HCRYPTKEY hKey, DWORD *pdwReserved,
2109 DWORD dwFlags, HCRYPTKEY *phKey)
2111 CRYPTKEY *pSrcKey, *pDestKey;
2113 TRACE("(hUID=%08lx, hKey=%08lx, pdwReserved=%p, dwFlags=%08x, phKey=%p)\n", hUID, hKey,
2114 pdwReserved, dwFlags, phKey);
2116 if (!is_valid_handle(&handle_table, hUID, RSAENH_MAGIC_CONTAINER))
2118 SetLastError(NTE_BAD_UID);
2119 return FALSE;
2122 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pSrcKey))
2124 SetLastError(NTE_BAD_KEY);
2125 return FALSE;
2128 if (!phKey || pdwReserved || dwFlags)
2130 SetLastError(ERROR_INVALID_PARAMETER);
2131 return FALSE;
2134 *phKey = new_object(&handle_table, sizeof(CRYPTKEY), RSAENH_MAGIC_KEY, destroy_key,
2135 (OBJECTHDR**)&pDestKey);
2136 if (*phKey != (HCRYPTKEY)INVALID_HANDLE_VALUE)
2138 *pDestKey = *pSrcKey;
2139 copy_data_blob(&pDestKey->siSChannelInfo.blobServerRandom,
2140 &pSrcKey->siSChannelInfo.blobServerRandom);
2141 copy_data_blob(&pDestKey->siSChannelInfo.blobClientRandom,
2142 &pSrcKey->siSChannelInfo.blobClientRandom);
2143 duplicate_key_impl(pSrcKey->aiAlgid, &pSrcKey->context, &pDestKey->context);
2144 return TRUE;
2146 else
2148 return FALSE;
2152 /******************************************************************************
2153 * CPEncrypt (RSAENH.@)
2155 * Encrypt data.
2157 * PARAMS
2158 * hProv [I] The key container hKey and hHash belong to.
2159 * hKey [I] The key used to encrypt the data.
2160 * hHash [I] An optional hash object for parallel hashing. See notes.
2161 * Final [I] Indicates if this is the last block of data to encrypt.
2162 * dwFlags [I] Currently no flags defined. Must be zero.
2163 * pbData [I/O] Pointer to the data to encrypt. Encrypted data will also be stored there.
2164 * pdwDataLen [I/O] I: Length of data to encrypt, O: Length of encrypted data.
2165 * dwBufLen [I] Size of the buffer at pbData.
2167 * RETURNS
2168 * Success: TRUE.
2169 * Failure: FALSE.
2171 * NOTES
2172 * If a hash object handle is provided in hHash, it will be updated with the plaintext.
2173 * This is useful for message signatures.
2175 * This function uses the standard WINAPI protocol for querying data of dynamic length.
2177 BOOL WINAPI RSAENH_CPEncrypt(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final,
2178 DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen, DWORD dwBufLen)
2180 CRYPTKEY *pCryptKey;
2181 BYTE *in, out[RSAENH_MAX_BLOCK_SIZE], o[RSAENH_MAX_BLOCK_SIZE];
2182 DWORD dwEncryptedLen, i, j, k;
2184 TRACE("(hProv=%08lx, hKey=%08lx, hHash=%08lx, Final=%d, dwFlags=%08x, pbData=%p, "
2185 "pdwDataLen=%p, dwBufLen=%d)\n", hProv, hKey, hHash, Final, dwFlags, pbData, pdwDataLen,
2186 dwBufLen);
2188 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2190 SetLastError(NTE_BAD_UID);
2191 return FALSE;
2194 if (dwFlags)
2196 SetLastError(NTE_BAD_FLAGS);
2197 return FALSE;
2200 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2202 SetLastError(NTE_BAD_KEY);
2203 return FALSE;
2206 if (pCryptKey->dwState == RSAENH_KEYSTATE_IDLE)
2207 pCryptKey->dwState = RSAENH_KEYSTATE_ENCRYPTING;
2209 if (pCryptKey->dwState != RSAENH_KEYSTATE_ENCRYPTING)
2211 SetLastError(NTE_BAD_DATA);
2212 return FALSE;
2215 if (is_valid_handle(&handle_table, hHash, RSAENH_MAGIC_HASH)) {
2216 if (!RSAENH_CPHashData(hProv, hHash, pbData, *pdwDataLen, 0)) return FALSE;
2219 if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_BLOCK) {
2220 if (!Final && (*pdwDataLen % pCryptKey->dwBlockLen)) {
2221 SetLastError(NTE_BAD_DATA);
2222 return FALSE;
2225 dwEncryptedLen = (*pdwDataLen/pCryptKey->dwBlockLen+(Final?1:0))*pCryptKey->dwBlockLen;
2227 if (pbData == NULL) {
2228 *pdwDataLen = dwEncryptedLen;
2229 return TRUE;
2231 else if (dwEncryptedLen > dwBufLen) {
2232 *pdwDataLen = dwEncryptedLen;
2233 SetLastError(ERROR_MORE_DATA);
2234 return FALSE;
2237 /* Pad final block with length bytes */
2238 for (i=*pdwDataLen; i<dwEncryptedLen; i++) pbData[i] = dwEncryptedLen - *pdwDataLen;
2239 *pdwDataLen = dwEncryptedLen;
2241 for (i=0, in=pbData; i<*pdwDataLen; i+=pCryptKey->dwBlockLen, in+=pCryptKey->dwBlockLen) {
2242 switch (pCryptKey->dwMode) {
2243 case CRYPT_MODE_ECB:
2244 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out,
2245 RSAENH_ENCRYPT);
2246 break;
2248 case CRYPT_MODE_CBC:
2249 for (j=0; j<pCryptKey->dwBlockLen; j++) in[j] ^= pCryptKey->abChainVector[j];
2250 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out,
2251 RSAENH_ENCRYPT);
2252 memcpy(pCryptKey->abChainVector, out, pCryptKey->dwBlockLen);
2253 break;
2255 case CRYPT_MODE_CFB:
2256 for (j=0; j<pCryptKey->dwBlockLen; j++) {
2257 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context,
2258 pCryptKey->abChainVector, o, RSAENH_ENCRYPT);
2259 out[j] = in[j] ^ o[0];
2260 for (k=0; k<pCryptKey->dwBlockLen-1; k++)
2261 pCryptKey->abChainVector[k] = pCryptKey->abChainVector[k+1];
2262 pCryptKey->abChainVector[k] = out[j];
2264 break;
2266 default:
2267 SetLastError(NTE_BAD_ALGID);
2268 return FALSE;
2270 memcpy(in, out, pCryptKey->dwBlockLen);
2272 } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_STREAM) {
2273 if (pbData == NULL) {
2274 *pdwDataLen = dwBufLen;
2275 return TRUE;
2277 encrypt_stream_impl(pCryptKey->aiAlgid, &pCryptKey->context, pbData, *pdwDataLen);
2278 } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_RSA) {
2279 if (pCryptKey->aiAlgid == CALG_RSA_SIGN) {
2280 SetLastError(NTE_BAD_KEY);
2281 return FALSE;
2283 if (!pbData) {
2284 *pdwDataLen = pCryptKey->dwBlockLen;
2285 return TRUE;
2287 if (dwBufLen < pCryptKey->dwBlockLen) {
2288 SetLastError(ERROR_MORE_DATA);
2289 return FALSE;
2291 if (!pad_data(pbData, *pdwDataLen, pbData, pCryptKey->dwBlockLen, dwFlags)) return FALSE;
2292 encrypt_block_impl(pCryptKey->aiAlgid, PK_PUBLIC, &pCryptKey->context, pbData, pbData, RSAENH_ENCRYPT);
2293 *pdwDataLen = pCryptKey->dwBlockLen;
2294 Final = TRUE;
2295 } else {
2296 SetLastError(NTE_BAD_TYPE);
2297 return FALSE;
2300 if (Final) setup_key(pCryptKey);
2302 return TRUE;
2305 /******************************************************************************
2306 * CPDecrypt (RSAENH.@)
2308 * Decrypt data.
2310 * PARAMS
2311 * hProv [I] The key container hKey and hHash belong to.
2312 * hKey [I] The key used to decrypt the data.
2313 * hHash [I] An optional hash object for parallel hashing. See notes.
2314 * Final [I] Indicates if this is the last block of data to decrypt.
2315 * dwFlags [I] Currently no flags defined. Must be zero.
2316 * pbData [I/O] Pointer to the data to decrypt. Plaintext will also be stored there.
2317 * pdwDataLen [I/O] I: Length of ciphertext, O: Length of plaintext.
2319 * RETURNS
2320 * Success: TRUE.
2321 * Failure: FALSE.
2323 * NOTES
2324 * If a hash object handle is provided in hHash, it will be updated with the plaintext.
2325 * This is useful for message signatures.
2327 * This function uses the standard WINAPI protocol for querying data of dynamic length.
2329 BOOL WINAPI RSAENH_CPDecrypt(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final,
2330 DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2332 CRYPTKEY *pCryptKey;
2333 BYTE *in, out[RSAENH_MAX_BLOCK_SIZE], o[RSAENH_MAX_BLOCK_SIZE];
2334 DWORD i, j, k;
2335 DWORD dwMax;
2337 TRACE("(hProv=%08lx, hKey=%08lx, hHash=%08lx, Final=%d, dwFlags=%08x, pbData=%p, "
2338 "pdwDataLen=%p)\n", hProv, hKey, hHash, Final, dwFlags, pbData, pdwDataLen);
2340 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2342 SetLastError(NTE_BAD_UID);
2343 return FALSE;
2346 if (dwFlags)
2348 SetLastError(NTE_BAD_FLAGS);
2349 return FALSE;
2352 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2354 SetLastError(NTE_BAD_KEY);
2355 return FALSE;
2358 if (pCryptKey->dwState == RSAENH_KEYSTATE_IDLE)
2359 pCryptKey->dwState = RSAENH_KEYSTATE_ENCRYPTING;
2361 if (pCryptKey->dwState != RSAENH_KEYSTATE_ENCRYPTING)
2363 SetLastError(NTE_BAD_DATA);
2364 return FALSE;
2367 dwMax=*pdwDataLen;
2369 if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_BLOCK) {
2370 for (i=0, in=pbData; i<*pdwDataLen; i+=pCryptKey->dwBlockLen, in+=pCryptKey->dwBlockLen) {
2371 switch (pCryptKey->dwMode) {
2372 case CRYPT_MODE_ECB:
2373 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out,
2374 RSAENH_DECRYPT);
2375 break;
2377 case CRYPT_MODE_CBC:
2378 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context, in, out,
2379 RSAENH_DECRYPT);
2380 for (j=0; j<pCryptKey->dwBlockLen; j++) out[j] ^= pCryptKey->abChainVector[j];
2381 memcpy(pCryptKey->abChainVector, in, pCryptKey->dwBlockLen);
2382 break;
2384 case CRYPT_MODE_CFB:
2385 for (j=0; j<pCryptKey->dwBlockLen; j++) {
2386 encrypt_block_impl(pCryptKey->aiAlgid, 0, &pCryptKey->context,
2387 pCryptKey->abChainVector, o, RSAENH_ENCRYPT);
2388 out[j] = in[j] ^ o[0];
2389 for (k=0; k<pCryptKey->dwBlockLen-1; k++)
2390 pCryptKey->abChainVector[k] = pCryptKey->abChainVector[k+1];
2391 pCryptKey->abChainVector[k] = in[j];
2393 break;
2395 default:
2396 SetLastError(NTE_BAD_ALGID);
2397 return FALSE;
2399 memcpy(in, out, pCryptKey->dwBlockLen);
2401 if (Final) {
2402 if (pbData[*pdwDataLen-1] &&
2403 pbData[*pdwDataLen-1] <= pCryptKey->dwBlockLen &&
2404 pbData[*pdwDataLen-1] <= *pdwDataLen) {
2405 BOOL padOkay = TRUE;
2407 /* check that every bad byte has the same value */
2408 for (i = 1; padOkay && i < pbData[*pdwDataLen-1]; i++)
2409 if (pbData[*pdwDataLen - i - 1] != pbData[*pdwDataLen - 1])
2410 padOkay = FALSE;
2411 if (padOkay)
2412 *pdwDataLen -= pbData[*pdwDataLen-1];
2413 else {
2414 SetLastError(NTE_BAD_DATA);
2415 setup_key(pCryptKey);
2416 return FALSE;
2419 else {
2420 SetLastError(NTE_BAD_DATA);
2421 setup_key(pCryptKey);
2422 return FALSE;
2426 } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_STREAM) {
2427 encrypt_stream_impl(pCryptKey->aiAlgid, &pCryptKey->context, pbData, *pdwDataLen);
2428 } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_RSA) {
2429 if (pCryptKey->aiAlgid == CALG_RSA_SIGN) {
2430 SetLastError(NTE_BAD_KEY);
2431 return FALSE;
2433 encrypt_block_impl(pCryptKey->aiAlgid, PK_PRIVATE, &pCryptKey->context, pbData, pbData, RSAENH_DECRYPT);
2434 if (!unpad_data(pbData, pCryptKey->dwBlockLen, pbData, pdwDataLen, dwFlags)) return FALSE;
2435 Final = TRUE;
2436 } else {
2437 SetLastError(NTE_BAD_TYPE);
2438 return FALSE;
2441 if (Final) setup_key(pCryptKey);
2443 if (is_valid_handle(&handle_table, hHash, RSAENH_MAGIC_HASH)) {
2444 if (*pdwDataLen>dwMax ||
2445 !RSAENH_CPHashData(hProv, hHash, pbData, *pdwDataLen, 0)) return FALSE;
2448 return TRUE;
2451 static BOOL crypt_export_simple(CRYPTKEY *pCryptKey, CRYPTKEY *pPubKey,
2452 DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2454 BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2455 ALG_ID *pAlgid = (ALG_ID*)(pBlobHeader+1);
2456 DWORD dwDataLen;
2458 if (!(GET_ALG_CLASS(pCryptKey->aiAlgid)&(ALG_CLASS_DATA_ENCRYPT|ALG_CLASS_MSG_ENCRYPT))) {
2459 SetLastError(NTE_BAD_KEY); /* FIXME: error code? */
2460 return FALSE;
2463 dwDataLen = sizeof(BLOBHEADER) + sizeof(ALG_ID) + pPubKey->dwBlockLen;
2464 if (pbData) {
2465 if (*pdwDataLen < dwDataLen) {
2466 SetLastError(ERROR_MORE_DATA);
2467 *pdwDataLen = dwDataLen;
2468 return FALSE;
2471 pBlobHeader->bType = SIMPLEBLOB;
2472 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2473 pBlobHeader->reserved = 0;
2474 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2476 *pAlgid = pPubKey->aiAlgid;
2478 if (!pad_data(pCryptKey->abKeyValue, pCryptKey->dwKeyLen, (BYTE*)(pAlgid+1),
2479 pPubKey->dwBlockLen, dwFlags))
2481 return FALSE;
2484 encrypt_block_impl(pPubKey->aiAlgid, PK_PUBLIC, &pPubKey->context, (BYTE*)(pAlgid+1),
2485 (BYTE*)(pAlgid+1), RSAENH_ENCRYPT);
2487 *pdwDataLen = dwDataLen;
2488 return TRUE;
2491 static BOOL crypt_export_public_key(CRYPTKEY *pCryptKey, BYTE *pbData,
2492 DWORD *pdwDataLen)
2494 BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2495 RSAPUBKEY *pRSAPubKey = (RSAPUBKEY*)(pBlobHeader+1);
2496 DWORD dwDataLen;
2498 if ((pCryptKey->aiAlgid != CALG_RSA_KEYX) && (pCryptKey->aiAlgid != CALG_RSA_SIGN)) {
2499 SetLastError(NTE_BAD_KEY);
2500 return FALSE;
2503 dwDataLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) + pCryptKey->dwKeyLen;
2504 if (pbData) {
2505 if (*pdwDataLen < dwDataLen) {
2506 SetLastError(ERROR_MORE_DATA);
2507 *pdwDataLen = dwDataLen;
2508 return FALSE;
2511 pBlobHeader->bType = PUBLICKEYBLOB;
2512 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2513 pBlobHeader->reserved = 0;
2514 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2516 pRSAPubKey->magic = RSAENH_MAGIC_RSA1;
2517 pRSAPubKey->bitlen = pCryptKey->dwKeyLen << 3;
2519 export_public_key_impl((BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2520 pCryptKey->dwKeyLen, &pRSAPubKey->pubexp);
2522 *pdwDataLen = dwDataLen;
2523 return TRUE;
2526 static BOOL crypt_export_private_key(CRYPTKEY *pCryptKey, BOOL force,
2527 BYTE *pbData, DWORD *pdwDataLen)
2529 BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2530 RSAPUBKEY *pRSAPubKey = (RSAPUBKEY*)(pBlobHeader+1);
2531 DWORD dwDataLen;
2533 if ((pCryptKey->aiAlgid != CALG_RSA_KEYX) && (pCryptKey->aiAlgid != CALG_RSA_SIGN)) {
2534 SetLastError(NTE_BAD_KEY);
2535 return FALSE;
2537 if (!force && !(pCryptKey->dwPermissions & CRYPT_EXPORT))
2539 SetLastError(NTE_BAD_KEY_STATE);
2540 return FALSE;
2543 dwDataLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) +
2544 2 * pCryptKey->dwKeyLen + 5 * ((pCryptKey->dwKeyLen + 1) >> 1);
2545 if (pbData) {
2546 if (*pdwDataLen < dwDataLen) {
2547 SetLastError(ERROR_MORE_DATA);
2548 *pdwDataLen = dwDataLen;
2549 return FALSE;
2552 pBlobHeader->bType = PRIVATEKEYBLOB;
2553 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2554 pBlobHeader->reserved = 0;
2555 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2557 pRSAPubKey->magic = RSAENH_MAGIC_RSA2;
2558 pRSAPubKey->bitlen = pCryptKey->dwKeyLen << 3;
2560 export_private_key_impl((BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2561 pCryptKey->dwKeyLen, &pRSAPubKey->pubexp);
2563 *pdwDataLen = dwDataLen;
2564 return TRUE;
2567 static BOOL crypt_export_plaintext_key(CRYPTKEY *pCryptKey, BYTE *pbData,
2568 DWORD *pdwDataLen)
2570 BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2571 DWORD *pKeyLen = (DWORD*)(pBlobHeader+1);
2572 BYTE *pbKey = (BYTE*)(pKeyLen+1);
2573 DWORD dwDataLen;
2575 dwDataLen = sizeof(BLOBHEADER) + sizeof(DWORD) + pCryptKey->dwKeyLen;
2576 if (pbData) {
2577 if (*pdwDataLen < dwDataLen) {
2578 SetLastError(ERROR_MORE_DATA);
2579 *pdwDataLen = dwDataLen;
2580 return FALSE;
2583 pBlobHeader->bType = PLAINTEXTKEYBLOB;
2584 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2585 pBlobHeader->reserved = 0;
2586 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2588 *pKeyLen = pCryptKey->dwKeyLen;
2589 memcpy(pbKey, pCryptKey->abKeyValue, pCryptKey->dwKeyLen);
2591 *pdwDataLen = dwDataLen;
2592 return TRUE;
2594 /******************************************************************************
2595 * crypt_export_key [Internal]
2597 * Export a key into a binary large object (BLOB). Called by CPExportKey and
2598 * by store_key_pair.
2600 * PARAMS
2601 * pCryptKey [I] Key to be exported.
2602 * hPubKey [I] Key used to encrypt sensitive BLOB data.
2603 * dwBlobType [I] SIMPLEBLOB, PUBLICKEYBLOB or PRIVATEKEYBLOB.
2604 * dwFlags [I] Currently none defined.
2605 * force [I] If TRUE, the key is written no matter what the key's
2606 * permissions are. Otherwise the key's permissions are
2607 * checked before exporting.
2608 * pbData [O] Pointer to a buffer where the BLOB will be written to.
2609 * pdwDataLen [I/O] I: Size of buffer at pbData, O: Size of BLOB
2611 * RETURNS
2612 * Success: TRUE.
2613 * Failure: FALSE.
2615 static BOOL crypt_export_key(CRYPTKEY *pCryptKey, HCRYPTKEY hPubKey,
2616 DWORD dwBlobType, DWORD dwFlags, BOOL force,
2617 BYTE *pbData, DWORD *pdwDataLen)
2619 CRYPTKEY *pPubKey;
2621 if (dwFlags & CRYPT_SSL2_FALLBACK) {
2622 if (pCryptKey->aiAlgid != CALG_SSL2_MASTER) {
2623 SetLastError(NTE_BAD_KEY);
2624 return FALSE;
2628 switch ((BYTE)dwBlobType)
2630 case SIMPLEBLOB:
2631 if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pPubKey)){
2632 SetLastError(NTE_BAD_PUBLIC_KEY); /* FIXME: error_code? */
2633 return FALSE;
2635 return crypt_export_simple(pCryptKey, pPubKey, dwFlags, pbData,
2636 pdwDataLen);
2638 case PUBLICKEYBLOB:
2639 if (is_valid_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY)) {
2640 SetLastError(NTE_BAD_KEY); /* FIXME: error code? */
2641 return FALSE;
2644 return crypt_export_public_key(pCryptKey, pbData, pdwDataLen);
2646 case PRIVATEKEYBLOB:
2647 return crypt_export_private_key(pCryptKey, force, pbData, pdwDataLen);
2649 case PLAINTEXTKEYBLOB:
2650 return crypt_export_plaintext_key(pCryptKey, pbData, pdwDataLen);
2652 default:
2653 SetLastError(NTE_BAD_TYPE); /* FIXME: error code? */
2654 return FALSE;
2658 /******************************************************************************
2659 * CPExportKey (RSAENH.@)
2661 * Export a key into a binary large object (BLOB).
2663 * PARAMS
2664 * hProv [I] Key container from which a key is to be exported.
2665 * hKey [I] Key to be exported.
2666 * hPubKey [I] Key used to encrypt sensitive BLOB data.
2667 * dwBlobType [I] SIMPLEBLOB, PUBLICKEYBLOB or PRIVATEKEYBLOB.
2668 * dwFlags [I] Currently none defined.
2669 * pbData [O] Pointer to a buffer where the BLOB will be written to.
2670 * pdwDataLen [I/O] I: Size of buffer at pbData, O: Size of BLOB
2672 * RETURNS
2673 * Success: TRUE.
2674 * Failure: FALSE.
2676 BOOL WINAPI RSAENH_CPExportKey(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTKEY hPubKey,
2677 DWORD dwBlobType, DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2679 CRYPTKEY *pCryptKey;
2681 TRACE("(hProv=%08lx, hKey=%08lx, hPubKey=%08lx, dwBlobType=%08x, dwFlags=%08x, pbData=%p,"
2682 "pdwDataLen=%p)\n", hProv, hKey, hPubKey, dwBlobType, dwFlags, pbData, pdwDataLen);
2684 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2686 SetLastError(NTE_BAD_UID);
2687 return FALSE;
2690 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2692 SetLastError(NTE_BAD_KEY);
2693 return FALSE;
2696 return crypt_export_key(pCryptKey, hPubKey, dwBlobType, dwFlags, FALSE,
2697 pbData, pdwDataLen);
2700 /******************************************************************************
2701 * release_and_install_key [Internal]
2703 * Release an existing key, if present, and replaces it with a new one.
2705 * PARAMS
2706 * hProv [I] Key container into which the key is to be imported.
2707 * src [I] Key which will replace *dest
2708 * dest [I] Points to key to be released and replaced with src
2709 * fStoreKey [I] If TRUE, the newly installed key is stored to the registry.
2711 static void release_and_install_key(HCRYPTPROV hProv, HCRYPTKEY src,
2712 HCRYPTKEY *dest, DWORD fStoreKey)
2714 RSAENH_CPDestroyKey(hProv, *dest);
2715 copy_handle(&handle_table, src, RSAENH_MAGIC_KEY, dest);
2716 if (fStoreKey)
2718 KEYCONTAINER *pKeyContainer;
2720 if ((pKeyContainer = get_key_container(hProv)))
2722 store_key_container_keys(pKeyContainer);
2723 store_key_container_permissions(pKeyContainer);
2728 /******************************************************************************
2729 * import_private_key [Internal]
2731 * Import a BLOB'ed private key into a key container.
2733 * PARAMS
2734 * hProv [I] Key container into which the private key is to be imported.
2735 * pbData [I] Pointer to a buffer which holds the private key BLOB.
2736 * dwDataLen [I] Length of data in buffer at pbData.
2737 * dwFlags [I] One of:
2738 * CRYPT_EXPORTABLE: the imported key is marked exportable
2739 * fStoreKey [I] If TRUE, the imported key is stored to the registry.
2740 * phKey [O] Handle to the imported key.
2743 * NOTES
2744 * Assumes the caller has already checked the BLOBHEADER at pbData to ensure
2745 * it's a PRIVATEKEYBLOB.
2747 * RETURNS
2748 * Success: TRUE.
2749 * Failure: FALSE.
2751 static BOOL import_private_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
2752 DWORD dwFlags, BOOL fStoreKey, HCRYPTKEY *phKey)
2754 KEYCONTAINER *pKeyContainer;
2755 CRYPTKEY *pCryptKey;
2756 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
2757 const RSAPUBKEY *pRSAPubKey = (const RSAPUBKEY*)(pBlobHeader+1);
2758 BOOL ret;
2760 if (dwFlags & CRYPT_IPSEC_HMAC_KEY)
2762 FIXME("unimplemented for CRYPT_IPSEC_HMAC_KEY\n");
2763 SetLastError(NTE_BAD_FLAGS);
2764 return FALSE;
2766 if (!(pKeyContainer = get_key_container(hProv)))
2767 return FALSE;
2769 if ((dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY)))
2771 ERR("datalen %d not long enough for a BLOBHEADER + RSAPUBKEY\n",
2772 dwDataLen);
2773 SetLastError(NTE_BAD_DATA);
2774 return FALSE;
2776 if (pRSAPubKey->magic != RSAENH_MAGIC_RSA2)
2778 ERR("unexpected magic %08x\n", pRSAPubKey->magic);
2779 SetLastError(NTE_BAD_DATA);
2780 return FALSE;
2782 if ((dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) +
2783 (pRSAPubKey->bitlen >> 3) + (5 * ((pRSAPubKey->bitlen+8)>>4))))
2785 DWORD expectedLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) +
2786 (pRSAPubKey->bitlen >> 3) + (5 * ((pRSAPubKey->bitlen+8)>>4));
2788 ERR("blob too short for pub key: expect %d, got %d\n",
2789 expectedLen, dwDataLen);
2790 SetLastError(NTE_BAD_DATA);
2791 return FALSE;
2794 *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, MAKELONG(0,pRSAPubKey->bitlen), &pCryptKey);
2795 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
2796 setup_key(pCryptKey);
2797 ret = import_private_key_impl((const BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2798 pRSAPubKey->bitlen/8, dwDataLen, pRSAPubKey->pubexp);
2799 if (ret) {
2800 if (dwFlags & CRYPT_EXPORTABLE)
2801 pCryptKey->dwPermissions |= CRYPT_EXPORT;
2802 switch (pBlobHeader->aiKeyAlg)
2804 case AT_SIGNATURE:
2805 case CALG_RSA_SIGN:
2806 TRACE("installing signing key\n");
2807 release_and_install_key(hProv, *phKey, &pKeyContainer->hSignatureKeyPair,
2808 fStoreKey);
2809 break;
2810 case AT_KEYEXCHANGE:
2811 case CALG_RSA_KEYX:
2812 TRACE("installing key exchange key\n");
2813 release_and_install_key(hProv, *phKey, &pKeyContainer->hKeyExchangeKeyPair,
2814 fStoreKey);
2815 break;
2818 return ret;
2821 /******************************************************************************
2822 * import_public_key [Internal]
2824 * Import a BLOB'ed public key.
2826 * PARAMS
2827 * hProv [I] A CSP.
2828 * pbData [I] Pointer to a buffer which holds the public key BLOB.
2829 * dwDataLen [I] Length of data in buffer at pbData.
2830 * dwFlags [I] One of:
2831 * CRYPT_EXPORTABLE: the imported key is marked exportable
2832 * phKey [O] Handle to the imported key.
2835 * NOTES
2836 * Assumes the caller has already checked the BLOBHEADER at pbData to ensure
2837 * it's a PUBLICKEYBLOB.
2839 * RETURNS
2840 * Success: TRUE.
2841 * Failure: FALSE.
2843 static BOOL import_public_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
2844 DWORD dwFlags, HCRYPTKEY *phKey)
2846 CRYPTKEY *pCryptKey;
2847 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
2848 const RSAPUBKEY *pRSAPubKey = (const RSAPUBKEY*)(pBlobHeader+1);
2849 ALG_ID algID;
2850 BOOL ret;
2852 if (dwFlags & CRYPT_IPSEC_HMAC_KEY)
2854 FIXME("unimplemented for CRYPT_IPSEC_HMAC_KEY\n");
2855 SetLastError(NTE_BAD_FLAGS);
2856 return FALSE;
2859 if ((dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY)) ||
2860 (pRSAPubKey->magic != RSAENH_MAGIC_RSA1) ||
2861 (dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) + (pRSAPubKey->bitlen >> 3)))
2863 SetLastError(NTE_BAD_DATA);
2864 return FALSE;
2867 /* Since this is a public key blob, only the public key is
2868 * available, so only signature verification is possible.
2870 algID = pBlobHeader->aiKeyAlg;
2871 *phKey = new_key(hProv, algID, MAKELONG(0,pRSAPubKey->bitlen), &pCryptKey);
2872 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
2873 setup_key(pCryptKey);
2874 ret = import_public_key_impl((const BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2875 pRSAPubKey->bitlen >> 3, pRSAPubKey->pubexp);
2876 if (ret) {
2877 if (dwFlags & CRYPT_EXPORTABLE)
2878 pCryptKey->dwPermissions |= CRYPT_EXPORT;
2880 return ret;
2883 /******************************************************************************
2884 * import_symmetric_key [Internal]
2886 * Import a BLOB'ed symmetric key into a key container.
2888 * PARAMS
2889 * hProv [I] Key container into which the symmetric key is to be imported.
2890 * pbData [I] Pointer to a buffer which holds the symmetric key BLOB.
2891 * dwDataLen [I] Length of data in buffer at pbData.
2892 * hPubKey [I] Key used to decrypt sensitive BLOB data.
2893 * dwFlags [I] One of:
2894 * CRYPT_EXPORTABLE: the imported key is marked exportable
2895 * phKey [O] Handle to the imported key.
2898 * NOTES
2899 * Assumes the caller has already checked the BLOBHEADER at pbData to ensure
2900 * it's a SIMPLEBLOB.
2902 * RETURNS
2903 * Success: TRUE.
2904 * Failure: FALSE.
2906 static BOOL import_symmetric_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
2907 HCRYPTKEY hPubKey, DWORD dwFlags, HCRYPTKEY *phKey)
2909 CRYPTKEY *pCryptKey, *pPubKey;
2910 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
2911 const ALG_ID *pAlgid = (const ALG_ID*)(pBlobHeader+1);
2912 const BYTE *pbKeyStream = (const BYTE*)(pAlgid + 1);
2913 BYTE *pbDecrypted;
2914 DWORD dwKeyLen;
2916 if (dwFlags & CRYPT_IPSEC_HMAC_KEY)
2918 FIXME("unimplemented for CRYPT_IPSEC_HMAC_KEY\n");
2919 SetLastError(NTE_BAD_FLAGS);
2920 return FALSE;
2922 if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pPubKey) ||
2923 pPubKey->aiAlgid != CALG_RSA_KEYX)
2925 SetLastError(NTE_BAD_PUBLIC_KEY); /* FIXME: error code? */
2926 return FALSE;
2929 if (dwDataLen < sizeof(BLOBHEADER)+sizeof(ALG_ID)+pPubKey->dwBlockLen)
2931 SetLastError(NTE_BAD_DATA); /* FIXME: error code */
2932 return FALSE;
2935 pbDecrypted = HeapAlloc(GetProcessHeap(), 0, pPubKey->dwBlockLen);
2936 if (!pbDecrypted) return FALSE;
2937 encrypt_block_impl(pPubKey->aiAlgid, PK_PRIVATE, &pPubKey->context, pbKeyStream, pbDecrypted,
2938 RSAENH_DECRYPT);
2940 dwKeyLen = RSAENH_MAX_KEY_SIZE;
2941 if (!unpad_data(pbDecrypted, pPubKey->dwBlockLen, pbDecrypted, &dwKeyLen, dwFlags)) {
2942 HeapFree(GetProcessHeap(), 0, pbDecrypted);
2943 return FALSE;
2946 *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, dwKeyLen<<19, &pCryptKey);
2947 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
2949 HeapFree(GetProcessHeap(), 0, pbDecrypted);
2950 return FALSE;
2952 memcpy(pCryptKey->abKeyValue, pbDecrypted, dwKeyLen);
2953 HeapFree(GetProcessHeap(), 0, pbDecrypted);
2954 setup_key(pCryptKey);
2955 if (dwFlags & CRYPT_EXPORTABLE)
2956 pCryptKey->dwPermissions |= CRYPT_EXPORT;
2957 return TRUE;
2960 /******************************************************************************
2961 * import_plaintext_key [Internal]
2963 * Import a plaintext key into a key container.
2965 * PARAMS
2966 * hProv [I] Key container into which the symmetric key is to be imported.
2967 * pbData [I] Pointer to a buffer which holds the plaintext key BLOB.
2968 * dwDataLen [I] Length of data in buffer at pbData.
2969 * dwFlags [I] One of:
2970 * CRYPT_EXPORTABLE: the imported key is marked exportable
2971 * phKey [O] Handle to the imported key.
2974 * NOTES
2975 * Assumes the caller has already checked the BLOBHEADER at pbData to ensure
2976 * it's a PLAINTEXTKEYBLOB.
2978 * RETURNS
2979 * Success: TRUE.
2980 * Failure: FALSE.
2982 static BOOL import_plaintext_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
2983 DWORD dwFlags, HCRYPTKEY *phKey)
2985 CRYPTKEY *pCryptKey;
2986 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
2987 const DWORD *pKeyLen = (const DWORD *)(pBlobHeader + 1);
2988 const BYTE *pbKeyStream = (const BYTE*)(pKeyLen + 1);
2990 if (dwDataLen < sizeof(BLOBHEADER)+sizeof(DWORD)+*pKeyLen)
2992 SetLastError(NTE_BAD_DATA); /* FIXME: error code */
2993 return FALSE;
2996 if (dwFlags & CRYPT_IPSEC_HMAC_KEY)
2998 *phKey = new_key(hProv, CALG_HMAC, 0, &pCryptKey);
2999 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
3000 return FALSE;
3001 if (*pKeyLen <= RSAENH_MIN(sizeof(pCryptKey->abKeyValue), RSAENH_HMAC_BLOCK_LEN))
3003 memcpy(pCryptKey->abKeyValue, pbKeyStream, *pKeyLen);
3004 pCryptKey->dwKeyLen = *pKeyLen;
3006 else
3008 CRYPT_DATA_BLOB blobHmacKey = { *pKeyLen, (BYTE *)pbKeyStream };
3010 /* In order to initialize an HMAC key, the key material is hashed,
3011 * and the output of the hash function is used as the key material.
3012 * Unfortunately, the way the Crypto API is designed, we don't know
3013 * the hash algorithm yet, so we have to copy the entire key
3014 * material.
3016 if (!copy_data_blob(&pCryptKey->blobHmacKey, &blobHmacKey))
3018 release_handle(&handle_table, *phKey, RSAENH_MAGIC_KEY);
3019 *phKey = (HCRYPTKEY)INVALID_HANDLE_VALUE;
3020 return FALSE;
3023 setup_key(pCryptKey);
3024 if (dwFlags & CRYPT_EXPORTABLE)
3025 pCryptKey->dwPermissions |= CRYPT_EXPORT;
3027 else
3029 *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, *pKeyLen<<19, &pCryptKey);
3030 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
3031 return FALSE;
3032 memcpy(pCryptKey->abKeyValue, pbKeyStream, *pKeyLen);
3033 setup_key(pCryptKey);
3034 if (dwFlags & CRYPT_EXPORTABLE)
3035 pCryptKey->dwPermissions |= CRYPT_EXPORT;
3037 return TRUE;
3040 /******************************************************************************
3041 * import_key [Internal]
3043 * Import a BLOB'ed key into a key container, optionally storing the key's
3044 * value to the registry.
3046 * PARAMS
3047 * hProv [I] Key container into which the key is to be imported.
3048 * pbData [I] Pointer to a buffer which holds the BLOB.
3049 * dwDataLen [I] Length of data in buffer at pbData.
3050 * hPubKey [I] Key used to decrypt sensitive BLOB data.
3051 * dwFlags [I] One of:
3052 * CRYPT_EXPORTABLE: the imported key is marked exportable
3053 * fStoreKey [I] If TRUE, the imported key is stored to the registry.
3054 * phKey [O] Handle to the imported key.
3056 * RETURNS
3057 * Success: TRUE.
3058 * Failure: FALSE.
3060 static BOOL import_key(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen, HCRYPTKEY hPubKey,
3061 DWORD dwFlags, BOOL fStoreKey, HCRYPTKEY *phKey)
3063 KEYCONTAINER *pKeyContainer;
3064 const BLOBHEADER *pBlobHeader = (const BLOBHEADER*)pbData;
3066 if (!(pKeyContainer = get_key_container(hProv)))
3067 return FALSE;
3069 if (dwDataLen < sizeof(BLOBHEADER) ||
3070 pBlobHeader->bVersion != CUR_BLOB_VERSION ||
3071 pBlobHeader->reserved != 0)
3073 TRACE("bVersion = %d, reserved = %d\n", pBlobHeader->bVersion,
3074 pBlobHeader->reserved);
3075 SetLastError(NTE_BAD_DATA);
3076 return FALSE;
3079 /* If this is a verify-only context, the key is not persisted regardless of
3080 * fStoreKey's original value.
3082 fStoreKey = fStoreKey && !(dwFlags & CRYPT_VERIFYCONTEXT);
3083 TRACE("blob type: %x\n", pBlobHeader->bType);
3084 switch (pBlobHeader->bType)
3086 case PRIVATEKEYBLOB:
3087 return import_private_key(hProv, pbData, dwDataLen, dwFlags,
3088 fStoreKey, phKey);
3090 case PUBLICKEYBLOB:
3091 return import_public_key(hProv, pbData, dwDataLen, dwFlags,
3092 phKey);
3094 case SIMPLEBLOB:
3095 return import_symmetric_key(hProv, pbData, dwDataLen, hPubKey,
3096 dwFlags, phKey);
3098 case PLAINTEXTKEYBLOB:
3099 return import_plaintext_key(hProv, pbData, dwDataLen, dwFlags,
3100 phKey);
3102 default:
3103 SetLastError(NTE_BAD_TYPE); /* FIXME: error code? */
3104 return FALSE;
3108 /******************************************************************************
3109 * CPImportKey (RSAENH.@)
3111 * Import a BLOB'ed key into a key container.
3113 * PARAMS
3114 * hProv [I] Key container into which the key is to be imported.
3115 * pbData [I] Pointer to a buffer which holds the BLOB.
3116 * dwDataLen [I] Length of data in buffer at pbData.
3117 * hPubKey [I] Key used to decrypt sensitive BLOB data.
3118 * dwFlags [I] One of:
3119 * CRYPT_EXPORTABLE: the imported key is marked exportable
3120 * phKey [O] Handle to the imported key.
3122 * RETURNS
3123 * Success: TRUE.
3124 * Failure: FALSE.
3126 BOOL WINAPI RSAENH_CPImportKey(HCRYPTPROV hProv, const BYTE *pbData, DWORD dwDataLen,
3127 HCRYPTKEY hPubKey, DWORD dwFlags, HCRYPTKEY *phKey)
3129 TRACE("(hProv=%08lx, pbData=%p, dwDataLen=%d, hPubKey=%08lx, dwFlags=%08x, phKey=%p)\n",
3130 hProv, pbData, dwDataLen, hPubKey, dwFlags, phKey);
3132 return import_key(hProv, pbData, dwDataLen, hPubKey, dwFlags, TRUE, phKey);
3135 /******************************************************************************
3136 * CPGenKey (RSAENH.@)
3138 * Generate a key in the key container
3140 * PARAMS
3141 * hProv [I] Key container for which a key is to be generated.
3142 * Algid [I] Crypto algorithm identifier for the key to be generated.
3143 * dwFlags [I] Upper 16 bits: Binary length of key. Lower 16 bits: Flags. See Notes
3144 * phKey [O] Handle to the generated key.
3146 * RETURNS
3147 * Success: TRUE.
3148 * Failure: FALSE.
3150 * FIXME
3151 * Flags currently not considered.
3153 * NOTES
3154 * Private key-exchange- and signature-keys can be generated with Algid AT_KEYEXCHANGE
3155 * and AT_SIGNATURE values.
3157 BOOL WINAPI RSAENH_CPGenKey(HCRYPTPROV hProv, ALG_ID Algid, DWORD dwFlags, HCRYPTKEY *phKey)
3159 KEYCONTAINER *pKeyContainer;
3160 CRYPTKEY *pCryptKey;
3162 TRACE("(hProv=%08lx, aiAlgid=%d, dwFlags=%08x, phKey=%p)\n", hProv, Algid, dwFlags, phKey);
3164 if (!(pKeyContainer = get_key_container(hProv)))
3166 /* MSDN: hProv not containing valid context handle */
3167 return FALSE;
3170 switch (Algid)
3172 case AT_SIGNATURE:
3173 case CALG_RSA_SIGN:
3174 *phKey = new_key(hProv, CALG_RSA_SIGN, dwFlags, &pCryptKey);
3175 if (pCryptKey) {
3176 new_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen);
3177 setup_key(pCryptKey);
3178 release_and_install_key(hProv, *phKey,
3179 &pKeyContainer->hSignatureKeyPair,
3180 FALSE);
3182 break;
3184 case AT_KEYEXCHANGE:
3185 case CALG_RSA_KEYX:
3186 *phKey = new_key(hProv, CALG_RSA_KEYX, dwFlags, &pCryptKey);
3187 if (pCryptKey) {
3188 new_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen);
3189 setup_key(pCryptKey);
3190 release_and_install_key(hProv, *phKey,
3191 &pKeyContainer->hKeyExchangeKeyPair,
3192 FALSE);
3194 break;
3196 case CALG_RC2:
3197 case CALG_RC4:
3198 case CALG_DES:
3199 case CALG_3DES_112:
3200 case CALG_3DES:
3201 case CALG_AES:
3202 case CALG_AES_128:
3203 case CALG_AES_192:
3204 case CALG_AES_256:
3205 case CALG_PCT1_MASTER:
3206 case CALG_SSL2_MASTER:
3207 case CALG_SSL3_MASTER:
3208 case CALG_TLS1_MASTER:
3209 *phKey = new_key(hProv, Algid, dwFlags, &pCryptKey);
3210 if (pCryptKey) {
3211 gen_rand_impl(pCryptKey->abKeyValue, RSAENH_MAX_KEY_SIZE);
3212 switch (Algid) {
3213 case CALG_SSL3_MASTER:
3214 pCryptKey->abKeyValue[0] = RSAENH_SSL3_VERSION_MAJOR;
3215 pCryptKey->abKeyValue[1] = RSAENH_SSL3_VERSION_MINOR;
3216 break;
3218 case CALG_TLS1_MASTER:
3219 pCryptKey->abKeyValue[0] = RSAENH_TLS1_VERSION_MAJOR;
3220 pCryptKey->abKeyValue[1] = RSAENH_TLS1_VERSION_MINOR;
3221 break;
3223 setup_key(pCryptKey);
3225 break;
3227 default:
3228 /* MSDN: Algorithm not supported specified by Algid */
3229 SetLastError(NTE_BAD_ALGID);
3230 return FALSE;
3233 return *phKey != (HCRYPTKEY)INVALID_HANDLE_VALUE;
3236 /******************************************************************************
3237 * CPGenRandom (RSAENH.@)
3239 * Generate a random byte stream.
3241 * PARAMS
3242 * hProv [I] Key container that is used to generate random bytes.
3243 * dwLen [I] Specifies the number of requested random data bytes.
3244 * pbBuffer [O] Random bytes will be stored here.
3246 * RETURNS
3247 * Success: TRUE
3248 * Failure: FALSE
3250 BOOL WINAPI RSAENH_CPGenRandom(HCRYPTPROV hProv, DWORD dwLen, BYTE *pbBuffer)
3252 TRACE("(hProv=%08lx, dwLen=%d, pbBuffer=%p)\n", hProv, dwLen, pbBuffer);
3254 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3256 /* MSDN: hProv not containing valid context handle */
3257 SetLastError(NTE_BAD_UID);
3258 return FALSE;
3261 return gen_rand_impl(pbBuffer, dwLen);
3264 /******************************************************************************
3265 * CPGetHashParam (RSAENH.@)
3267 * Query parameters of an hash object.
3269 * PARAMS
3270 * hProv [I] The kea container, which the hash belongs to.
3271 * hHash [I] The hash object that is to be queried.
3272 * dwParam [I] Specifies the parameter that is to be queried.
3273 * pbData [I] Pointer to the buffer where the parameter value will be stored.
3274 * pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
3275 * dwFlags [I] None currently defined.
3277 * RETURNS
3278 * Success: TRUE
3279 * Failure: FALSE
3281 * NOTES
3282 * Valid dwParams are: HP_ALGID, HP_HASHSIZE, HP_HASHVALUE. The hash will be
3283 * finalized if HP_HASHVALUE is queried.
3285 BOOL WINAPI RSAENH_CPGetHashParam(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwParam, BYTE *pbData,
3286 DWORD *pdwDataLen, DWORD dwFlags)
3288 CRYPTHASH *pCryptHash;
3290 TRACE("(hProv=%08lx, hHash=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p, dwFlags=%08x)\n",
3291 hProv, hHash, dwParam, pbData, pdwDataLen, dwFlags);
3293 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3295 SetLastError(NTE_BAD_UID);
3296 return FALSE;
3299 if (dwFlags)
3301 SetLastError(NTE_BAD_FLAGS);
3302 return FALSE;
3305 if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH,
3306 (OBJECTHDR**)&pCryptHash))
3308 SetLastError(NTE_BAD_HASH);
3309 return FALSE;
3312 if (!pdwDataLen)
3314 SetLastError(ERROR_INVALID_PARAMETER);
3315 return FALSE;
3318 switch (dwParam)
3320 case HP_ALGID:
3321 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptHash->aiAlgid,
3322 sizeof(ALG_ID));
3324 case HP_HASHSIZE:
3325 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptHash->dwHashSize,
3326 sizeof(DWORD));
3328 case HP_HASHVAL:
3329 if (pCryptHash->aiAlgid == CALG_TLS1PRF) {
3330 return tls1_prf(hProv, pCryptHash->hKey, &pCryptHash->tpPRFParams.blobLabel,
3331 &pCryptHash->tpPRFParams.blobSeed, pbData, *pdwDataLen);
3334 if ( pbData == NULL ) {
3335 *pdwDataLen = pCryptHash->dwHashSize;
3336 return TRUE;
3339 if (pbData && (pCryptHash->dwState != RSAENH_HASHSTATE_FINISHED))
3341 finalize_hash(pCryptHash);
3342 pCryptHash->dwState = RSAENH_HASHSTATE_FINISHED;
3345 return copy_param(pbData, pdwDataLen, pCryptHash->abHashValue,
3346 pCryptHash->dwHashSize);
3348 default:
3349 SetLastError(NTE_BAD_TYPE);
3350 return FALSE;
3354 /******************************************************************************
3355 * CPSetKeyParam (RSAENH.@)
3357 * Set a parameter of a key object
3359 * PARAMS
3360 * hProv [I] The key container to which the key belongs.
3361 * hKey [I] The key for which a parameter is to be set.
3362 * dwParam [I] Parameter type. See Notes.
3363 * pbData [I] Pointer to the parameter value.
3364 * dwFlags [I] Currently none defined.
3366 * RETURNS
3367 * Success: TRUE.
3368 * Failure: FALSE.
3370 * NOTES:
3371 * Defined dwParam types are:
3372 * - KP_MODE: Values MODE_CBC, MODE_ECB, MODE_CFB.
3373 * - KP_MODE_BITS: Shift width for cipher feedback mode. (Currently ignored by MS CSP's)
3374 * - KP_PERMISSIONS: Or'ed combination of CRYPT_ENCRYPT, CRYPT_DECRYPT,
3375 * CRYPT_EXPORT, CRYPT_READ, CRYPT_WRITE, CRYPT_MAC
3376 * - KP_IV: Initialization vector
3378 BOOL WINAPI RSAENH_CPSetKeyParam(HCRYPTPROV hProv, HCRYPTKEY hKey, DWORD dwParam, BYTE *pbData,
3379 DWORD dwFlags)
3381 CRYPTKEY *pCryptKey;
3383 TRACE("(hProv=%08lx, hKey=%08lx, dwParam=%08x, pbData=%p, dwFlags=%08x)\n", hProv, hKey,
3384 dwParam, pbData, dwFlags);
3386 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3388 SetLastError(NTE_BAD_UID);
3389 return FALSE;
3392 if (dwFlags) {
3393 SetLastError(NTE_BAD_FLAGS);
3394 return FALSE;
3397 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
3399 SetLastError(NTE_BAD_KEY);
3400 return FALSE;
3403 switch (dwParam) {
3404 case KP_PADDING:
3405 /* The MS providers only support PKCS5_PADDING */
3406 if (*(DWORD *)pbData != PKCS5_PADDING) {
3407 SetLastError(NTE_BAD_DATA);
3408 return FALSE;
3410 return TRUE;
3412 case KP_MODE:
3413 pCryptKey->dwMode = *(DWORD*)pbData;
3414 return TRUE;
3416 case KP_MODE_BITS:
3417 pCryptKey->dwModeBits = *(DWORD*)pbData;
3418 return TRUE;
3420 case KP_PERMISSIONS:
3422 DWORD perms = *(DWORD *)pbData;
3424 if ((perms & CRYPT_EXPORT) &&
3425 !(pCryptKey->dwPermissions & CRYPT_EXPORT))
3427 SetLastError(NTE_BAD_DATA);
3428 return FALSE;
3430 else if (!(perms & CRYPT_EXPORT) &&
3431 (pCryptKey->dwPermissions & CRYPT_EXPORT))
3433 /* Clearing the export permission appears to be ignored,
3434 * see tests.
3436 perms |= CRYPT_EXPORT;
3438 pCryptKey->dwPermissions = perms;
3439 return TRUE;
3442 case KP_IV:
3443 memcpy(pCryptKey->abInitVector, pbData, pCryptKey->dwBlockLen);
3444 setup_key(pCryptKey);
3445 return TRUE;
3447 case KP_SALT:
3448 switch (pCryptKey->aiAlgid) {
3449 case CALG_RC2:
3450 case CALG_RC4:
3452 KEYCONTAINER *pKeyContainer = get_key_container(pCryptKey->hProv);
3453 if (!pbData)
3455 SetLastError(ERROR_INVALID_PARAMETER);
3456 return FALSE;
3458 /* MSDN: the base provider always sets eleven bytes of
3459 * salt value.
3461 memcpy(pCryptKey->abKeyValue + pCryptKey->dwKeyLen,
3462 pbData, 11);
3463 pCryptKey->dwSaltLen = 11;
3464 setup_key(pCryptKey);
3465 /* After setting the salt value if the provider is not base or
3466 * strong the salt length will be reset. */
3467 if (pKeyContainer->dwPersonality != RSAENH_PERSONALITY_BASE &&
3468 pKeyContainer->dwPersonality != RSAENH_PERSONALITY_STRONG)
3469 pCryptKey->dwSaltLen = 0;
3470 break;
3472 default:
3473 SetLastError(NTE_BAD_KEY);
3474 return FALSE;
3476 return TRUE;
3478 case KP_SALT_EX:
3480 CRYPT_INTEGER_BLOB *blob = (CRYPT_INTEGER_BLOB *)pbData;
3482 /* salt length can't be greater than 184 bits = 24 bytes */
3483 if (blob->cbData > 24)
3485 SetLastError(NTE_BAD_DATA);
3486 return FALSE;
3488 memcpy(pCryptKey->abKeyValue + pCryptKey->dwKeyLen, blob->pbData,
3489 blob->cbData);
3490 pCryptKey->dwSaltLen = blob->cbData;
3491 setup_key(pCryptKey);
3492 return TRUE;
3495 case KP_EFFECTIVE_KEYLEN:
3496 switch (pCryptKey->aiAlgid) {
3497 case CALG_RC2:
3499 DWORD keylen, deflen;
3500 BOOL ret = TRUE;
3501 KEYCONTAINER *pKeyContainer = get_key_container(pCryptKey->hProv);
3503 if (!pbData)
3505 SetLastError(ERROR_INVALID_PARAMETER);
3506 return FALSE;
3508 keylen = *(DWORD *)pbData;
3509 if (!keylen || keylen > 1024)
3511 SetLastError(NTE_BAD_DATA);
3512 return FALSE;
3516 * The Base provider will force the key length to default
3517 * and set an error state if a key length different from
3518 * the default is tried.
3520 deflen = aProvEnumAlgsEx[pKeyContainer->dwPersonality]->dwDefaultLen;
3521 if (pKeyContainer->dwPersonality == RSAENH_PERSONALITY_BASE
3522 && keylen != deflen)
3524 keylen = deflen;
3525 SetLastError(NTE_BAD_DATA);
3526 ret = FALSE;
3528 pCryptKey->dwEffectiveKeyLen = keylen;
3529 setup_key(pCryptKey);
3530 return ret;
3532 default:
3533 SetLastError(NTE_BAD_TYPE);
3534 return FALSE;
3536 return TRUE;
3538 case KP_SCHANNEL_ALG:
3539 switch (((PSCHANNEL_ALG)pbData)->dwUse) {
3540 case SCHANNEL_ENC_KEY:
3541 memcpy(&pCryptKey->siSChannelInfo.saEncAlg, pbData, sizeof(SCHANNEL_ALG));
3542 break;
3544 case SCHANNEL_MAC_KEY:
3545 memcpy(&pCryptKey->siSChannelInfo.saMACAlg, pbData, sizeof(SCHANNEL_ALG));
3546 break;
3548 default:
3549 SetLastError(NTE_FAIL); /* FIXME: error code */
3550 return FALSE;
3552 return TRUE;
3554 case KP_CLIENT_RANDOM:
3555 return copy_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom, (PCRYPT_DATA_BLOB)pbData);
3557 case KP_SERVER_RANDOM:
3558 return copy_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom, (PCRYPT_DATA_BLOB)pbData);
3560 default:
3561 SetLastError(NTE_BAD_TYPE);
3562 return FALSE;
3566 /******************************************************************************
3567 * CPGetKeyParam (RSAENH.@)
3569 * Query a key parameter.
3571 * PARAMS
3572 * hProv [I] The key container, which the key belongs to.
3573 * hHash [I] The key object that is to be queried.
3574 * dwParam [I] Specifies the parameter that is to be queried.
3575 * pbData [I] Pointer to the buffer where the parameter value will be stored.
3576 * pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
3577 * dwFlags [I] None currently defined.
3579 * RETURNS
3580 * Success: TRUE
3581 * Failure: FALSE
3583 * NOTES
3584 * Defined dwParam types are:
3585 * - KP_MODE: Values MODE_CBC, MODE_ECB, MODE_CFB.
3586 * - KP_MODE_BITS: Shift width for cipher feedback mode.
3587 * (Currently ignored by MS CSP's - always eight)
3588 * - KP_PERMISSIONS: Or'ed combination of CRYPT_ENCRYPT, CRYPT_DECRYPT,
3589 * CRYPT_EXPORT, CRYPT_READ, CRYPT_WRITE, CRYPT_MAC
3590 * - KP_IV: Initialization vector.
3591 * - KP_KEYLEN: Bitwidth of the key.
3592 * - KP_BLOCKLEN: Size of a block cipher block.
3593 * - KP_SALT: Salt value.
3595 BOOL WINAPI RSAENH_CPGetKeyParam(HCRYPTPROV hProv, HCRYPTKEY hKey, DWORD dwParam, BYTE *pbData,
3596 DWORD *pdwDataLen, DWORD dwFlags)
3598 CRYPTKEY *pCryptKey;
3599 DWORD dwValue;
3601 TRACE("(hProv=%08lx, hKey=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p dwFlags=%08x)\n",
3602 hProv, hKey, dwParam, pbData, pdwDataLen, dwFlags);
3604 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3606 SetLastError(NTE_BAD_UID);
3607 return FALSE;
3610 if (dwFlags) {
3611 SetLastError(NTE_BAD_FLAGS);
3612 return FALSE;
3615 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
3617 SetLastError(NTE_BAD_KEY);
3618 return FALSE;
3621 switch (dwParam)
3623 case KP_IV:
3624 return copy_param(pbData, pdwDataLen, pCryptKey->abInitVector,
3625 pCryptKey->dwBlockLen);
3627 case KP_SALT:
3628 switch (pCryptKey->aiAlgid) {
3629 case CALG_RC2:
3630 case CALG_RC4:
3631 return copy_param(pbData, pdwDataLen,
3632 &pCryptKey->abKeyValue[pCryptKey->dwKeyLen],
3633 pCryptKey->dwSaltLen);
3634 default:
3635 SetLastError(NTE_BAD_KEY);
3636 return FALSE;
3639 case KP_PADDING:
3640 dwValue = PKCS5_PADDING;
3641 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwValue, sizeof(DWORD));
3643 case KP_KEYLEN:
3644 dwValue = pCryptKey->dwKeyLen << 3;
3645 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwValue, sizeof(DWORD));
3647 case KP_EFFECTIVE_KEYLEN:
3648 if (pCryptKey->dwEffectiveKeyLen)
3649 dwValue = pCryptKey->dwEffectiveKeyLen;
3650 else
3651 dwValue = pCryptKey->dwKeyLen << 3;
3652 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwValue, sizeof(DWORD));
3654 case KP_BLOCKLEN:
3655 dwValue = pCryptKey->dwBlockLen << 3;
3656 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwValue, sizeof(DWORD));
3658 case KP_MODE:
3659 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptKey->dwMode, sizeof(DWORD));
3661 case KP_MODE_BITS:
3662 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptKey->dwModeBits,
3663 sizeof(DWORD));
3665 case KP_PERMISSIONS:
3666 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptKey->dwPermissions,
3667 sizeof(DWORD));
3669 case KP_ALGID:
3670 return copy_param(pbData, pdwDataLen, (const BYTE*)&pCryptKey->aiAlgid, sizeof(DWORD));
3672 default:
3673 SetLastError(NTE_BAD_TYPE);
3674 return FALSE;
3678 /******************************************************************************
3679 * CPGetProvParam (RSAENH.@)
3681 * Query a CSP parameter.
3683 * PARAMS
3684 * hProv [I] The key container that is to be queried.
3685 * dwParam [I] Specifies the parameter that is to be queried.
3686 * pbData [I] Pointer to the buffer where the parameter value will be stored.
3687 * pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
3688 * dwFlags [I] CRYPT_FIRST: Start enumeration (for PP_ENUMALGS{_EX}).
3690 * RETURNS
3691 * Success: TRUE
3692 * Failure: FALSE
3693 * NOTES:
3694 * Defined dwParam types:
3695 * - PP_CONTAINER: Name of the key container.
3696 * - PP_NAME: Name of the cryptographic service provider.
3697 * - PP_SIG_KEYSIZE_INC: RSA signature keywidth granularity in bits.
3698 * - PP_KEYX_KEYSIZE_INC: RSA key-exchange keywidth granularity in bits.
3699 * - PP_ENUMALGS{_EX}: Query provider capabilities.
3700 * - PP_KEYSET_SEC_DESCR: Retrieve security descriptor on container.
3702 BOOL WINAPI RSAENH_CPGetProvParam(HCRYPTPROV hProv, DWORD dwParam, BYTE *pbData,
3703 DWORD *pdwDataLen, DWORD dwFlags)
3705 KEYCONTAINER *pKeyContainer;
3706 PROV_ENUMALGS provEnumalgs;
3707 DWORD dwTemp;
3708 HKEY hKey;
3710 /* This is for dwParam PP_CRYPT_COUNT_KEY_USE.
3711 * IE6 SP1 asks for it in the 'About' dialog.
3712 * Returning this BLOB seems to satisfy IE. The marked 0x00 seem
3713 * to be 'don't care's. If you know anything more specific about
3714 * this provider parameter, please report to wine-devel@winehq.org */
3715 static const BYTE abWTF[96] = {
3716 0xb0, 0x25, 0x63, 0x86, 0x9c, 0xab, 0xb6, 0x37,
3717 0xe8, 0x82, /**/0x00,/**/ 0x72, 0x06, 0xb2, /**/0x00,/**/ 0x3b,
3718 0x60, 0x35, /**/0x00,/**/ 0x3b, 0x88, 0xce, /**/0x00,/**/ 0x82,
3719 0xbc, 0x7a, /**/0x00,/**/ 0xb7, 0x4f, 0x7e, /**/0x00,/**/ 0xde,
3720 0x92, 0xf1, /**/0x00,/**/ 0x83, 0xea, 0x5e, /**/0x00,/**/ 0xc8,
3721 0x12, 0x1e, 0xd4, 0x06, 0xf7, 0x66, /**/0x00,/**/ 0x01,
3722 0x29, 0xa4, /**/0x00,/**/ 0xf8, 0x24, 0x0c, /**/0x00,/**/ 0x33,
3723 0x06, 0x80, /**/0x00,/**/ 0x02, 0x46, 0x0b, /**/0x00,/**/ 0x6d,
3724 0x5b, 0xca, /**/0x00,/**/ 0x9a, 0x10, 0xf0, /**/0x00,/**/ 0x05,
3725 0x19, 0xd0, /**/0x00,/**/ 0x2c, 0xf6, 0x27, /**/0x00,/**/ 0xaa,
3726 0x7c, 0x6f, /**/0x00,/**/ 0xb9, 0xd8, 0x72, /**/0x00,/**/ 0x03,
3727 0xf3, 0x81, /**/0x00,/**/ 0xfa, 0xe8, 0x26, /**/0x00,/**/ 0xca
3730 TRACE("(hProv=%08lx, dwParam=%08x, pbData=%p, pdwDataLen=%p, dwFlags=%08x)\n",
3731 hProv, dwParam, pbData, pdwDataLen, dwFlags);
3733 if (!pdwDataLen) {
3734 SetLastError(ERROR_INVALID_PARAMETER);
3735 return FALSE;
3738 if (!(pKeyContainer = get_key_container(hProv)))
3740 /* MSDN: hProv not containing valid context handle */
3741 return FALSE;
3744 switch (dwParam)
3746 case PP_CONTAINER:
3747 case PP_UNIQUE_CONTAINER:/* MSDN says we can return the same value as PP_CONTAINER */
3748 return copy_param(pbData, pdwDataLen, (const BYTE*)pKeyContainer->szName,
3749 strlen(pKeyContainer->szName)+1);
3751 case PP_NAME:
3752 return copy_param(pbData, pdwDataLen, (const BYTE*)pKeyContainer->szProvName,
3753 strlen(pKeyContainer->szProvName)+1);
3755 case PP_PROVTYPE:
3756 dwTemp = PROV_RSA_FULL;
3757 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
3759 case PP_KEYSPEC:
3760 dwTemp = AT_SIGNATURE | AT_KEYEXCHANGE;
3761 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
3763 case PP_KEYSET_TYPE:
3764 dwTemp = pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET;
3765 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
3767 case PP_KEYSTORAGE:
3768 dwTemp = CRYPT_SEC_DESCR;
3769 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
3771 case PP_SIG_KEYSIZE_INC:
3772 case PP_KEYX_KEYSIZE_INC:
3773 dwTemp = 8;
3774 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
3776 case PP_IMPTYPE:
3777 dwTemp = CRYPT_IMPL_SOFTWARE;
3778 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
3780 case PP_VERSION:
3781 dwTemp = 0x00000200;
3782 return copy_param(pbData, pdwDataLen, (const BYTE*)&dwTemp, sizeof(dwTemp));
3784 case PP_ENUMCONTAINERS:
3785 if ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) pKeyContainer->dwEnumContainersCtr = 0;
3787 if (!pbData) {
3788 *pdwDataLen = (DWORD)MAX_PATH + 1;
3789 return TRUE;
3792 if (!open_container_key("", dwFlags, KEY_READ, &hKey))
3794 SetLastError(ERROR_NO_MORE_ITEMS);
3795 return FALSE;
3798 dwTemp = *pdwDataLen;
3799 switch (RegEnumKeyExA(hKey, pKeyContainer->dwEnumContainersCtr, (LPSTR)pbData, &dwTemp,
3800 NULL, NULL, NULL, NULL))
3802 case ERROR_MORE_DATA:
3803 *pdwDataLen = (DWORD)MAX_PATH + 1;
3805 case ERROR_SUCCESS:
3806 pKeyContainer->dwEnumContainersCtr++;
3807 RegCloseKey(hKey);
3808 return TRUE;
3810 case ERROR_NO_MORE_ITEMS:
3811 default:
3812 SetLastError(ERROR_NO_MORE_ITEMS);
3813 RegCloseKey(hKey);
3814 return FALSE;
3817 case PP_ENUMALGS:
3818 case PP_ENUMALGS_EX:
3819 if (((pKeyContainer->dwEnumAlgsCtr >= RSAENH_MAX_ENUMALGS-1) ||
3820 (!aProvEnumAlgsEx[pKeyContainer->dwPersonality]
3821 [pKeyContainer->dwEnumAlgsCtr+1].aiAlgid)) &&
3822 ((dwFlags & CRYPT_FIRST) != CRYPT_FIRST))
3824 SetLastError(ERROR_NO_MORE_ITEMS);
3825 return FALSE;
3828 if (dwParam == PP_ENUMALGS) {
3829 if (pbData && (*pdwDataLen >= sizeof(PROV_ENUMALGS)))
3830 pKeyContainer->dwEnumAlgsCtr = ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) ?
3831 0 : pKeyContainer->dwEnumAlgsCtr+1;
3833 provEnumalgs.aiAlgid = aProvEnumAlgsEx
3834 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].aiAlgid;
3835 provEnumalgs.dwBitLen = aProvEnumAlgsEx
3836 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].dwDefaultLen;
3837 provEnumalgs.dwNameLen = aProvEnumAlgsEx
3838 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].dwNameLen;
3839 memcpy(provEnumalgs.szName, aProvEnumAlgsEx
3840 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].szName,
3841 20*sizeof(CHAR));
3843 return copy_param(pbData, pdwDataLen, (const BYTE*)&provEnumalgs,
3844 sizeof(PROV_ENUMALGS));
3845 } else {
3846 if (pbData && (*pdwDataLen >= sizeof(PROV_ENUMALGS_EX)))
3847 pKeyContainer->dwEnumAlgsCtr = ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) ?
3848 0 : pKeyContainer->dwEnumAlgsCtr+1;
3850 return copy_param(pbData, pdwDataLen,
3851 (const BYTE*)&aProvEnumAlgsEx
3852 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr],
3853 sizeof(PROV_ENUMALGS_EX));
3856 case PP_CRYPT_COUNT_KEY_USE: /* Asked for by IE About dialog */
3857 return copy_param(pbData, pdwDataLen, abWTF, sizeof(abWTF));
3859 case PP_KEYSET_SEC_DESCR:
3861 SECURITY_DESCRIPTOR *sd;
3862 DWORD err, len, flags = (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET);
3864 if (!open_container_key(pKeyContainer->szName, flags, KEY_READ, &hKey))
3866 SetLastError(NTE_BAD_KEYSET);
3867 return FALSE;
3870 err = GetSecurityInfo(hKey, SE_REGISTRY_KEY, dwFlags, NULL, NULL, NULL, NULL, (void **)&sd);
3871 RegCloseKey(hKey);
3872 if (err)
3874 SetLastError(err);
3875 return FALSE;
3878 len = GetSecurityDescriptorLength(sd);
3879 if (*pdwDataLen >= len) memcpy(pbData, sd, len);
3880 else SetLastError(ERROR_INSUFFICIENT_BUFFER);
3881 *pdwDataLen = len;
3883 LocalFree(sd);
3884 return TRUE;
3887 default:
3888 /* MSDN: Unknown parameter number in dwParam */
3889 SetLastError(NTE_BAD_TYPE);
3890 return FALSE;
3894 /******************************************************************************
3895 * CPDeriveKey (RSAENH.@)
3897 * Derives a key from a hash value.
3899 * PARAMS
3900 * hProv [I] Key container for which a key is to be generated.
3901 * Algid [I] Crypto algorithm identifier for the key to be generated.
3902 * hBaseData [I] Hash from whose value the key will be derived.
3903 * dwFlags [I] See Notes.
3904 * phKey [O] The generated key.
3906 * RETURNS
3907 * Success: TRUE
3908 * Failure: FALSE
3910 * NOTES
3911 * Defined flags:
3912 * - CRYPT_EXPORTABLE: Key can be exported.
3913 * - CRYPT_NO_SALT: No salt is used for 40 bit keys.
3914 * - CRYPT_CREATE_SALT: Use remaining bits as salt value.
3916 BOOL WINAPI RSAENH_CPDeriveKey(HCRYPTPROV hProv, ALG_ID Algid, HCRYPTHASH hBaseData,
3917 DWORD dwFlags, HCRYPTKEY *phKey)
3919 CRYPTKEY *pCryptKey, *pMasterKey;
3920 CRYPTHASH *pCryptHash;
3921 BYTE abHashValue[RSAENH_MAX_HASH_SIZE*2];
3922 DWORD dwLen;
3924 TRACE("(hProv=%08lx, Algid=%d, hBaseData=%08lx, dwFlags=%08x phKey=%p)\n", hProv, Algid,
3925 hBaseData, dwFlags, phKey);
3927 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3929 SetLastError(NTE_BAD_UID);
3930 return FALSE;
3933 if (!lookup_handle(&handle_table, hBaseData, RSAENH_MAGIC_HASH,
3934 (OBJECTHDR**)&pCryptHash))
3936 SetLastError(NTE_BAD_HASH);
3937 return FALSE;
3940 if (!phKey)
3942 SetLastError(ERROR_INVALID_PARAMETER);
3943 return FALSE;
3946 switch (GET_ALG_CLASS(Algid))
3948 case ALG_CLASS_DATA_ENCRYPT:
3950 int need_padding, copy_len;
3951 *phKey = new_key(hProv, Algid, dwFlags, &pCryptKey);
3952 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
3955 * We derive the key material from the hash.
3956 * If the hash value is not large enough for the claimed key, we have to construct
3957 * a larger binary value based on the hash. This is documented in MSDN: CryptDeriveKey.
3959 dwLen = RSAENH_MAX_HASH_SIZE;
3960 RSAENH_CPGetHashParam(pCryptHash->hProv, hBaseData, HP_HASHVAL, abHashValue, &dwLen, 0);
3963 * The usage of padding seems to vary from algorithm to algorithm.
3964 * For now the only different case found was for AES with 128 bit key.
3966 switch(Algid)
3968 case CALG_AES_128:
3969 /* To reduce the chance of regressions we will only deviate
3970 * from the old behavior for the tested hash lengths */
3971 if (dwLen == 16 || dwLen == 20)
3973 need_padding = 1;
3974 break;
3976 default:
3977 need_padding = dwLen < pCryptKey->dwKeyLen;
3980 copy_len = pCryptKey->dwKeyLen;
3981 if (need_padding)
3983 BYTE pad1[RSAENH_HMAC_DEF_PAD_LEN], pad2[RSAENH_HMAC_DEF_PAD_LEN];
3984 BYTE old_hashval[RSAENH_MAX_HASH_SIZE];
3985 DWORD i;
3987 memcpy(old_hashval, pCryptHash->abHashValue, RSAENH_MAX_HASH_SIZE);
3989 for (i=0; i<RSAENH_HMAC_DEF_PAD_LEN; i++) {
3990 pad1[i] = RSAENH_HMAC_DEF_IPAD_CHAR ^ (i<dwLen ? abHashValue[i] : 0);
3991 pad2[i] = RSAENH_HMAC_DEF_OPAD_CHAR ^ (i<dwLen ? abHashValue[i] : 0);
3994 init_hash(pCryptHash);
3995 update_hash(pCryptHash, pad1, RSAENH_HMAC_DEF_PAD_LEN);
3996 finalize_hash(pCryptHash);
3997 memcpy(abHashValue, pCryptHash->abHashValue, pCryptHash->dwHashSize);
3999 init_hash(pCryptHash);
4000 update_hash(pCryptHash, pad2, RSAENH_HMAC_DEF_PAD_LEN);
4001 finalize_hash(pCryptHash);
4002 memcpy(abHashValue+pCryptHash->dwHashSize, pCryptHash->abHashValue,
4003 pCryptHash->dwHashSize);
4005 memcpy(pCryptHash->abHashValue, old_hashval, RSAENH_MAX_HASH_SIZE);
4008 * Padding was not required, we have more hash than needed.
4009 * Do we need to use the remaining hash as salt?
4011 else if((dwFlags & CRYPT_CREATE_SALT) &&
4012 (Algid == CALG_RC2 || Algid == CALG_RC4))
4014 copy_len += pCryptKey->dwSaltLen;
4017 memcpy(pCryptKey->abKeyValue, abHashValue,
4018 RSAENH_MIN(copy_len, sizeof(pCryptKey->abKeyValue)));
4019 break;
4021 case ALG_CLASS_MSG_ENCRYPT:
4022 if (!lookup_handle(&handle_table, pCryptHash->hKey, RSAENH_MAGIC_KEY,
4023 (OBJECTHDR**)&pMasterKey))
4025 SetLastError(NTE_FAIL); /* FIXME error code */
4026 return FALSE;
4029 switch (Algid)
4031 /* See RFC 2246, chapter 6.3 Key calculation */
4032 case CALG_SCHANNEL_ENC_KEY:
4033 if (!pMasterKey->siSChannelInfo.saEncAlg.Algid ||
4034 !pMasterKey->siSChannelInfo.saEncAlg.cBits)
4036 SetLastError(NTE_BAD_FLAGS);
4037 return FALSE;
4039 *phKey = new_key(hProv, pMasterKey->siSChannelInfo.saEncAlg.Algid,
4040 MAKELONG(LOWORD(dwFlags),pMasterKey->siSChannelInfo.saEncAlg.cBits),
4041 &pCryptKey);
4042 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
4043 memcpy(pCryptKey->abKeyValue,
4044 pCryptHash->abHashValue + (
4045 2 * (pMasterKey->siSChannelInfo.saMACAlg.cBits / 8) +
4046 ((dwFlags & CRYPT_SERVER) ?
4047 (pMasterKey->siSChannelInfo.saEncAlg.cBits / 8) : 0)),
4048 pMasterKey->siSChannelInfo.saEncAlg.cBits / 8);
4049 memcpy(pCryptKey->abInitVector,
4050 pCryptHash->abHashValue + (
4051 2 * (pMasterKey->siSChannelInfo.saMACAlg.cBits / 8) +
4052 2 * (pMasterKey->siSChannelInfo.saEncAlg.cBits / 8) +
4053 ((dwFlags & CRYPT_SERVER) ? pCryptKey->dwBlockLen : 0)),
4054 pCryptKey->dwBlockLen);
4055 break;
4057 case CALG_SCHANNEL_MAC_KEY:
4058 *phKey = new_key(hProv, Algid,
4059 MAKELONG(LOWORD(dwFlags),pMasterKey->siSChannelInfo.saMACAlg.cBits),
4060 &pCryptKey);
4061 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
4062 memcpy(pCryptKey->abKeyValue,
4063 pCryptHash->abHashValue + ((dwFlags & CRYPT_SERVER) ?
4064 pMasterKey->siSChannelInfo.saMACAlg.cBits / 8 : 0),
4065 pMasterKey->siSChannelInfo.saMACAlg.cBits / 8);
4066 break;
4068 default:
4069 SetLastError(NTE_BAD_ALGID);
4070 return FALSE;
4072 break;
4074 default:
4075 SetLastError(NTE_BAD_ALGID);
4076 return FALSE;
4079 setup_key(pCryptKey);
4080 return TRUE;
4083 /******************************************************************************
4084 * CPGetUserKey (RSAENH.@)
4086 * Returns a handle to the user's private key-exchange- or signature-key.
4088 * PARAMS
4089 * hProv [I] The key container from which a user key is requested.
4090 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
4091 * phUserKey [O] Handle to the requested key or INVALID_HANDLE_VALUE in case of failure.
4093 * RETURNS
4094 * Success: TRUE.
4095 * Failure: FALSE.
4097 * NOTE
4098 * A newly created key container does not contain private user key. Create them with CPGenKey.
4100 BOOL WINAPI RSAENH_CPGetUserKey(HCRYPTPROV hProv, DWORD dwKeySpec, HCRYPTKEY *phUserKey)
4102 KEYCONTAINER *pKeyContainer;
4104 TRACE("(hProv=%08lx, dwKeySpec=%08x, phUserKey=%p)\n", hProv, dwKeySpec, phUserKey);
4106 if (!(pKeyContainer = get_key_container(hProv)))
4108 /* MSDN: hProv not containing valid context handle */
4109 return FALSE;
4112 switch (dwKeySpec)
4114 case AT_KEYEXCHANGE:
4115 copy_handle(&handle_table, pKeyContainer->hKeyExchangeKeyPair, RSAENH_MAGIC_KEY,
4116 phUserKey);
4117 break;
4119 case AT_SIGNATURE:
4120 copy_handle(&handle_table, pKeyContainer->hSignatureKeyPair, RSAENH_MAGIC_KEY,
4121 phUserKey);
4122 break;
4124 default:
4125 *phUserKey = (HCRYPTKEY)INVALID_HANDLE_VALUE;
4128 if (*phUserKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
4130 /* MSDN: dwKeySpec parameter specifies nonexistent key */
4131 SetLastError(NTE_NO_KEY);
4132 return FALSE;
4135 return TRUE;
4138 /******************************************************************************
4139 * CPHashData (RSAENH.@)
4141 * Updates a hash object with the given data.
4143 * PARAMS
4144 * hProv [I] Key container to which the hash object belongs.
4145 * hHash [I] Hash object which is to be updated.
4146 * pbData [I] Pointer to data with which the hash object is to be updated.
4147 * dwDataLen [I] Length of the data.
4148 * dwFlags [I] Currently none defined.
4150 * RETURNS
4151 * Success: TRUE.
4152 * Failure: FALSE.
4154 * NOTES
4155 * The actual hash value is queried with CPGetHashParam, which will finalize
4156 * the hash. Updating a finalized hash will fail with a last error NTE_BAD_HASH_STATE.
4158 BOOL WINAPI RSAENH_CPHashData(HCRYPTPROV hProv, HCRYPTHASH hHash, const BYTE *pbData,
4159 DWORD dwDataLen, DWORD dwFlags)
4161 CRYPTHASH *pCryptHash;
4163 TRACE("(hProv=%08lx, hHash=%08lx, pbData=%p, dwDataLen=%d, dwFlags=%08x)\n",
4164 hProv, hHash, pbData, dwDataLen, dwFlags);
4166 if (dwFlags & ~CRYPT_USERDATA)
4168 SetLastError(NTE_BAD_FLAGS);
4169 return FALSE;
4172 if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH,
4173 (OBJECTHDR**)&pCryptHash))
4175 SetLastError(NTE_BAD_HASH);
4176 return FALSE;
4179 if (!get_algid_info(hProv, pCryptHash->aiAlgid) || pCryptHash->aiAlgid == CALG_SSL3_SHAMD5)
4181 SetLastError(NTE_BAD_ALGID);
4182 return FALSE;
4185 if (pCryptHash->dwState != RSAENH_HASHSTATE_HASHING)
4187 SetLastError(NTE_BAD_HASH_STATE);
4188 return FALSE;
4191 update_hash(pCryptHash, pbData, dwDataLen);
4192 return TRUE;
4195 /******************************************************************************
4196 * CPHashSessionKey (RSAENH.@)
4198 * Updates a hash object with the binary representation of a symmetric key.
4200 * PARAMS
4201 * hProv [I] Key container to which the hash object belongs.
4202 * hHash [I] Hash object which is to be updated.
4203 * hKey [I] The symmetric key, whose binary value will be added to the hash.
4204 * dwFlags [I] CRYPT_LITTLE_ENDIAN, if the binary key value shall be interpreted as little endian.
4206 * RETURNS
4207 * Success: TRUE.
4208 * Failure: FALSE.
4210 BOOL WINAPI RSAENH_CPHashSessionKey(HCRYPTPROV hProv, HCRYPTHASH hHash, HCRYPTKEY hKey,
4211 DWORD dwFlags)
4213 BYTE abKeyValue[RSAENH_MAX_KEY_SIZE], bTemp;
4214 CRYPTKEY *pKey;
4215 DWORD i;
4217 TRACE("(hProv=%08lx, hHash=%08lx, hKey=%08lx, dwFlags=%08x)\n", hProv, hHash, hKey, dwFlags);
4219 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pKey) ||
4220 (GET_ALG_CLASS(pKey->aiAlgid) != ALG_CLASS_DATA_ENCRYPT))
4222 SetLastError(NTE_BAD_KEY);
4223 return FALSE;
4226 if (dwFlags & ~CRYPT_LITTLE_ENDIAN) {
4227 SetLastError(NTE_BAD_FLAGS);
4228 return FALSE;
4231 memcpy(abKeyValue, pKey->abKeyValue, pKey->dwKeyLen);
4232 if (!(dwFlags & CRYPT_LITTLE_ENDIAN)) {
4233 for (i=0; i<pKey->dwKeyLen/2; i++) {
4234 bTemp = abKeyValue[i];
4235 abKeyValue[i] = abKeyValue[pKey->dwKeyLen-i-1];
4236 abKeyValue[pKey->dwKeyLen-i-1] = bTemp;
4240 return RSAENH_CPHashData(hProv, hHash, abKeyValue, pKey->dwKeyLen, 0);
4243 /******************************************************************************
4244 * CPReleaseContext (RSAENH.@)
4246 * Release a key container.
4248 * PARAMS
4249 * hProv [I] Key container to be released.
4250 * dwFlags [I] Currently none defined.
4252 * RETURNS
4253 * Success: TRUE
4254 * Failure: FALSE
4256 BOOL WINAPI RSAENH_CPReleaseContext(HCRYPTPROV hProv, DWORD dwFlags)
4258 TRACE("(hProv=%08lx, dwFlags=%08x)\n", hProv, dwFlags);
4260 if (!release_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
4262 /* MSDN: hProv not containing valid context handle */
4263 SetLastError(NTE_BAD_UID);
4264 return FALSE;
4267 if (dwFlags) {
4268 SetLastError(NTE_BAD_FLAGS);
4269 return FALSE;
4272 return TRUE;
4275 /******************************************************************************
4276 * CPSetHashParam (RSAENH.@)
4278 * Set a parameter of a hash object
4280 * PARAMS
4281 * hProv [I] The key container to which the key belongs.
4282 * hHash [I] The hash object for which a parameter is to be set.
4283 * dwParam [I] Parameter type. See Notes.
4284 * pbData [I] Pointer to the parameter value.
4285 * dwFlags [I] Currently none defined.
4287 * RETURNS
4288 * Success: TRUE.
4289 * Failure: FALSE.
4291 * NOTES
4292 * Currently only the HP_HMAC_INFO dwParam type is defined.
4293 * The HMAC_INFO struct will be deep copied into the hash object.
4294 * See Internet RFC 2104 for details on the HMAC algorithm.
4296 BOOL WINAPI RSAENH_CPSetHashParam(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwParam,
4297 BYTE *pbData, DWORD dwFlags)
4299 CRYPTHASH *pCryptHash;
4300 CRYPTKEY *pCryptKey;
4301 DWORD i;
4303 TRACE("(hProv=%08lx, hHash=%08lx, dwParam=%08x, pbData=%p, dwFlags=%08x)\n",
4304 hProv, hHash, dwParam, pbData, dwFlags);
4306 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
4308 SetLastError(NTE_BAD_UID);
4309 return FALSE;
4312 if (dwFlags) {
4313 SetLastError(NTE_BAD_FLAGS);
4314 return FALSE;
4317 if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH,
4318 (OBJECTHDR**)&pCryptHash))
4320 SetLastError(NTE_BAD_HASH);
4321 return FALSE;
4324 switch (dwParam) {
4325 case HP_HMAC_INFO:
4326 free_hmac_info(pCryptHash->pHMACInfo);
4327 if (!copy_hmac_info(&pCryptHash->pHMACInfo, (PHMAC_INFO)pbData)) return FALSE;
4329 if (!lookup_handle(&handle_table, pCryptHash->hKey, RSAENH_MAGIC_KEY,
4330 (OBJECTHDR**)&pCryptKey))
4332 SetLastError(NTE_FAIL); /* FIXME: correct error code? */
4333 return FALSE;
4336 if (pCryptKey->aiAlgid == CALG_HMAC && !pCryptKey->dwKeyLen) {
4337 HCRYPTHASH hKeyHash;
4338 DWORD keyLen;
4340 if (!RSAENH_CPCreateHash(hProv, ((PHMAC_INFO)pbData)->HashAlgid, 0, 0,
4341 &hKeyHash))
4342 return FALSE;
4343 if (!RSAENH_CPHashData(hProv, hKeyHash, pCryptKey->blobHmacKey.pbData,
4344 pCryptKey->blobHmacKey.cbData, 0))
4346 RSAENH_CPDestroyHash(hProv, hKeyHash);
4347 return FALSE;
4349 keyLen = sizeof(pCryptKey->abKeyValue);
4350 if (!RSAENH_CPGetHashParam(hProv, hKeyHash, HP_HASHVAL, pCryptKey->abKeyValue,
4351 &keyLen, 0))
4353 RSAENH_CPDestroyHash(hProv, hKeyHash);
4354 return FALSE;
4356 pCryptKey->dwKeyLen = keyLen;
4357 RSAENH_CPDestroyHash(hProv, hKeyHash);
4359 for (i=0; i<RSAENH_MIN(pCryptKey->dwKeyLen,pCryptHash->pHMACInfo->cbInnerString); i++) {
4360 pCryptHash->pHMACInfo->pbInnerString[i] ^= pCryptKey->abKeyValue[i];
4362 for (i=0; i<RSAENH_MIN(pCryptKey->dwKeyLen,pCryptHash->pHMACInfo->cbOuterString); i++) {
4363 pCryptHash->pHMACInfo->pbOuterString[i] ^= pCryptKey->abKeyValue[i];
4366 init_hash(pCryptHash);
4367 return TRUE;
4369 case HP_HASHVAL:
4370 memcpy(pCryptHash->abHashValue, pbData, pCryptHash->dwHashSize);
4371 pCryptHash->dwState = RSAENH_HASHSTATE_FINISHED;
4372 return TRUE;
4374 case HP_TLS1PRF_SEED:
4375 return copy_data_blob(&pCryptHash->tpPRFParams.blobSeed, (PCRYPT_DATA_BLOB)pbData);
4377 case HP_TLS1PRF_LABEL:
4378 return copy_data_blob(&pCryptHash->tpPRFParams.blobLabel, (PCRYPT_DATA_BLOB)pbData);
4380 default:
4381 SetLastError(NTE_BAD_TYPE);
4382 return FALSE;
4386 /******************************************************************************
4387 * CPSetProvParam (RSAENH.@)
4389 BOOL WINAPI RSAENH_CPSetProvParam(HCRYPTPROV hProv, DWORD dwParam, BYTE *pbData, DWORD dwFlags)
4391 KEYCONTAINER *pKeyContainer;
4392 HKEY hKey;
4394 TRACE("(hProv=%08lx, dwParam=%08x, pbData=%p, dwFlags=%08x)\n", hProv, dwParam, pbData, dwFlags);
4396 if (!(pKeyContainer = get_key_container(hProv)))
4397 return FALSE;
4399 switch (dwParam)
4401 case PP_KEYSET_SEC_DESCR:
4403 SECURITY_DESCRIPTOR *sd = (SECURITY_DESCRIPTOR *)pbData;
4404 DWORD err, flags = (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET);
4405 BOOL def, present;
4406 REGSAM access = WRITE_DAC | WRITE_OWNER | ACCESS_SYSTEM_SECURITY;
4407 PSID owner = NULL, group = NULL;
4408 PACL dacl = NULL, sacl = NULL;
4410 if (!open_container_key(pKeyContainer->szName, flags, access, &hKey))
4412 SetLastError(NTE_BAD_KEYSET);
4413 return FALSE;
4416 if ((dwFlags & OWNER_SECURITY_INFORMATION && !GetSecurityDescriptorOwner(sd, &owner, &def)) ||
4417 (dwFlags & GROUP_SECURITY_INFORMATION && !GetSecurityDescriptorGroup(sd, &group, &def)) ||
4418 (dwFlags & DACL_SECURITY_INFORMATION && !GetSecurityDescriptorDacl(sd, &present, &dacl, &def)) ||
4419 (dwFlags & SACL_SECURITY_INFORMATION && !GetSecurityDescriptorSacl(sd, &present, &sacl, &def)))
4421 RegCloseKey(hKey);
4422 return FALSE;
4425 err = SetSecurityInfo(hKey, SE_REGISTRY_KEY, dwFlags, owner, group, dacl, sacl);
4426 RegCloseKey(hKey);
4427 if (err)
4429 SetLastError(err);
4430 return FALSE;
4432 return TRUE;
4434 default:
4435 FIXME("unimplemented parameter %08x\n", dwParam);
4436 return FALSE;
4440 /******************************************************************************
4441 * CPSignHash (RSAENH.@)
4443 * Sign a hash object
4445 * PARAMS
4446 * hProv [I] The key container, to which the hash object belongs.
4447 * hHash [I] The hash object to be signed.
4448 * dwKeySpec [I] AT_SIGNATURE or AT_KEYEXCHANGE: Key used to generate the signature.
4449 * sDescription [I] Should be NULL for security reasons.
4450 * dwFlags [I] 0, CRYPT_NOHASHOID or CRYPT_X931_FORMAT: Format of the signature.
4451 * pbSignature [O] Buffer, to which the signature will be stored. May be NULL to query SigLen.
4452 * pdwSigLen [I/O] Size of the buffer (in), Length of the signature (out)
4454 * RETURNS
4455 * Success: TRUE
4456 * Failure: FALSE
4458 BOOL WINAPI RSAENH_CPSignHash(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwKeySpec,
4459 LPCWSTR sDescription, DWORD dwFlags, BYTE *pbSignature,
4460 DWORD *pdwSigLen)
4462 HCRYPTKEY hCryptKey = (HCRYPTKEY)INVALID_HANDLE_VALUE;
4463 CRYPTKEY *pCryptKey;
4464 DWORD dwHashLen;
4465 BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
4466 ALG_ID aiAlgid;
4467 BOOL ret = FALSE;
4469 TRACE("(hProv=%08lx, hHash=%08lx, dwKeySpec=%08x, sDescription=%s, dwFlags=%08x, "
4470 "pbSignature=%p, pdwSigLen=%p)\n", hProv, hHash, dwKeySpec, debugstr_w(sDescription),
4471 dwFlags, pbSignature, pdwSigLen);
4473 if (dwFlags & ~(CRYPT_NOHASHOID|CRYPT_X931_FORMAT)) {
4474 SetLastError(NTE_BAD_FLAGS);
4475 return FALSE;
4478 if (!RSAENH_CPGetUserKey(hProv, dwKeySpec, &hCryptKey)) return FALSE;
4480 if (!lookup_handle(&handle_table, hCryptKey, RSAENH_MAGIC_KEY,
4481 (OBJECTHDR**)&pCryptKey))
4483 SetLastError(NTE_NO_KEY);
4484 goto out;
4487 if (!pbSignature) {
4488 *pdwSigLen = pCryptKey->dwKeyLen;
4489 ret = TRUE;
4490 goto out;
4492 if (pCryptKey->dwKeyLen > *pdwSigLen)
4494 SetLastError(ERROR_MORE_DATA);
4495 *pdwSigLen = pCryptKey->dwKeyLen;
4496 goto out;
4498 *pdwSigLen = pCryptKey->dwKeyLen;
4500 if (sDescription) {
4501 if (!RSAENH_CPHashData(hProv, hHash, (const BYTE*)sDescription,
4502 (DWORD)lstrlenW(sDescription)*sizeof(WCHAR), 0))
4504 goto out;
4508 dwHashLen = sizeof(DWORD);
4509 if (!RSAENH_CPGetHashParam(hProv, hHash, HP_ALGID, (BYTE*)&aiAlgid, &dwHashLen, 0)) goto out;
4511 dwHashLen = RSAENH_MAX_HASH_SIZE;
4512 if (!RSAENH_CPGetHashParam(hProv, hHash, HP_HASHVAL, abHashValue, &dwHashLen, 0)) goto out;
4515 if (!build_hash_signature(pbSignature, *pdwSigLen, aiAlgid, abHashValue, dwHashLen, dwFlags)) {
4516 goto out;
4519 ret = encrypt_block_impl(pCryptKey->aiAlgid, PK_PRIVATE, &pCryptKey->context, pbSignature, pbSignature, RSAENH_ENCRYPT);
4520 out:
4521 RSAENH_CPDestroyKey(hProv, hCryptKey);
4522 return ret;
4525 /******************************************************************************
4526 * CPVerifySignature (RSAENH.@)
4528 * Verify the signature of a hash object.
4530 * PARAMS
4531 * hProv [I] The key container, to which the hash belongs.
4532 * hHash [I] The hash for which the signature is verified.
4533 * pbSignature [I] The binary signature.
4534 * dwSigLen [I] Length of the signature BLOB.
4535 * hPubKey [I] Public key used to verify the signature.
4536 * sDescription [I] Should be NULL for security reasons.
4537 * dwFlags [I] 0, CRYPT_NOHASHOID or CRYPT_X931_FORMAT: Format of the signature.
4539 * RETURNS
4540 * Success: TRUE (Signature is valid)
4541 * Failure: FALSE (GetLastError() == NTE_BAD_SIGNATURE, if signature is invalid)
4543 BOOL WINAPI RSAENH_CPVerifySignature(HCRYPTPROV hProv, HCRYPTHASH hHash, const BYTE *pbSignature,
4544 DWORD dwSigLen, HCRYPTKEY hPubKey, LPCWSTR sDescription,
4545 DWORD dwFlags)
4547 BYTE *pbConstructed = NULL, *pbDecrypted = NULL;
4548 CRYPTKEY *pCryptKey;
4549 DWORD dwHashLen;
4550 ALG_ID aiAlgid;
4551 BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
4552 BOOL res = FALSE;
4554 TRACE("(hProv=%08lx, hHash=%08lx, pbSignature=%p, dwSigLen=%d, hPubKey=%08lx, sDescription=%s, "
4555 "dwFlags=%08x)\n", hProv, hHash, pbSignature, dwSigLen, hPubKey, debugstr_w(sDescription),
4556 dwFlags);
4558 if (dwFlags & ~(CRYPT_NOHASHOID|CRYPT_X931_FORMAT)) {
4559 SetLastError(NTE_BAD_FLAGS);
4560 return FALSE;
4563 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
4565 SetLastError(NTE_BAD_UID);
4566 return FALSE;
4569 if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY,
4570 (OBJECTHDR**)&pCryptKey))
4572 SetLastError(NTE_BAD_KEY);
4573 return FALSE;
4576 /* in Microsoft implementation, the signature length is checked before
4577 * the signature pointer.
4579 if (dwSigLen != pCryptKey->dwKeyLen)
4581 SetLastError(NTE_BAD_SIGNATURE);
4582 return FALSE;
4585 if (!hHash || !pbSignature)
4587 SetLastError(ERROR_INVALID_PARAMETER);
4588 return FALSE;
4591 if (sDescription) {
4592 if (!RSAENH_CPHashData(hProv, hHash, (const BYTE*)sDescription,
4593 (DWORD)lstrlenW(sDescription)*sizeof(WCHAR), 0))
4595 return FALSE;
4599 dwHashLen = sizeof(DWORD);
4600 if (!RSAENH_CPGetHashParam(hProv, hHash, HP_ALGID, (BYTE*)&aiAlgid, &dwHashLen, 0)) return FALSE;
4602 dwHashLen = RSAENH_MAX_HASH_SIZE;
4603 if (!RSAENH_CPGetHashParam(hProv, hHash, HP_HASHVAL, abHashValue, &dwHashLen, 0)) return FALSE;
4605 pbConstructed = HeapAlloc(GetProcessHeap(), 0, dwSigLen);
4606 if (!pbConstructed) {
4607 SetLastError(NTE_NO_MEMORY);
4608 goto cleanup;
4611 pbDecrypted = HeapAlloc(GetProcessHeap(), 0, dwSigLen);
4612 if (!pbDecrypted) {
4613 SetLastError(NTE_NO_MEMORY);
4614 goto cleanup;
4617 if (!encrypt_block_impl(pCryptKey->aiAlgid, PK_PUBLIC, &pCryptKey->context, pbSignature, pbDecrypted,
4618 RSAENH_DECRYPT))
4620 goto cleanup;
4623 if (build_hash_signature(pbConstructed, dwSigLen, aiAlgid, abHashValue, dwHashLen, dwFlags) &&
4624 !memcmp(pbDecrypted, pbConstructed, dwSigLen)) {
4625 res = TRUE;
4626 goto cleanup;
4629 if (!(dwFlags & CRYPT_NOHASHOID) &&
4630 build_hash_signature(pbConstructed, dwSigLen, aiAlgid, abHashValue, dwHashLen, dwFlags|CRYPT_NOHASHOID) &&
4631 !memcmp(pbDecrypted, pbConstructed, dwSigLen)) {
4632 res = TRUE;
4633 goto cleanup;
4636 SetLastError(NTE_BAD_SIGNATURE);
4638 cleanup:
4639 HeapFree(GetProcessHeap(), 0, pbConstructed);
4640 HeapFree(GetProcessHeap(), 0, pbDecrypted);
4641 return res;
4644 /******************************************************************************
4645 * DllRegisterServer (RSAENH.@)
4647 HRESULT WINAPI DllRegisterServer(void)
4649 return __wine_register_resources( instance );
4652 /******************************************************************************
4653 * DllUnregisterServer (RSAENH.@)
4655 HRESULT WINAPI DllUnregisterServer(void)
4657 return __wine_unregister_resources( instance );