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
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 #include "wine/port.h"
26 #include "wine/library.h"
27 #include "wine/debug.h"
40 WINE_DEFAULT_DEBUG_CHANNEL(crypt);
42 /******************************************************************************
43 * CRYPTHASH - hash objects
45 #define RSAENH_MAGIC_HASH 0x85938417u
46 #define RSAENH_MAX_HASH_SIZE 104
47 #define RSAENH_HASHSTATE_IDLE 0
48 #define RSAENH_HASHSTATE_HASHING 1
49 #define RSAENH_HASHSTATE_FINISHED 2
50 typedef struct _RSAENH_TLS1PRF_PARAMS
52 CRYPT_DATA_BLOB blobLabel;
53 CRYPT_DATA_BLOB blobSeed;
54 } RSAENH_TLS1PRF_PARAMS;
56 typedef struct tagCRYPTHASH
65 BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
67 RSAENH_TLS1PRF_PARAMS tpPRFParams;
70 /******************************************************************************
71 * CRYPTKEY - key objects
73 #define RSAENH_MAGIC_KEY 0x73620457u
74 #define RSAENH_MAX_KEY_SIZE 48
75 #define RSAENH_MAX_BLOCK_SIZE 24
76 #define RSAENH_KEYSTATE_IDLE 0
77 #define RSAENH_KEYSTATE_ENCRYPTING 1
78 #define RSAENH_KEYSTATE_DECRYPTING 2
79 #define RSAENH_KEYSTATE_MASTERKEY 3
80 typedef struct _RSAENH_SCHANNEL_INFO
82 SCHANNEL_ALG saEncAlg;
83 SCHANNEL_ALG saMACAlg;
84 CRYPT_DATA_BLOB blobClientRandom;
85 CRYPT_DATA_BLOB blobServerRandom;
86 } RSAENH_SCHANNEL_INFO;
88 typedef struct tagCRYPTKEY
101 BYTE abKeyValue[RSAENH_MAX_KEY_SIZE];
102 BYTE abInitVector[RSAENH_MAX_BLOCK_SIZE];
103 BYTE abChainVector[RSAENH_MAX_BLOCK_SIZE];
104 RSAENH_SCHANNEL_INFO siSChannelInfo;
107 /******************************************************************************
108 * KEYCONTAINER - key containers
110 #define RSAENH_PERSONALITY_BASE 0u
111 #define RSAENH_PERSONALITY_STRONG 1u
112 #define RSAENH_PERSONALITY_ENHANCED 2u
113 #define RSAENH_PERSONALITY_SCHANNEL 3u
115 #define RSAENH_MAGIC_CONTAINER 0x26384993u
116 typedef struct tagKEYCONTAINER
122 DWORD dwEnumContainersCtr;
123 CHAR szName[MAX_PATH];
124 CHAR szProvName[MAX_PATH];
125 HCRYPTKEY hKeyExchangeKeyPair;
126 HCRYPTKEY hSignatureKeyPair;
129 /******************************************************************************
130 * Some magic constants
132 #define RSAENH_ENCRYPT 1
133 #define RSAENH_DECRYPT 0
134 #define RSAENH_HMAC_DEF_IPAD_CHAR 0x36
135 #define RSAENH_HMAC_DEF_OPAD_CHAR 0x5c
136 #define RSAENH_HMAC_DEF_PAD_LEN 64
137 #define RSAENH_DES_EFFECTIVE_KEYLEN 56
138 #define RSAENH_DES_STORAGE_KEYLEN 64
139 #define RSAENH_3DES112_EFFECTIVE_KEYLEN 112
140 #define RSAENH_3DES112_STORAGE_KEYLEN 128
141 #define RSAENH_3DES_EFFECTIVE_KEYLEN 168
142 #define RSAENH_3DES_STORAGE_KEYLEN 192
143 #define RSAENH_MAGIC_RSA2 0x32415352
144 #define RSAENH_MAGIC_RSA1 0x31415352
145 #define RSAENH_PKC_BLOCKTYPE 0x02
146 #define RSAENH_SSL3_VERSION_MAJOR 3
147 #define RSAENH_SSL3_VERSION_MINOR 0
148 #define RSAENH_TLS1_VERSION_MAJOR 3
149 #define RSAENH_TLS1_VERSION_MINOR 1
150 #define RSAENH_REGKEY "Software\\Wine\\Crypto\\RSA\\%s"
152 #define RSAENH_MIN(a,b) ((a)<(b)?(a):(b))
153 /******************************************************************************
154 * aProvEnumAlgsEx - Defines the capabilities of the CSP personalities.
156 #define RSAENH_MAX_ENUMALGS 20
157 #define RSAENH_PCT1_SSL2_SSL3_TLS1 (CRYPT_FLAG_PCT1|CRYPT_FLAG_SSL2|CRYPT_FLAG_SSL3|CRYPT_FLAG_TLS1)
158 PROV_ENUMALGS_EX aProvEnumAlgsEx[4][RSAENH_MAX_ENUMALGS+1] =
161 {CALG_RC2, 40, 40, 56,0, 4,"RC2", 24,"RSA Data Security's RC2"},
162 {CALG_RC4, 40, 40, 56,0, 4,"RC4", 24,"RSA Data Security's RC4"},
163 {CALG_DES, 56, 56, 56,0, 4,"DES", 31,"Data Encryption Standard (DES)"},
164 {CALG_SHA, 160,160, 160,CRYPT_FLAG_SIGNING, 6,"SHA-1", 30,"Secure Hash Algorithm (SHA-1)"},
165 {CALG_MD2, 128,128, 128,CRYPT_FLAG_SIGNING, 4,"MD2", 23,"Message Digest 2 (MD2)"},
166 {CALG_MD4, 128,128, 128,CRYPT_FLAG_SIGNING, 4,"MD4", 23,"Message Digest 4 (MD4)"},
167 {CALG_MD5, 128,128, 128,CRYPT_FLAG_SIGNING, 4,"MD5", 23,"Message Digest 5 (MD5)"},
168 {CALG_SSL3_SHAMD5,288,288,288,0, 12,"SSL3 SHAMD5",12,"SSL3 SHAMD5"},
169 {CALG_MAC, 0, 0, 0,0, 4,"MAC", 28,"Message Authentication Code"},
170 {CALG_RSA_SIGN, 512,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_SIGN",14,"RSA Signature"},
171 {CALG_RSA_KEYX, 512,384, 1024,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_KEYX",17,"RSA Key Exchange"},
172 {CALG_HMAC, 0, 0, 0,0, 5,"HMAC", 18,"Hugo's MAC (HMAC)"},
173 {0, 0, 0, 0,0, 1,"", 1,""}
176 {CALG_RC2, 128, 40, 128,0, 4,"RC2", 24,"RSA Data Security's RC2"},
177 {CALG_RC4, 128, 40, 128,0, 4,"RC4", 24,"RSA Data Security's RC4"},
178 {CALG_DES, 56, 56, 56,0, 4,"DES", 31,"Data Encryption Standard (DES)"},
179 {CALG_3DES_112, 112,112, 112,0, 13,"3DES TWO KEY",19,"Two Key Triple DES"},
180 {CALG_3DES, 168,168, 168,0, 5,"3DES", 21,"Three Key Triple DES"},
181 {CALG_SHA, 160,160, 160,CRYPT_FLAG_SIGNING, 6,"SHA-1", 30,"Secure Hash Algorithm (SHA-1)"},
182 {CALG_MD2, 128,128, 128,CRYPT_FLAG_SIGNING, 4,"MD2", 23,"Message Digest 2 (MD2)"},
183 {CALG_MD4, 128,128, 128,CRYPT_FLAG_SIGNING, 4,"MD4", 23,"Message Digest 4 (MD4)"},
184 {CALG_MD5, 128,128, 128,CRYPT_FLAG_SIGNING, 4,"MD5", 23,"Message Digest 5 (MD5)"},
185 {CALG_SSL3_SHAMD5,288,288,288,0, 12,"SSL3 SHAMD5",12,"SSL3 SHAMD5"},
186 {CALG_MAC, 0, 0, 0,0, 4,"MAC", 28,"Message Authentication Code"},
187 {CALG_RSA_SIGN,1024,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_SIGN",14,"RSA Signature"},
188 {CALG_RSA_KEYX,1024,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_KEYX",17,"RSA Key Exchange"},
189 {CALG_HMAC, 0, 0, 0,0, 5,"HMAC", 18,"Hugo's MAC (HMAC)"},
190 {0, 0, 0, 0,0, 1,"", 1,""}
193 {CALG_RC2, 128, 40, 128,0, 4,"RC2", 24,"RSA Data Security's RC2"},
194 {CALG_RC4, 128, 40, 128,0, 4,"RC4", 24,"RSA Data Security's RC4"},
195 {CALG_DES, 56, 56, 56,0, 4,"DES", 31,"Data Encryption Standard (DES)"},
196 {CALG_3DES_112, 112,112, 112,0, 13,"3DES TWO KEY",19,"Two Key Triple DES"},
197 {CALG_3DES, 168,168, 168,0, 5,"3DES", 21,"Three Key Triple DES"},
198 {CALG_SHA, 160,160, 160,CRYPT_FLAG_SIGNING, 6,"SHA-1", 30,"Secure Hash Algorithm (SHA-1)"},
199 {CALG_MD2, 128,128, 128,CRYPT_FLAG_SIGNING, 4,"MD2", 23,"Message Digest 2 (MD2)"},
200 {CALG_MD4, 128,128, 128,CRYPT_FLAG_SIGNING, 4,"MD4", 23,"Message Digest 4 (MD4)"},
201 {CALG_MD5, 128,128, 128,CRYPT_FLAG_SIGNING, 4,"MD5", 23,"Message Digest 5 (MD5)"},
202 {CALG_SSL3_SHAMD5,288,288,288,0, 12,"SSL3 SHAMD5",12,"SSL3 SHAMD5"},
203 {CALG_MAC, 0, 0, 0,0, 4,"MAC", 28,"Message Authentication Code"},
204 {CALG_RSA_SIGN,1024,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_SIGN",14,"RSA Signature"},
205 {CALG_RSA_KEYX,1024,384,16384,CRYPT_FLAG_SIGNING|CRYPT_FLAG_IPSEC,9,"RSA_KEYX",17,"RSA Key Exchange"},
206 {CALG_HMAC, 0, 0, 0,0, 5,"HMAC", 18,"Hugo's MAC (HMAC)"},
207 {0, 0, 0, 0,0, 1,"", 1,""}
210 {CALG_RC2, 128, 40, 128,RSAENH_PCT1_SSL2_SSL3_TLS1, 4,"RC2", 24,"RSA Data Security's RC2"},
211 {CALG_RC4, 128, 40, 128,RSAENH_PCT1_SSL2_SSL3_TLS1, 4,"RC4", 24,"RSA Data Security's RC4"},
212 {CALG_DES, 56, 56, 56,RSAENH_PCT1_SSL2_SSL3_TLS1, 4,"DES", 31,"Data Encryption Standard (DES)"},
213 {CALG_3DES_112, 112,112, 112,RSAENH_PCT1_SSL2_SSL3_TLS1,13,"3DES TWO KEY",19,"Two Key Triple DES"},
214 {CALG_3DES, 168,168, 168,RSAENH_PCT1_SSL2_SSL3_TLS1, 5,"3DES", 21,"Three Key Triple DES"},
215 {CALG_SHA,160,160,160,CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1,6,"SHA-1",30,"Secure Hash Algorithm (SHA-1)"},
216 {CALG_MD5,128,128,128,CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1,4,"MD5",23,"Message Digest 5 (MD5)"},
217 {CALG_SSL3_SHAMD5,288,288,288,0, 12,"SSL3 SHAMD5",12,"SSL3 SHAMD5"},
218 {CALG_MAC, 0, 0, 0,0, 4,"MAC", 28,"Message Authentication Code"},
219 {CALG_RSA_SIGN,1024,384,16384,CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1,9,"RSA_SIGN",14,"RSA Signature"},
220 {CALG_RSA_KEYX,1024,384,16384,CRYPT_FLAG_SIGNING|RSAENH_PCT1_SSL2_SSL3_TLS1,9,"RSA_KEYX",17,"RSA Key Exchange"},
221 {CALG_HMAC, 0, 0, 0,0, 5,"HMAC", 18,"Hugo's MAC (HMAC)"},
222 {CALG_PCT1_MASTER,128,128,128,CRYPT_FLAG_PCT1, 12,"PCT1 MASTER",12,"PCT1 Master"},
223 {CALG_SSL2_MASTER,40,40, 192,CRYPT_FLAG_SSL2, 12,"SSL2 MASTER",12,"SSL2 Master"},
224 {CALG_SSL3_MASTER,384,384,384,CRYPT_FLAG_SSL3, 12,"SSL3 MASTER",12,"SSL3 Master"},
225 {CALG_TLS1_MASTER,384,384,384,CRYPT_FLAG_TLS1, 12,"TLS1 MASTER",12,"TLS1 Master"},
226 {CALG_SCHANNEL_MASTER_HASH,0,0,-1,0, 16,"SCH MASTER HASH",21,"SChannel Master Hash"},
227 {CALG_SCHANNEL_MAC_KEY,0,0,-1,0, 12,"SCH MAC KEY",17,"SChannel MAC Key"},
228 {CALG_SCHANNEL_ENC_KEY,0,0,-1,0, 12,"SCH ENC KEY",24,"SChannel Encryption Key"},
229 {CALG_TLS1PRF, 0, 0, -1,0, 9,"TLS1 PRF", 28,"TLS1 Pseudo Random Function"},
230 {0, 0, 0, 0,0, 1,"", 1,""}
234 /******************************************************************************
235 * API forward declarations
238 RSAENH_CPGetKeyParam(
269 RSAENH_CPSetHashParam(
273 BYTE *pbData, DWORD dwFlags
277 RSAENH_CPGetHashParam(
287 RSAENH_CPDestroyHash(
322 /******************************************************************************
323 * CSP's handle table (used by all acquired key containers)
325 static HANDLETABLE handle_table;
327 /******************************************************************************
330 * Initializes and destroys the handle table for the CSP's handles.
332 int WINAPI DllMain(HINSTANCE hInstance, DWORD fdwReason, PVOID pvReserved)
336 case DLL_PROCESS_ATTACH:
337 init_handle_table(&handle_table);
340 case DLL_PROCESS_DETACH:
341 destroy_handle_table(&handle_table);
347 /******************************************************************************
348 * copy_param [Internal]
350 * Helper function that supports the standard WINAPI protocol for querying data
354 * pbBuffer [O] Buffer where the queried parameter is copied to, if it is large enough.
355 * May be NUL if the required buffer size is to be queried only.
356 * pdwBufferSize [I/O] In: Size of the buffer at pbBuffer
357 * Out: Size of parameter pbParam
358 * pbParam [I] Parameter value.
359 * dwParamSize [I] Size of pbParam
362 * Success: TRUE (pbParam was copied into pbBuffer or pbBuffer is NULL)
363 * Failure: FALSE (pbBuffer is not large enough to hold pbParam). Last error: ERROR_MORE_DATA
365 static inline BOOL copy_param(
366 BYTE *pbBuffer, DWORD *pdwBufferSize, CONST BYTE *pbParam, DWORD dwParamSize)
370 if (dwParamSize > *pdwBufferSize)
372 SetLastError(ERROR_MORE_DATA);
373 *pdwBufferSize = dwParamSize;
376 memcpy(pbBuffer, pbParam, dwParamSize);
378 *pdwBufferSize = dwParamSize;
382 /******************************************************************************
383 * get_algid_info [Internal]
385 * Query CSP capabilities for a given crypto algorithm.
388 * hProv [I] Handle to a key container of the CSP whose capabilities are to be queried.
389 * algid [I] Identifier of the crypto algorithm about which information is requested.
392 * Success: Pointer to a PROV_ENUMALGS_EX struct containing information about the crypto algorithm.
393 * Failure: NULL (algid not supported)
395 static inline const PROV_ENUMALGS_EX* get_algid_info(HCRYPTPROV hProv, ALG_ID algid) {
396 PROV_ENUMALGS_EX *iterator;
397 KEYCONTAINER *pKeyContainer;
399 if (!lookup_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER, (OBJECTHDR**)&pKeyContainer)) {
400 SetLastError(NTE_BAD_UID);
404 for (iterator = aProvEnumAlgsEx[pKeyContainer->dwPersonality]; iterator->aiAlgid; iterator++) {
405 if (iterator->aiAlgid == algid) return iterator;
408 SetLastError(NTE_BAD_ALGID);
412 /******************************************************************************
413 * copy_data_blob [Internal]
415 * deeply copies a DATA_BLOB
418 * dst [O] That's where the blob will be copied to
419 * src [I] Source blob
423 * Failure: FALSE (GetLastError() == NTE_NO_MEMORY
426 * Use free_data_blob to release resources occupied by copy_data_blob.
428 static inline BOOL copy_data_blob(PCRYPT_DATA_BLOB dst, CONST PCRYPT_DATA_BLOB src) {
429 dst->pbData = HeapAlloc(GetProcessHeap(), 0, src->cbData);
431 SetLastError(NTE_NO_MEMORY);
434 dst->cbData = src->cbData;
435 memcpy(dst->pbData, src->pbData, src->cbData);
439 /******************************************************************************
440 * concat_data_blobs [Internal]
442 * Concatenates two blobs
445 * dst [O] The new blob will be copied here
446 * src1 [I] Prefix blob
447 * src2 [I] Appendix blob
451 * Failure: FALSE (GetLastError() == NTE_NO_MEMORY)
454 * Release resources occupied by concat_data_blobs with free_data_blobs
456 static inline BOOL concat_data_blobs(PCRYPT_DATA_BLOB dst, CONST PCRYPT_DATA_BLOB src1,
457 CONST PCRYPT_DATA_BLOB src2)
459 dst->cbData = src1->cbData + src2->cbData;
460 dst->pbData = HeapAlloc(GetProcessHeap(), 0, dst->cbData);
462 SetLastError(NTE_NO_MEMORY);
465 memcpy(dst->pbData, src1->pbData, src1->cbData);
466 memcpy(dst->pbData + src1->cbData, src2->pbData, src2->cbData);
470 /******************************************************************************
471 * free_data_blob [Internal]
473 * releases resource occupied by a dynamically allocated CRYPT_DATA_BLOB
476 * pBlob [I] Heap space occupied by pBlob->pbData is released
478 static inline void free_data_blob(PCRYPT_DATA_BLOB pBlob) {
479 HeapFree(GetProcessHeap(), 0, pBlob->pbData);
482 /******************************************************************************
483 * init_data_blob [Internal]
485 static inline void init_data_blob(PCRYPT_DATA_BLOB pBlob) {
486 pBlob->pbData = NULL;
490 /******************************************************************************
491 * free_hmac_info [Internal]
493 * Deeply free an HMAC_INFO struct.
496 * hmac_info [I] Pointer to the HMAC_INFO struct to be freed.
499 * See Internet RFC 2104 for details on the HMAC algorithm.
501 static inline void free_hmac_info(PHMAC_INFO hmac_info) {
502 if (!hmac_info) return;
503 HeapFree(GetProcessHeap(), 0, hmac_info->pbInnerString);
504 HeapFree(GetProcessHeap(), 0, hmac_info->pbOuterString);
505 HeapFree(GetProcessHeap(), 0, hmac_info);
508 /******************************************************************************
509 * copy_hmac_info [Internal]
511 * Deeply copy an HMAC_INFO struct
514 * dst [O] Pointer to a location where the pointer to the HMAC_INFO copy will be stored.
515 * src [I] Pointer to the HMAC_INFO struct to be copied.
522 * See Internet RFC 2104 for details on the HMAC algorithm.
524 static BOOL copy_hmac_info(PHMAC_INFO *dst, PHMAC_INFO src) {
525 if (!src) return FALSE;
526 *dst = HeapAlloc(GetProcessHeap(), 0, sizeof(HMAC_INFO));
527 if (!*dst) return FALSE;
528 memcpy(*dst, src, sizeof(HMAC_INFO));
529 (*dst)->pbInnerString = NULL;
530 (*dst)->pbOuterString = NULL;
531 if ((*dst)->cbInnerString == 0) (*dst)->cbInnerString = RSAENH_HMAC_DEF_PAD_LEN;
532 (*dst)->pbInnerString = HeapAlloc(GetProcessHeap(), 0, (*dst)->cbInnerString);
533 if (!(*dst)->pbInnerString) {
534 free_hmac_info(*dst);
537 if (src->cbInnerString)
538 memcpy((*dst)->pbInnerString, src->pbInnerString, src->cbInnerString);
540 memset((*dst)->pbInnerString, RSAENH_HMAC_DEF_IPAD_CHAR, RSAENH_HMAC_DEF_PAD_LEN);
541 if ((*dst)->cbOuterString == 0) (*dst)->cbOuterString = RSAENH_HMAC_DEF_PAD_LEN;
542 (*dst)->pbOuterString = HeapAlloc(GetProcessHeap(), 0, (*dst)->cbOuterString);
543 if (!(*dst)->pbOuterString) {
544 free_hmac_info(*dst);
547 if (src->cbOuterString)
548 memcpy((*dst)->pbOuterString, src->pbOuterString, src->cbOuterString);
550 memset((*dst)->pbOuterString, RSAENH_HMAC_DEF_OPAD_CHAR, RSAENH_HMAC_DEF_PAD_LEN);
554 /******************************************************************************
555 * destroy_hash [Internal]
557 * Destructor for hash objects
560 * pCryptHash [I] Pointer to the hash object to be destroyed.
561 * Will be invalid after function returns!
563 static void destroy_hash(OBJECTHDR *pObject)
565 CRYPTHASH *pCryptHash = (CRYPTHASH*)pObject;
567 free_hmac_info(pCryptHash->pHMACInfo);
568 free_data_blob(&pCryptHash->tpPRFParams.blobLabel);
569 free_data_blob(&pCryptHash->tpPRFParams.blobSeed);
570 HeapFree(GetProcessHeap(), 0, pCryptHash);
573 /******************************************************************************
574 * init_hash [Internal]
576 * Initialize (or reset) a hash object
579 * pCryptHash [I] The hash object to be initialized.
581 static inline BOOL init_hash(CRYPTHASH *pCryptHash) {
584 switch (pCryptHash->aiAlgid)
587 if (pCryptHash->pHMACInfo) {
588 const PROV_ENUMALGS_EX *pAlgInfo;
590 pAlgInfo = get_algid_info(pCryptHash->hProv, pCryptHash->pHMACInfo->HashAlgid);
591 if (!pAlgInfo) return FALSE;
592 pCryptHash->dwHashSize = pAlgInfo->dwDefaultLen >> 3;
593 init_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context);
594 update_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
595 pCryptHash->pHMACInfo->pbInnerString,
596 pCryptHash->pHMACInfo->cbInnerString);
601 dwLen = sizeof(DWORD);
602 RSAENH_CPGetKeyParam(pCryptHash->hProv, pCryptHash->hKey, KP_BLOCKLEN,
603 (BYTE*)&pCryptHash->dwHashSize, &dwLen, 0);
604 pCryptHash->dwHashSize >>= 3;
608 return init_hash_impl(pCryptHash->aiAlgid, &pCryptHash->context);
612 /******************************************************************************
613 * update_hash [Internal]
615 * Hashes the given data and updates the hash object's state accordingly
618 * pCryptHash [I] Hash object to be updated.
619 * pbData [I] Pointer to data stream to be hashed.
620 * dwDataLen [I] Length of data stream.
622 static inline void update_hash(CRYPTHASH *pCryptHash, CONST BYTE *pbData, DWORD dwDataLen) {
625 switch (pCryptHash->aiAlgid)
628 if (pCryptHash->pHMACInfo)
629 update_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
634 pbTemp = HeapAlloc(GetProcessHeap(), 0, dwDataLen);
636 memcpy(pbTemp, pbData, dwDataLen);
637 RSAENH_CPEncrypt(pCryptHash->hProv, pCryptHash->hKey, (HCRYPTHASH)NULL, FALSE, 0,
638 pbTemp, &dwDataLen, dwDataLen);
639 HeapFree(GetProcessHeap(), 0, pbTemp);
643 update_hash_impl(pCryptHash->aiAlgid, &pCryptHash->context, pbData, dwDataLen);
647 /******************************************************************************
648 * finalize_hash [Internal]
650 * Finalizes the hash, after all data has been hashed with update_hash.
651 * No additional data can be hashed afterwards until the hash gets initialized again.
654 * pCryptHash [I] Hash object to be finalized.
656 static inline void finalize_hash(CRYPTHASH *pCryptHash) {
659 switch (pCryptHash->aiAlgid)
662 if (pCryptHash->pHMACInfo) {
663 BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
665 finalize_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
666 pCryptHash->abHashValue);
667 memcpy(abHashValue, pCryptHash->abHashValue, pCryptHash->dwHashSize);
668 init_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context);
669 update_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
670 pCryptHash->pHMACInfo->pbOuterString,
671 pCryptHash->pHMACInfo->cbOuterString);
672 update_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
673 abHashValue, pCryptHash->dwHashSize);
674 finalize_hash_impl(pCryptHash->pHMACInfo->HashAlgid, &pCryptHash->context,
675 pCryptHash->abHashValue);
681 RSAENH_CPEncrypt(pCryptHash->hProv, pCryptHash->hKey, (HCRYPTHASH)NULL, TRUE, 0,
682 pCryptHash->abHashValue, &dwDataLen, pCryptHash->dwHashSize);
686 finalize_hash_impl(pCryptHash->aiAlgid, &pCryptHash->context, pCryptHash->abHashValue);
690 /******************************************************************************
691 * destroy_key [Internal]
693 * Destructor for key objects
696 * pCryptKey [I] Pointer to the key object to be destroyed.
697 * Will be invalid after function returns!
699 static void destroy_key(OBJECTHDR *pObject)
701 CRYPTKEY *pCryptKey = (CRYPTKEY*)pObject;
703 free_key_impl(pCryptKey->aiAlgid, &pCryptKey->context);
704 free_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom);
705 free_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom);
706 HeapFree(GetProcessHeap(), 0, pCryptKey);
709 /******************************************************************************
710 * setup_key [Internal]
712 * Initialize (or reset) a key object
715 * pCryptKey [I] The key object to be initialized.
717 static inline void setup_key(CRYPTKEY *pCryptKey) {
718 pCryptKey->dwState = RSAENH_KEYSTATE_IDLE;
719 memcpy(pCryptKey->abChainVector, pCryptKey->abInitVector, sizeof(pCryptKey->abChainVector));
720 setup_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen,
721 pCryptKey->dwSaltLen, pCryptKey->abKeyValue);
724 /******************************************************************************
727 * Creates a new key object without assigning the actual binary key value.
728 * This is done by CPDeriveKey, CPGenKey or CPImportKey, which call this function.
731 * hProv [I] Handle to the provider to which the created key will belong.
732 * aiAlgid [I] The new key shall use the crypto algorithm idenfied by aiAlgid.
733 * dwFlags [I] Upper 16 bits give the key length.
734 * Lower 16 bits: CRYPT_CREATE_SALT, CRYPT_NO_SALT
735 * ppCryptKey [O] Pointer to the created key
738 * Success: Handle to the created key.
739 * Failure: INVALID_HANDLE_VALUE
741 static HCRYPTKEY new_key(HCRYPTPROV hProv, ALG_ID aiAlgid, DWORD dwFlags, CRYPTKEY **ppCryptKey)
745 DWORD dwKeyLen = HIWORD(dwFlags);
746 const PROV_ENUMALGS_EX *peaAlgidInfo;
751 * Retrieve the CSP's capabilities for the given ALG_ID value
753 peaAlgidInfo = get_algid_info(hProv, aiAlgid);
754 if (!peaAlgidInfo) return (HCRYPTKEY)INVALID_HANDLE_VALUE;
757 * Assume the default key length, if none is specified explicitly
759 if (dwKeyLen == 0) dwKeyLen = peaAlgidInfo->dwDefaultLen;
762 * Check if the requested key length is supported by the current CSP.
763 * Adjust key length's for DES algorithms.
767 if (dwKeyLen == RSAENH_DES_EFFECTIVE_KEYLEN) {
768 dwKeyLen = RSAENH_DES_STORAGE_KEYLEN;
770 if (dwKeyLen != RSAENH_DES_STORAGE_KEYLEN) {
771 SetLastError(NTE_BAD_FLAGS);
772 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
777 if (dwKeyLen == RSAENH_3DES112_EFFECTIVE_KEYLEN) {
778 dwKeyLen = RSAENH_3DES112_STORAGE_KEYLEN;
780 if (dwKeyLen != RSAENH_3DES112_STORAGE_KEYLEN) {
781 SetLastError(NTE_BAD_FLAGS);
782 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
787 if (dwKeyLen == RSAENH_3DES_EFFECTIVE_KEYLEN) {
788 dwKeyLen = RSAENH_3DES_STORAGE_KEYLEN;
790 if (dwKeyLen != RSAENH_3DES_STORAGE_KEYLEN) {
791 SetLastError(NTE_BAD_FLAGS);
792 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
798 dwKeyLen > peaAlgidInfo->dwMaxLen ||
799 dwKeyLen < peaAlgidInfo->dwMinLen)
801 SetLastError(NTE_BAD_FLAGS);
802 return (HCRYPTKEY)INVALID_HANDLE_VALUE;
806 hCryptKey = (HCRYPTKEY)new_object(&handle_table, sizeof(CRYPTKEY), RSAENH_MAGIC_KEY,
807 destroy_key, (OBJECTHDR**)&pCryptKey);
808 if (hCryptKey != (HCRYPTKEY)INVALID_HANDLE_VALUE)
810 pCryptKey->aiAlgid = aiAlgid;
811 pCryptKey->hProv = hProv;
812 pCryptKey->dwModeBits = 0;
813 pCryptKey->dwPermissions = CRYPT_ENCRYPT | CRYPT_DECRYPT | CRYPT_READ | CRYPT_WRITE |
815 pCryptKey->dwKeyLen = dwKeyLen >> 3;
816 if ((dwFlags & CRYPT_CREATE_SALT) || (dwKeyLen == 40 && !(dwFlags & CRYPT_NO_SALT)))
817 pCryptKey->dwSaltLen = 16 /*FIXME*/ - pCryptKey->dwKeyLen;
819 pCryptKey->dwSaltLen = 0;
820 memset(pCryptKey->abKeyValue, 0, sizeof(pCryptKey->abKeyValue));
821 memset(pCryptKey->abInitVector, 0, sizeof(pCryptKey->abInitVector));
822 init_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom);
823 init_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom);
827 case CALG_PCT1_MASTER:
828 case CALG_SSL2_MASTER:
829 case CALG_SSL3_MASTER:
830 case CALG_TLS1_MASTER:
832 pCryptKey->dwBlockLen = 0;
833 pCryptKey->dwMode = 0;
840 pCryptKey->dwBlockLen = 8;
841 pCryptKey->dwMode = CRYPT_MODE_CBC;
846 pCryptKey->dwBlockLen = dwKeyLen >> 3;
847 pCryptKey->dwMode = 0;
851 *ppCryptKey = pCryptKey;
857 /******************************************************************************
858 * destroy_key_container [Internal]
860 * Destructor for key containers. The user's signature and key exchange private
861 * keys are stored in the registry _IN_PLAINTEXT_.
864 * pObjectHdr [I] Pointer to the key container to be destroyed.
866 static void destroy_key_container(OBJECTHDR *pObjectHdr)
868 KEYCONTAINER *pKeyContainer = (KEYCONTAINER*)pObjectHdr;
870 CHAR szRSABase[MAX_PATH];
875 if (!(pKeyContainer->dwFlags & CRYPT_VERIFYCONTEXT)) {
876 /* On WinXP, persistent keys are stored in a file located at:
877 * $AppData$\\Microsoft\\Crypto\\RSA\\$SID$\\some_hex_string
879 sprintf(szRSABase, RSAENH_REGKEY, pKeyContainer->szName);
881 if (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET) {
882 hRootKey = HKEY_LOCAL_MACHINE;
884 hRootKey = HKEY_CURRENT_USER;
887 if (RegCreateKeyExA(hRootKey, szRSABase, 0, NULL, REG_OPTION_NON_VOLATILE,
888 KEY_WRITE, NULL, &hKey, NULL) == ERROR_SUCCESS)
890 if (lookup_handle(&handle_table, pKeyContainer->hKeyExchangeKeyPair, RSAENH_MAGIC_KEY,
893 if (RSAENH_CPExportKey(pKey->hProv, pKeyContainer->hKeyExchangeKeyPair, 0,
894 PRIVATEKEYBLOB, 0, 0, &dwLen))
896 pbKey = HeapAlloc(GetProcessHeap(), 0, dwLen);
899 if (RSAENH_CPExportKey(pKey->hProv, pKeyContainer->hKeyExchangeKeyPair, 0,
900 PRIVATEKEYBLOB, 0, pbKey, &dwLen))
902 RegSetValueExA(hKey, "KeyExchangeKeyPair", 0, REG_BINARY, pbKey, dwLen);
904 HeapFree(GetProcessHeap(), 0, pbKey);
907 release_handle(&handle_table, (unsigned int)pKeyContainer->hKeyExchangeKeyPair,
911 if (lookup_handle(&handle_table, pKeyContainer->hSignatureKeyPair, RSAENH_MAGIC_KEY,
914 if (RSAENH_CPExportKey(pKey->hProv, pKeyContainer->hSignatureKeyPair, 0,
915 PRIVATEKEYBLOB, 0, 0, &dwLen))
917 pbKey = HeapAlloc(GetProcessHeap(), 0, dwLen);
920 if (RSAENH_CPExportKey(pKey->hProv, pKeyContainer->hSignatureKeyPair, 0,
921 PRIVATEKEYBLOB, 0, pbKey, &dwLen))
923 RegSetValueExA(hKey, "SignatureKeyPair", 0, REG_BINARY, pbKey, dwLen);
925 HeapFree(GetProcessHeap(), 0, pbKey);
928 release_handle(&handle_table, (unsigned int)pKeyContainer->hSignatureKeyPair,
936 HeapFree( GetProcessHeap(), 0, pKeyContainer );
939 /******************************************************************************
940 * new_key_container [Internal]
942 * Create a new key container. The personality (RSA Base, Strong or Enhanced CP)
943 * of the CSP is determined via the pVTable->pszProvName string.
946 * pszContainerName [I] Name of the key container.
947 * pVTable [I] Callback functions and context info provided by the OS
950 * Success: Handle to the new key container.
951 * Failure: INVALID_HANDLE_VALUE
953 static HCRYPTPROV new_key_container(PCHAR pszContainerName, DWORD dwFlags, PVTableProvStruc pVTable)
955 KEYCONTAINER *pKeyContainer;
956 HCRYPTPROV hKeyContainer;
958 hKeyContainer = (HCRYPTPROV)new_object(&handle_table, sizeof(KEYCONTAINER), RSAENH_MAGIC_CONTAINER,
959 destroy_key_container, (OBJECTHDR**)&pKeyContainer);
960 if (hKeyContainer != (HCRYPTPROV)INVALID_HANDLE_VALUE)
962 lstrcpynA(pKeyContainer->szName, pszContainerName, MAX_PATH);
963 pKeyContainer->dwFlags = dwFlags;
964 pKeyContainer->dwEnumAlgsCtr = 0;
965 pKeyContainer->hKeyExchangeKeyPair = (HCRYPTKEY)INVALID_HANDLE_VALUE;
966 pKeyContainer->hSignatureKeyPair = (HCRYPTKEY)INVALID_HANDLE_VALUE;
967 if (pVTable && pVTable->pszProvName) {
968 lstrcpynA(pKeyContainer->szProvName, pVTable->pszProvName, MAX_PATH);
969 if (!strcmp(pVTable->pszProvName, MS_DEF_PROV_A)) {
970 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_BASE;
971 } else if (!strcmp(pVTable->pszProvName, MS_ENHANCED_PROV_A)) {
972 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_ENHANCED;
973 } else if (!strcmp(pVTable->pszProvName, MS_DEF_RSA_SCHANNEL_PROV_A)) {
974 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_SCHANNEL;
976 pKeyContainer->dwPersonality = RSAENH_PERSONALITY_STRONG;
980 /* The new key container has to be inserted into the CSP immediately
981 * after creation to be available for CPGetProvParam's PP_ENUMCONTAINERS. */
982 if (!(dwFlags & CRYPT_VERIFYCONTEXT)) {
983 BYTE szRSABase[MAX_PATH];
986 sprintf(szRSABase, RSAENH_REGKEY, pKeyContainer->szName);
988 if (pKeyContainer->dwFlags & CRYPT_MACHINE_KEYSET) {
989 hRootKey = HKEY_LOCAL_MACHINE;
991 hRootKey = HKEY_CURRENT_USER;
994 RegCreateKeyA(hRootKey, szRSABase, &hKey);
999 return hKeyContainer;
1002 /******************************************************************************
1003 * read_key_container [Internal]
1005 * Tries to read the persistent state of the key container (mainly the signature
1006 * and key exchange private keys) given by pszContainerName.
1009 * pszContainerName [I] Name of the key container to read from the registry
1010 * pVTable [I] Pointer to context data provided by the operating system
1013 * Success: Handle to the key container read from the registry
1014 * Failure: INVALID_HANDLE_VALUE
1016 static HCRYPTPROV read_key_container(PCHAR pszContainerName, DWORD dwFlags, PVTableProvStruc pVTable)
1018 CHAR szRSABase[MAX_PATH];
1020 HKEY hKey, hRootKey;
1021 DWORD dwValueType, dwLen;
1022 KEYCONTAINER *pKeyContainer;
1023 HCRYPTPROV hKeyContainer;
1025 sprintf(szRSABase, RSAENH_REGKEY, pszContainerName);
1027 if (dwFlags & CRYPT_MACHINE_KEYSET) {
1028 hRootKey = HKEY_LOCAL_MACHINE;
1030 hRootKey = HKEY_CURRENT_USER;
1033 if (RegOpenKeyExA(hRootKey, szRSABase, 0, KEY_READ, &hKey) != ERROR_SUCCESS)
1035 SetLastError(NTE_BAD_KEYSET);
1036 return (HCRYPTPROV)INVALID_HANDLE_VALUE;
1039 hKeyContainer = new_key_container(pszContainerName, dwFlags, pVTable);
1040 if (hKeyContainer != (HCRYPTPROV)INVALID_HANDLE_VALUE)
1042 if (!lookup_handle(&handle_table, hKeyContainer, RSAENH_MAGIC_CONTAINER,
1043 (OBJECTHDR**)&pKeyContainer))
1044 return (HCRYPTPROV)INVALID_HANDLE_VALUE;
1046 if (RegQueryValueExA(hKey, "KeyExchangeKeyPair", 0, &dwValueType, NULL, &dwLen) ==
1049 pbKey = HeapAlloc(GetProcessHeap(), 0, dwLen);
1052 if (RegQueryValueExA(hKey, "KeyExchangeKeyPair", 0, &dwValueType, pbKey, &dwLen) ==
1055 RSAENH_CPImportKey(hKeyContainer, pbKey, dwLen, 0, 0,
1056 &pKeyContainer->hKeyExchangeKeyPair);
1058 HeapFree(GetProcessHeap(), 0, pbKey);
1062 if (RegQueryValueExA(hKey, "SignatureKeyPair", 0, &dwValueType, NULL, &dwLen) ==
1065 pbKey = HeapAlloc(GetProcessHeap(), 0, dwLen);
1068 if (RegQueryValueExA(hKey, "SignatureKeyPair", 0, &dwValueType, pbKey, &dwLen) ==
1071 RSAENH_CPImportKey(hKeyContainer, pbKey, dwLen, 0, 0,
1072 &pKeyContainer->hSignatureKeyPair);
1074 HeapFree(GetProcessHeap(), 0, pbKey);
1079 return hKeyContainer;
1082 /******************************************************************************
1083 * build_hash_signature [Internal]
1085 * Builds a padded version of a hash to match the length of the RSA key modulus.
1088 * pbSignature [O] The padded hash object is stored here.
1089 * dwLen [I] Length of the pbSignature buffer.
1090 * aiAlgid [I] Algorithm identifier of the hash to be padded.
1091 * abHashValue [I] The value of the hash object.
1092 * dwHashLen [I] Length of the hash value.
1093 * dwFlags [I] Selection of padding algorithm.
1097 * Failure: FALSE (NTE_BAD_ALGID)
1099 static BOOL build_hash_signature(BYTE *pbSignature, DWORD dwLen, ALG_ID aiAlgid,
1100 CONST BYTE *abHashValue, DWORD dwHashLen, DWORD dwFlags)
1102 /* These prefixes are meant to be concatenated with hash values of the
1103 * respective kind to form a PKCS #7 DigestInfo. */
1104 static const struct tagOIDDescriptor {
1107 CONST BYTE abOID[18];
1108 } aOIDDescriptor[5] = {
1109 { CALG_MD2, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48,
1110 0x86, 0xf7, 0x0d, 0x02, 0x02, 0x05, 0x00, 0x04, 0x10 } },
1111 { CALG_MD4, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48,
1112 0x86, 0xf7, 0x0d, 0x02, 0x04, 0x05, 0x00, 0x04, 0x10 } },
1113 { CALG_MD5, 18, { 0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48,
1114 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10 } },
1115 { CALG_SHA, 15, { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
1116 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 } },
1119 DWORD dwIdxOID, i, j;
1121 for (dwIdxOID = 0; aOIDDescriptor[dwIdxOID].aiAlgid; dwIdxOID++) {
1122 if (aOIDDescriptor[dwIdxOID].aiAlgid == aiAlgid) break;
1125 if (!aOIDDescriptor[dwIdxOID].aiAlgid) {
1126 SetLastError(NTE_BAD_ALGID);
1130 /* Build the padded signature */
1131 if (dwFlags & CRYPT_X931_FORMAT) {
1132 pbSignature[0] = 0x6b;
1133 for (i=1; i < dwLen - dwHashLen - 3; i++) {
1134 pbSignature[i] = 0xbb;
1136 pbSignature[i++] = 0xba;
1137 for (j=0; j < dwHashLen; j++, i++) {
1138 pbSignature[i] = abHashValue[j];
1140 pbSignature[i++] = 0x33;
1141 pbSignature[i++] = 0xcc;
1143 pbSignature[0] = 0x00;
1144 pbSignature[1] = 0x01;
1145 if (dwFlags & CRYPT_NOHASHOID) {
1146 for (i=2; i < dwLen - 1 - dwHashLen; i++) {
1147 pbSignature[i] = 0xff;
1149 pbSignature[i++] = 0x00;
1151 for (i=2; i < dwLen - 1 - aOIDDescriptor[dwIdxOID].dwLen - dwHashLen; i++) {
1152 pbSignature[i] = 0xff;
1154 pbSignature[i++] = 0x00;
1155 for (j=0; j < aOIDDescriptor[dwIdxOID].dwLen; j++) {
1156 pbSignature[i++] = aOIDDescriptor[dwIdxOID].abOID[j];
1159 for (j=0; j < dwHashLen; j++) {
1160 pbSignature[i++] = abHashValue[j];
1167 /******************************************************************************
1170 * This is an implementation of the 'P_hash' helper function for TLS1's PRF.
1171 * It is used exclusively by tls1_prf. For details see RFC 2246, chapter 5.
1172 * The pseudo random stream generated by this function is exclusive or'ed with
1173 * the data in pbBuffer.
1176 * hHMAC [I] HMAC object, which will be used in pseudo random generation
1177 * pblobSeed [I] Seed value
1178 * pbBuffer [I/O] Pseudo random stream will be xor'ed to the provided data
1179 * dwBufferLen [I] Number of pseudo random bytes desired
1185 static BOOL tls1_p(HCRYPTHASH hHMAC, CONST PCRYPT_DATA_BLOB pblobSeed, PBYTE pbBuffer, DWORD dwBufferLen)
1188 BYTE abAi[RSAENH_MAX_HASH_SIZE];
1191 if (!lookup_handle(&handle_table, hHMAC, RSAENH_MAGIC_HASH, (OBJECTHDR**)&pHMAC)) {
1192 SetLastError(NTE_BAD_HASH);
1196 /* compute A_1 = HMAC(seed) */
1198 update_hash(pHMAC, pblobSeed->pbData, pblobSeed->cbData);
1199 finalize_hash(pHMAC);
1200 memcpy(abAi, pHMAC->abHashValue, pHMAC->dwHashSize);
1203 /* compute HMAC(A_i + seed) */
1205 update_hash(pHMAC, abAi, pHMAC->dwHashSize);
1206 update_hash(pHMAC, pblobSeed->pbData, pblobSeed->cbData);
1207 finalize_hash(pHMAC);
1209 /* pseudo random stream := CONCAT_{i=1..n} ( HMAC(A_i + seed) ) */
1211 if (i >= dwBufferLen) break;
1212 pbBuffer[i] ^= pHMAC->abHashValue[i % pHMAC->dwHashSize];
1214 } while (i % pHMAC->dwHashSize);
1216 /* compute A_{i+1} = HMAC(A_i) */
1218 update_hash(pHMAC, abAi, pHMAC->dwHashSize);
1219 finalize_hash(pHMAC);
1220 memcpy(abAi, pHMAC->abHashValue, pHMAC->dwHashSize);
1221 } while (i < dwBufferLen);
1226 /******************************************************************************
1227 * tls1_prf [Internal]
1229 * TLS1 pseudo random function as specified in RFC 2246, chapter 5
1232 * hProv [I] Key container used to compute the pseudo random stream
1233 * hSecret [I] Key that holds the (pre-)master secret
1234 * pblobLabel [I] Descriptive label
1235 * pblobSeed [I] Seed value
1236 * pbBuffer [O] Pseudo random numbers will be stored here
1237 * dwBufferLen [I] Number of pseudo random bytes desired
1243 static BOOL tls1_prf(HCRYPTPROV hProv, HCRYPTPROV hSecret, CONST PCRYPT_DATA_BLOB pblobLabel,
1244 CONST PCRYPT_DATA_BLOB pblobSeed, PBYTE pbBuffer, DWORD dwBufferLen)
1246 HMAC_INFO hmacInfo = { 0, NULL, 0, NULL, 0 };
1247 HCRYPTHASH hHMAC = (HCRYPTHASH)INVALID_HANDLE_VALUE;
1248 HCRYPTKEY hHalfSecret = (HCRYPTKEY)INVALID_HANDLE_VALUE;
1249 CRYPTKEY *pHalfSecret, *pSecret;
1250 DWORD dwHalfSecretLen;
1251 BOOL result = FALSE;
1252 CRYPT_DATA_BLOB blobLabelSeed;
1254 TRACE("(hProv=%08lx, hSecret=%08lx, pblobLabel=%p, pblobSeed=%p, pbBuffer=%p, dwBufferLen=%ld)\n",
1255 hProv, hSecret, pblobLabel, pblobSeed, pbBuffer, dwBufferLen);
1257 if (!lookup_handle(&handle_table, hSecret, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pSecret)) {
1258 SetLastError(NTE_FAIL);
1262 dwHalfSecretLen = (pSecret->dwKeyLen+1)/2;
1264 /* concatenation of the label and the seed */
1265 if (!concat_data_blobs(&blobLabelSeed, pblobLabel, pblobSeed)) goto exit;
1267 /* zero out the buffer, since two random streams will be xor'ed into it. */
1268 memset(pbBuffer, 0, dwBufferLen);
1270 /* build a 'fake' key, to hold the secret. CALG_SSL2_MASTER is used since it provides
1271 * the biggest range of valid key lengths. */
1272 hHalfSecret = new_key(hProv, CALG_SSL2_MASTER, MAKELONG(0,dwHalfSecretLen*8), &pHalfSecret);
1273 if (hHalfSecret == (HCRYPTKEY)INVALID_HANDLE_VALUE) goto exit;
1275 /* Derive an HMAC_MD5 hash and call the helper function. */
1276 memcpy(pHalfSecret->abKeyValue, pSecret->abKeyValue, dwHalfSecretLen);
1277 if (!RSAENH_CPCreateHash(hProv, CALG_HMAC, hHalfSecret, 0, &hHMAC)) goto exit;
1278 hmacInfo.HashAlgid = CALG_MD5;
1279 if (!RSAENH_CPSetHashParam(hProv, hHMAC, HP_HMAC_INFO, (BYTE*)&hmacInfo, 0)) goto exit;
1280 if (!tls1_p(hHMAC, &blobLabelSeed, pbBuffer, dwBufferLen)) goto exit;
1282 /* Reconfigure to HMAC_SHA hash and call helper function again. */
1283 memcpy(pHalfSecret->abKeyValue, pSecret->abKeyValue + (pSecret->dwKeyLen/2), dwHalfSecretLen);
1284 hmacInfo.HashAlgid = CALG_SHA;
1285 if (!RSAENH_CPSetHashParam(hProv, hHMAC, HP_HMAC_INFO, (BYTE*)&hmacInfo, 0)) goto exit;
1286 if (!tls1_p(hHMAC, &blobLabelSeed, pbBuffer, dwBufferLen)) goto exit;
1290 release_handle(&handle_table, hHalfSecret, RSAENH_MAGIC_KEY);
1291 if (hHMAC != (HCRYPTHASH)INVALID_HANDLE_VALUE) RSAENH_CPDestroyHash(hProv, hHMAC);
1292 free_data_blob(&blobLabelSeed);
1296 /******************************************************************************
1297 * pad_data [Internal]
1299 * Helper function for data padding according to PKCS1 #2
1302 * abData [I] The data to be padded
1303 * dwDataLen [I] Length of the data
1304 * abBuffer [O] Padded data will be stored here
1305 * dwBufferLen [I] Length of the buffer (also length of padded data)
1306 * dwFlags [I] Padding format (CRYPT_SSL2_FALLBACK)
1310 * Failure: FALSE (NTE_BAD_LEN, too much data to pad)
1312 static BOOL pad_data(CONST BYTE *abData, DWORD dwDataLen, BYTE *abBuffer, DWORD dwBufferLen,
1317 /* Ensure there is enough space for PKCS1 #2 padding */
1318 if (dwDataLen > dwBufferLen-11) {
1319 SetLastError(NTE_BAD_LEN);
1323 memmove(abBuffer + dwBufferLen - dwDataLen, abData, dwDataLen);
1326 abBuffer[1] = RSAENH_PKC_BLOCKTYPE;
1327 for (i=2; i < dwBufferLen - dwDataLen - 1; i++)
1328 do gen_rand_impl(&abBuffer[i], 1); while (!abBuffer[i]);
1329 if (dwFlags & CRYPT_SSL2_FALLBACK)
1330 for (i-=8; i < dwBufferLen - dwDataLen - 1; i++)
1337 /******************************************************************************
1338 * unpad_data [Internal]
1340 * Remove the PKCS1 padding from RSA decrypted data
1343 * abData [I] The padded data
1344 * dwDataLen [I] Length of the padded data
1345 * abBuffer [O] Data without padding will be stored here
1346 * dwBufferLen [I/O] I: Length of the buffer, O: Length of unpadded data
1347 * dwFlags [I] Currently none defined
1351 * Failure: FALSE, (NTE_BAD_DATA, no valid PKCS1 padding or buffer too small)
1353 static BOOL unpad_data(CONST BYTE *abData, DWORD dwDataLen, BYTE *abBuffer, DWORD *dwBufferLen,
1358 for (i=2; i<dwDataLen; i++)
1362 if ((i == dwDataLen) || (*dwBufferLen < dwDataLen - i - 1) ||
1363 (abData[0] != 0x00) || (abData[1] != RSAENH_PKC_BLOCKTYPE))
1365 SetLastError(NTE_BAD_DATA);
1369 *dwBufferLen = dwDataLen - i - 1;
1370 memmove(abBuffer, abData + i + 1, *dwBufferLen);
1374 /******************************************************************************
1375 * CPAcquireContext (RSAENH.@)
1377 * Acquire a handle to the key container specified by pszContainer
1380 * phProv [O] Pointer to the location the acquired handle will be written to.
1381 * pszContainer [I] Name of the desired key container. See Notes
1382 * dwFlags [I] Flags. See Notes.
1383 * pVTable [I] Pointer to a PVTableProvStruct containing callbacks.
1390 * If pszContainer is NULL or points to a zero length string the user's login
1391 * name will be used as the key container name.
1393 * If the CRYPT_NEW_KEYSET flag is set in dwFlags a new keyset will be created.
1394 * If a keyset with the given name already exists, the function fails and sets
1395 * last error to NTE_EXISTS. If CRYPT_NEW_KEYSET is not set and the specified
1396 * key container does not exist, function fails and sets last error to
1399 BOOL WINAPI RSAENH_CPAcquireContext(HCRYPTPROV *phProv, LPSTR pszContainer,
1400 DWORD dwFlags, PVTableProvStruc pVTable)
1403 CHAR szKeyContainerName[MAX_PATH] = "";
1404 CHAR szRegKey[MAX_PATH];
1406 TRACE("(phProv=%p, pszContainer=%s, dwFlags=%08lx, pVTable=%p)\n", phProv,
1407 debugstr_a(pszContainer), dwFlags, pVTable);
1409 if (pszContainer ? strlen(pszContainer) : 0)
1411 strncpy(szKeyContainerName, pszContainer, MAX_PATH);
1412 szKeyContainerName[MAX_PATH-1] = '\0';
1417 if (!GetUserNameA(szKeyContainerName, &dwLen)) return FALSE;
1420 switch (dwFlags & (CRYPT_NEWKEYSET|CRYPT_VERIFYCONTEXT|CRYPT_DELETEKEYSET))
1423 *phProv = read_key_container(szKeyContainerName, dwFlags, pVTable);
1426 case CRYPT_DELETEKEYSET:
1427 if (snprintf(szRegKey, MAX_PATH, RSAENH_REGKEY, pszContainer) >= MAX_PATH) {
1428 SetLastError(NTE_BAD_KEYSET_PARAM);
1431 RegDeleteKeyA(HKEY_CURRENT_USER, szRegKey);
1432 SetLastError(ERROR_SUCCESS);
1437 case CRYPT_NEWKEYSET:
1438 *phProv = read_key_container(szKeyContainerName, dwFlags, pVTable);
1439 if (*phProv != (HCRYPTPROV)INVALID_HANDLE_VALUE)
1441 release_handle(&handle_table, (unsigned int)*phProv, RSAENH_MAGIC_CONTAINER);
1442 SetLastError(NTE_EXISTS);
1445 *phProv = new_key_container(szKeyContainerName, dwFlags, pVTable);
1448 case CRYPT_VERIFYCONTEXT:
1450 SetLastError(NTE_BAD_FLAGS);
1453 *phProv = new_key_container("", dwFlags, pVTable);
1457 *phProv = (unsigned int)INVALID_HANDLE_VALUE;
1458 SetLastError(NTE_BAD_FLAGS);
1462 if (*phProv != (unsigned int)INVALID_HANDLE_VALUE) {
1463 SetLastError(ERROR_SUCCESS);
1470 /******************************************************************************
1471 * CPCreateHash (RSAENH.@)
1473 * CPCreateHash creates and initalizes a new hash object.
1476 * hProv [I] Handle to the key container to which the new hash will belong.
1477 * Algid [I] Identifies the hash algorithm, which will be used for the hash.
1478 * hKey [I] Handle to a session key applied for keyed hashes.
1479 * dwFlags [I] Currently no flags defined. Must be zero.
1480 * phHash [O] Points to the location where a handle to the new hash will be stored.
1487 * hKey is a handle to a session key applied in keyed hashes like MAC and HMAC.
1488 * If a normal hash object is to be created (like e.g. MD2 or SHA1) hKey must be zero.
1490 BOOL WINAPI RSAENH_CPCreateHash(HCRYPTPROV hProv, ALG_ID Algid, HCRYPTKEY hKey, DWORD dwFlags,
1493 CRYPTKEY *pCryptKey;
1494 CRYPTHASH *pCryptHash;
1495 const PROV_ENUMALGS_EX *peaAlgidInfo;
1497 TRACE("(hProv=%08lx, Algid=%08x, hKey=%08lx, dwFlags=%08lx, phHash=%p)\n", hProv, Algid, hKey,
1500 peaAlgidInfo = get_algid_info(hProv, Algid);
1501 if (!peaAlgidInfo) return FALSE;
1505 SetLastError(NTE_BAD_FLAGS);
1509 if (Algid == CALG_MAC || Algid == CALG_HMAC || Algid == CALG_SCHANNEL_MASTER_HASH ||
1510 Algid == CALG_TLS1PRF)
1512 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey)) {
1513 SetLastError(NTE_BAD_KEY);
1517 if ((Algid == CALG_MAC) && (GET_ALG_TYPE(pCryptKey->aiAlgid) != ALG_TYPE_BLOCK)) {
1518 SetLastError(NTE_BAD_KEY);
1522 if ((Algid == CALG_SCHANNEL_MASTER_HASH || Algid == CALG_TLS1PRF) &&
1523 (pCryptKey->aiAlgid != CALG_TLS1_MASTER))
1525 SetLastError(NTE_BAD_KEY);
1529 if ((Algid == CALG_TLS1PRF) && (pCryptKey->dwState != RSAENH_KEYSTATE_MASTERKEY)) {
1530 SetLastError(NTE_BAD_KEY_STATE);
1535 *phHash = (HCRYPTHASH)new_object(&handle_table, sizeof(CRYPTHASH), RSAENH_MAGIC_HASH,
1536 destroy_hash, (OBJECTHDR**)&pCryptHash);
1537 if (!pCryptHash) return FALSE;
1539 pCryptHash->aiAlgid = Algid;
1540 pCryptHash->hKey = hKey;
1541 pCryptHash->hProv = hProv;
1542 pCryptHash->dwState = RSAENH_HASHSTATE_IDLE;
1543 pCryptHash->pHMACInfo = (PHMAC_INFO)NULL;
1544 pCryptHash->dwHashSize = peaAlgidInfo->dwDefaultLen >> 3;
1545 init_data_blob(&pCryptHash->tpPRFParams.blobLabel);
1546 init_data_blob(&pCryptHash->tpPRFParams.blobSeed);
1548 if (Algid == CALG_SCHANNEL_MASTER_HASH) {
1549 CRYPT_DATA_BLOB blobRandom, blobKeyExpansion = { 13, "key expansion" };
1551 if (pCryptKey->dwState != RSAENH_KEYSTATE_MASTERKEY) {
1552 CRYPT_DATA_BLOB blobLabel = { 13, "master secret" };
1553 BYTE abKeyValue[48];
1555 /* See RFC 2246, chapter 8.1 */
1556 if (!concat_data_blobs(&blobRandom,
1557 &pCryptKey->siSChannelInfo.blobClientRandom,
1558 &pCryptKey->siSChannelInfo.blobServerRandom))
1562 tls1_prf(hProv, hKey, &blobLabel, &blobRandom, abKeyValue, 48);
1563 pCryptKey->dwState = RSAENH_KEYSTATE_MASTERKEY;
1564 memcpy(pCryptKey->abKeyValue, abKeyValue, 48);
1565 free_data_blob(&blobRandom);
1568 /* See RFC 2246, chapter 6.3 */
1569 if (!concat_data_blobs(&blobRandom,
1570 &pCryptKey->siSChannelInfo.blobServerRandom,
1571 &pCryptKey->siSChannelInfo.blobClientRandom))
1575 tls1_prf(hProv, hKey, &blobKeyExpansion, &blobRandom, pCryptHash->abHashValue,
1576 RSAENH_MAX_HASH_SIZE);
1577 free_data_blob(&blobRandom);
1580 return init_hash(pCryptHash);
1583 /******************************************************************************
1584 * CPDestroyHash (RSAENH.@)
1586 * Releases the handle to a hash object. The object is destroyed if it's reference
1587 * count reaches zero.
1590 * hProv [I] Handle to the key container to which the hash object belongs.
1591 * hHash [I] Handle to the hash object to be released.
1597 BOOL WINAPI RSAENH_CPDestroyHash(HCRYPTPROV hProv, HCRYPTHASH hHash)
1599 TRACE("(hProv=%08lx, hHash=%08lx)\n", hProv, hHash);
1601 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
1603 SetLastError(NTE_BAD_UID);
1607 if (!release_handle(&handle_table, hHash, RSAENH_MAGIC_HASH))
1609 SetLastError(NTE_BAD_HASH);
1616 /******************************************************************************
1617 * CPDestroyKey (RSAENH.@)
1619 * Releases the handle to a key object. The object is destroyed if it's reference
1620 * count reaches zero.
1623 * hProv [I] Handle to the key container to which the key object belongs.
1624 * hKey [I] Handle to the key object to be released.
1630 BOOL WINAPI RSAENH_CPDestroyKey(HCRYPTPROV hProv, HCRYPTKEY hKey)
1632 TRACE("(hProv=%08lx, hKey=%08lx)\n", hProv, hKey);
1634 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
1636 SetLastError(NTE_BAD_UID);
1640 if (!release_handle(&handle_table, hKey, RSAENH_MAGIC_KEY))
1642 SetLastError(NTE_BAD_KEY);
1649 /******************************************************************************
1650 * CPDuplicateHash (RSAENH.@)
1652 * Clones a hash object including it's current state.
1655 * hUID [I] Handle to the key container the hash belongs to.
1656 * hHash [I] Handle to the hash object to be cloned.
1657 * pdwReserved [I] Reserved. Must be NULL.
1658 * dwFlags [I] No flags are currently defined. Must be 0.
1659 * phHash [O] Handle to the cloned hash object.
1665 BOOL WINAPI RSAENH_CPDuplicateHash(HCRYPTPROV hUID, HCRYPTHASH hHash, DWORD *pdwReserved,
1666 DWORD dwFlags, HCRYPTHASH *phHash)
1668 CRYPTHASH *pSrcHash, *pDestHash;
1670 TRACE("(hUID=%08lx, hHash=%08lx, pdwReserved=%p, dwFlags=%08lx, phHash=%p)\n", hUID, hHash,
1671 pdwReserved, dwFlags, phHash);
1673 if (!is_valid_handle(&handle_table, hUID, RSAENH_MAGIC_CONTAINER))
1675 SetLastError(NTE_BAD_UID);
1679 if (!lookup_handle(&handle_table, hHash, RSAENH_MAGIC_HASH, (OBJECTHDR**)&pSrcHash))
1681 SetLastError(NTE_BAD_HASH);
1685 if (!phHash || pdwReserved || dwFlags)
1687 SetLastError(ERROR_INVALID_PARAMETER);
1691 *phHash = (HCRYPTHASH)new_object(&handle_table, sizeof(CRYPTHASH), RSAENH_MAGIC_HASH,
1692 destroy_hash, (OBJECTHDR**)&pDestHash);
1693 if (*phHash != (HCRYPTHASH)INVALID_HANDLE_VALUE)
1695 memcpy(pDestHash, pSrcHash, sizeof(CRYPTHASH));
1696 duplicate_hash_impl(pSrcHash->aiAlgid, &pSrcHash->context, &pDestHash->context);
1697 copy_hmac_info(&pDestHash->pHMACInfo, pSrcHash->pHMACInfo);
1698 copy_data_blob(&pDestHash->tpPRFParams.blobLabel, &pSrcHash->tpPRFParams.blobLabel);
1699 copy_data_blob(&pDestHash->tpPRFParams.blobSeed, &pSrcHash->tpPRFParams.blobSeed);
1702 return *phHash != (HCRYPTHASH)INVALID_HANDLE_VALUE;
1705 /******************************************************************************
1706 * CPDuplicateKey (RSAENH.@)
1708 * Clones a key object including it's current state.
1711 * hUID [I] Handle to the key container the hash belongs to.
1712 * hKey [I] Handle to the key object to be cloned.
1713 * pdwReserved [I] Reserved. Must be NULL.
1714 * dwFlags [I] No flags are currently defined. Must be 0.
1715 * phHash [O] Handle to the cloned key object.
1721 BOOL WINAPI RSAENH_CPDuplicateKey(HCRYPTPROV hUID, HCRYPTKEY hKey, DWORD *pdwReserved,
1722 DWORD dwFlags, HCRYPTKEY *phKey)
1724 CRYPTKEY *pSrcKey, *pDestKey;
1726 TRACE("(hUID=%08lx, hKey=%08lx, pdwReserved=%p, dwFlags=%08lx, phKey=%p)\n", hUID, hKey,
1727 pdwReserved, dwFlags, phKey);
1729 if (!is_valid_handle(&handle_table, hUID, RSAENH_MAGIC_CONTAINER))
1731 SetLastError(NTE_BAD_UID);
1735 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pSrcKey))
1737 SetLastError(NTE_BAD_KEY);
1741 if (!phKey || pdwReserved || dwFlags)
1743 SetLastError(ERROR_INVALID_PARAMETER);
1747 *phKey = (HCRYPTKEY)new_object(&handle_table, sizeof(CRYPTKEY), RSAENH_MAGIC_KEY, destroy_key,
1748 (OBJECTHDR**)&pDestKey);
1749 if (*phKey != (HCRYPTKEY)INVALID_HANDLE_VALUE)
1751 memcpy(pDestKey, pSrcKey, sizeof(CRYPTKEY));
1752 copy_data_blob(&pDestKey->siSChannelInfo.blobServerRandom,
1753 &pSrcKey->siSChannelInfo.blobServerRandom);
1754 copy_data_blob(&pDestKey->siSChannelInfo.blobClientRandom,
1755 &pSrcKey->siSChannelInfo.blobClientRandom);
1756 duplicate_key_impl(pSrcKey->aiAlgid, &pSrcKey->context, &pDestKey->context);
1765 /******************************************************************************
1766 * CPEncrypt (RSAENH.@)
1771 * hProv [I] The key container hKey and hHash belong to.
1772 * hKey [I] The key used to encrypt the data.
1773 * hHash [I] An optional hash object for parallel hashing. See notes.
1774 * Final [I] Indicates if this is the last block of data to encrypt.
1775 * dwFlags [I] Currently no flags defined. Must be zero.
1776 * pbData [I/O] Pointer to the data to encrypt. Encrypted data will also be stored there.
1777 * pdwDataLen [I/O] I: Length of data to encrypt, O: Length of encrypted data.
1778 * dwBufLen [I] Size of the buffer at pbData.
1785 * If a hash object handle is provided in hHash, it will be updated with the plaintext.
1786 * This is useful for message signatures.
1788 * This function uses the standard WINAPI protocol for querying data of dynamic length.
1790 BOOL WINAPI RSAENH_CPEncrypt(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final,
1791 DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen, DWORD dwBufLen)
1793 CRYPTKEY *pCryptKey;
1794 BYTE *in, out[RSAENH_MAX_BLOCK_SIZE], o[RSAENH_MAX_BLOCK_SIZE];
1795 DWORD dwEncryptedLen, i, j, k;
1797 TRACE("(hProv=%08lx, hKey=%08lx, hHash=%08lx, Final=%d, dwFlags=%08lx, pbData=%p, "
1798 "pdwDataLen=%p, dwBufLen=%ld)\n", hProv, hKey, hHash, Final, dwFlags, pbData, pdwDataLen,
1801 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
1803 SetLastError(NTE_BAD_UID);
1809 SetLastError(NTE_BAD_FLAGS);
1813 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
1815 SetLastError(NTE_BAD_KEY);
1819 if (pCryptKey->dwState == RSAENH_KEYSTATE_IDLE)
1820 pCryptKey->dwState = RSAENH_KEYSTATE_ENCRYPTING;
1822 if (pCryptKey->dwState != RSAENH_KEYSTATE_ENCRYPTING)
1824 SetLastError(NTE_BAD_DATA);
1828 if (is_valid_handle(&handle_table, hHash, RSAENH_MAGIC_HASH)) {
1829 if (!RSAENH_CPHashData(hProv, hHash, pbData, *pdwDataLen, 0)) return FALSE;
1832 if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_BLOCK) {
1833 if (!Final && (*pdwDataLen % pCryptKey->dwBlockLen)) {
1834 SetLastError(NTE_BAD_DATA);
1838 dwEncryptedLen = (*pdwDataLen/pCryptKey->dwBlockLen+(Final?1:0))*pCryptKey->dwBlockLen;
1839 for (i=*pdwDataLen; i<dwEncryptedLen; i++) pbData[i] = dwEncryptedLen - *pdwDataLen;
1840 *pdwDataLen = dwEncryptedLen;
1842 if (*pdwDataLen > dwBufLen)
1844 SetLastError(ERROR_MORE_DATA);
1848 for (i=0, in=pbData; i<*pdwDataLen; i+=pCryptKey->dwBlockLen, in+=pCryptKey->dwBlockLen) {
1849 switch (pCryptKey->dwMode) {
1850 case CRYPT_MODE_ECB:
1851 encrypt_block_impl(pCryptKey->aiAlgid, &pCryptKey->context, in, out,
1855 case CRYPT_MODE_CBC:
1856 for (j=0; j<pCryptKey->dwBlockLen; j++) in[j] ^= pCryptKey->abChainVector[j];
1857 encrypt_block_impl(pCryptKey->aiAlgid, &pCryptKey->context, in, out,
1859 memcpy(pCryptKey->abChainVector, out, pCryptKey->dwBlockLen);
1862 case CRYPT_MODE_CFB:
1863 for (j=0; j<pCryptKey->dwBlockLen; j++) {
1864 encrypt_block_impl(pCryptKey->aiAlgid, &pCryptKey->context,
1865 pCryptKey->abChainVector, o, RSAENH_ENCRYPT);
1866 out[j] = in[j] ^ o[0];
1867 for (k=0; k<pCryptKey->dwBlockLen-1; k++)
1868 pCryptKey->abChainVector[k] = pCryptKey->abChainVector[k+1];
1869 pCryptKey->abChainVector[k] = out[j];
1874 SetLastError(NTE_BAD_ALGID);
1877 memcpy(in, out, pCryptKey->dwBlockLen);
1879 } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_STREAM) {
1880 encrypt_stream_impl(pCryptKey->aiAlgid, &pCryptKey->context, pbData, *pdwDataLen);
1881 } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_RSA) {
1882 if (pCryptKey->aiAlgid == CALG_RSA_SIGN) {
1883 SetLastError(NTE_BAD_KEY);
1886 if (dwBufLen < pCryptKey->dwBlockLen) {
1887 SetLastError(ERROR_MORE_DATA);
1890 if (!pad_data(pbData, *pdwDataLen, pbData, pCryptKey->dwBlockLen, dwFlags)) return FALSE;
1891 encrypt_block_impl(pCryptKey->aiAlgid, &pCryptKey->context, pbData, pbData, RSAENH_ENCRYPT);
1892 *pdwDataLen = pCryptKey->dwBlockLen;
1895 SetLastError(NTE_BAD_TYPE);
1899 if (Final) setup_key(pCryptKey);
1904 /******************************************************************************
1905 * CPDecrypt (RSAENH.@)
1910 * hProv [I] The key container hKey and hHash belong to.
1911 * hKey [I] The key used to decrypt the data.
1912 * hHash [I] An optional hash object for parallel hashing. See notes.
1913 * Final [I] Indicates if this is the last block of data to decrypt.
1914 * dwFlags [I] Currently no flags defined. Must be zero.
1915 * pbData [I/O] Pointer to the data to decrypt. Plaintext will also be stored there.
1916 * pdwDataLen [I/O] I: Length of ciphertext, O: Length of plaintext.
1923 * If a hash object handle is provided in hHash, it will be updated with the plaintext.
1924 * This is useful for message signatures.
1926 * This function uses the standard WINAPI protocol for querying data of dynamic length.
1928 BOOL WINAPI RSAENH_CPDecrypt(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final,
1929 DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
1931 CRYPTKEY *pCryptKey;
1932 BYTE *in, out[RSAENH_MAX_BLOCK_SIZE], o[RSAENH_MAX_BLOCK_SIZE];
1935 TRACE("(hProv=%08lx, hKey=%08lx, hHash=%08lx, Final=%d, dwFlags=%08lx, pbData=%p, "
1936 "pdwDataLen=%p)\n", hProv, hKey, hHash, Final, dwFlags, pbData, pdwDataLen);
1938 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
1940 SetLastError(NTE_BAD_UID);
1946 SetLastError(NTE_BAD_FLAGS);
1950 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
1952 SetLastError(NTE_BAD_KEY);
1956 if (pCryptKey->dwState == RSAENH_KEYSTATE_IDLE)
1957 pCryptKey->dwState = RSAENH_KEYSTATE_DECRYPTING;
1959 if (pCryptKey->dwState != RSAENH_KEYSTATE_DECRYPTING)
1961 SetLastError(NTE_BAD_DATA);
1965 if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_BLOCK) {
1966 for (i=0, in=pbData; i<*pdwDataLen; i+=pCryptKey->dwBlockLen, in+=pCryptKey->dwBlockLen) {
1967 switch (pCryptKey->dwMode) {
1968 case CRYPT_MODE_ECB:
1969 encrypt_block_impl(pCryptKey->aiAlgid, &pCryptKey->context, in, out,
1973 case CRYPT_MODE_CBC:
1974 encrypt_block_impl(pCryptKey->aiAlgid, &pCryptKey->context, in, out,
1976 for (j=0; j<pCryptKey->dwBlockLen; j++) out[j] ^= pCryptKey->abChainVector[j];
1977 memcpy(pCryptKey->abChainVector, in, pCryptKey->dwBlockLen);
1980 case CRYPT_MODE_CFB:
1981 for (j=0; j<pCryptKey->dwBlockLen; j++) {
1982 encrypt_block_impl(pCryptKey->aiAlgid, &pCryptKey->context,
1983 pCryptKey->abChainVector, o, RSAENH_ENCRYPT);
1984 out[j] = in[j] ^ o[0];
1985 for (k=0; k<pCryptKey->dwBlockLen-1; k++)
1986 pCryptKey->abChainVector[k] = pCryptKey->abChainVector[k+1];
1987 pCryptKey->abChainVector[k] = in[j];
1992 SetLastError(NTE_BAD_ALGID);
1995 memcpy(in, out, pCryptKey->dwBlockLen);
1997 if (Final) *pdwDataLen -= pbData[*pdwDataLen-1];
1999 } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_STREAM) {
2000 encrypt_stream_impl(pCryptKey->aiAlgid, &pCryptKey->context, pbData, *pdwDataLen);
2001 } else if (GET_ALG_TYPE(pCryptKey->aiAlgid) == ALG_TYPE_RSA) {
2002 if (pCryptKey->aiAlgid == CALG_RSA_SIGN) {
2003 SetLastError(NTE_BAD_KEY);
2006 encrypt_block_impl(pCryptKey->aiAlgid, &pCryptKey->context, pbData, pbData, RSAENH_DECRYPT);
2007 if (!unpad_data(pbData, pCryptKey->dwBlockLen, pbData, pdwDataLen, dwFlags)) return FALSE;
2010 SetLastError(NTE_BAD_TYPE);
2014 if (Final) setup_key(pCryptKey);
2016 if (is_valid_handle(&handle_table, hHash, RSAENH_MAGIC_HASH)) {
2017 if (!RSAENH_CPHashData(hProv, hHash, pbData, *pdwDataLen, 0)) return FALSE;
2023 /******************************************************************************
2024 * CPExportKey (RSAENH.@)
2026 * Export a key into a binary large object (BLOB).
2029 * hProv [I] Key container from which a key is to be exported.
2030 * hKey [I] Key to be exported.
2031 * hPubKey [I] Key used to encrypt sensitive BLOB data.
2032 * dwBlobType [I] SIMPLEBLOB, PUBLICKEYBLOB or PRIVATEKEYBLOB.
2033 * dwFlags [I] Currently none defined.
2034 * pbData [O] Pointer to a buffer where the BLOB will be written to.
2035 * pdwDataLen [I/O] I: Size of buffer at pbData, O: Size of BLOB
2041 BOOL WINAPI RSAENH_CPExportKey(HCRYPTPROV hProv, HCRYPTKEY hKey, HCRYPTKEY hPubKey,
2042 DWORD dwBlobType, DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen)
2044 CRYPTKEY *pCryptKey, *pPubKey;
2045 BLOBHEADER *pBlobHeader = (BLOBHEADER*)pbData;
2046 RSAPUBKEY *pRSAPubKey = (RSAPUBKEY*)(pBlobHeader+1);
2047 ALG_ID *pAlgid = (ALG_ID*)(pBlobHeader+1);
2050 TRACE("(hProv=%08lx, hKey=%08lx, hPubKey=%08lx, dwBlobType=%08lx, dwFlags=%08lx, pbData=%p,"
2051 "pdwDataLen=%p)\n", hProv, hKey, hPubKey, dwBlobType, dwFlags, pbData, pdwDataLen);
2053 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2055 SetLastError(NTE_BAD_UID);
2059 if (!lookup_handle(&handle_table, hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2061 SetLastError(NTE_BAD_KEY);
2065 if (dwFlags & CRYPT_SSL2_FALLBACK) {
2066 if (pCryptKey->aiAlgid != CALG_SSL2_MASTER) {
2067 SetLastError(NTE_BAD_KEY);
2072 switch ((BYTE)dwBlobType)
2075 if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pPubKey)){
2076 SetLastError(NTE_BAD_PUBLIC_KEY); /* FIXME: error_code? */
2080 if (!(GET_ALG_CLASS(pCryptKey->aiAlgid)&(ALG_CLASS_DATA_ENCRYPT|ALG_CLASS_MSG_ENCRYPT))) {
2081 SetLastError(NTE_BAD_KEY); /* FIXME: error code? */
2085 dwDataLen = sizeof(BLOBHEADER) + sizeof(ALG_ID) + pPubKey->dwBlockLen;
2087 if (*pdwDataLen < dwDataLen) {
2088 SetLastError(ERROR_MORE_DATA);
2089 *pdwDataLen = dwDataLen;
2093 pBlobHeader->bType = SIMPLEBLOB;
2094 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2095 pBlobHeader->reserved = 0;
2096 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2098 *pAlgid = pPubKey->aiAlgid;
2100 if (!pad_data(pCryptKey->abKeyValue, pCryptKey->dwKeyLen, (BYTE*)(pAlgid+1),
2101 pPubKey->dwBlockLen, dwFlags))
2106 encrypt_block_impl(pPubKey->aiAlgid, &pPubKey->context, (BYTE*)(pAlgid+1),
2107 (BYTE*)(pAlgid+1), RSAENH_ENCRYPT);
2109 *pdwDataLen = dwDataLen;
2113 if (is_valid_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY)) {
2114 SetLastError(NTE_BAD_KEY); /* FIXME: error code? */
2118 if ((pCryptKey->aiAlgid != CALG_RSA_KEYX) && (pCryptKey->aiAlgid != CALG_RSA_SIGN)) {
2119 SetLastError(NTE_BAD_KEY);
2123 dwDataLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) + pCryptKey->dwKeyLen;
2125 if (*pdwDataLen < dwDataLen) {
2126 SetLastError(ERROR_MORE_DATA);
2127 *pdwDataLen = dwDataLen;
2131 pBlobHeader->bType = PUBLICKEYBLOB;
2132 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2133 pBlobHeader->reserved = 0;
2134 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2136 pRSAPubKey->magic = RSAENH_MAGIC_RSA1;
2137 pRSAPubKey->bitlen = pCryptKey->dwKeyLen << 3;
2139 export_public_key_impl((BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2140 pCryptKey->dwKeyLen, &pRSAPubKey->pubexp);
2142 *pdwDataLen = dwDataLen;
2145 case PRIVATEKEYBLOB:
2146 if ((pCryptKey->aiAlgid != CALG_RSA_KEYX) && (pCryptKey->aiAlgid != CALG_RSA_SIGN)) {
2147 SetLastError(NTE_BAD_KEY);
2151 dwDataLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) +
2152 2 * pCryptKey->dwKeyLen + 5 * ((pCryptKey->dwKeyLen + 1) >> 1);
2154 if (*pdwDataLen < dwDataLen) {
2155 SetLastError(ERROR_MORE_DATA);
2156 *pdwDataLen = dwDataLen;
2160 pBlobHeader->bType = PRIVATEKEYBLOB;
2161 pBlobHeader->bVersion = CUR_BLOB_VERSION;
2162 pBlobHeader->reserved = 0;
2163 pBlobHeader->aiKeyAlg = pCryptKey->aiAlgid;
2165 pRSAPubKey->magic = RSAENH_MAGIC_RSA2;
2166 pRSAPubKey->bitlen = pCryptKey->dwKeyLen << 3;
2168 export_private_key_impl((BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2169 pCryptKey->dwKeyLen, &pRSAPubKey->pubexp);
2171 *pdwDataLen = dwDataLen;
2175 SetLastError(NTE_BAD_TYPE); /* FIXME: error code? */
2180 /******************************************************************************
2181 * CPImportKey (RSAENH.@)
2183 * Import a BLOB'ed key into a key container.
2186 * hProv [I] Key container into which the key is to be imported.
2187 * pbData [I] Pointer to a buffer which holds the BLOB.
2188 * dwDataLen [I] Length of data in buffer at pbData.
2189 * hPubKey [I] Key used to decrypt sensitive BLOB data.
2190 * dwFlags [I] Currently none defined.
2191 * phKey [O] Handle to the imported key.
2197 BOOL WINAPI RSAENH_CPImportKey(HCRYPTPROV hProv, CONST BYTE *pbData, DWORD dwDataLen,
2198 HCRYPTKEY hPubKey, DWORD dwFlags, HCRYPTKEY *phKey)
2200 CRYPTKEY *pCryptKey, *pPubKey;
2201 CONST BLOBHEADER *pBlobHeader = (CONST BLOBHEADER*)pbData;
2202 CONST RSAPUBKEY *pRSAPubKey = (CONST RSAPUBKEY*)(pBlobHeader+1);
2203 CONST ALG_ID *pAlgid = (CONST ALG_ID*)(pBlobHeader+1);
2204 CONST BYTE *pbKeyStream = (CONST BYTE*)(pAlgid + 1);
2208 TRACE("(hProv=%08lx, pbData=%p, dwDataLen=%ld, hPubKey=%08lx, dwFlags=%08lx, phKey=%p)\n",
2209 hProv, pbData, dwDataLen, hPubKey, dwFlags, phKey);
2211 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
2213 SetLastError(NTE_BAD_UID);
2217 if (dwDataLen < sizeof(BLOBHEADER) ||
2218 pBlobHeader->bVersion != CUR_BLOB_VERSION ||
2219 pBlobHeader->reserved != 0)
2221 SetLastError(NTE_BAD_DATA);
2225 switch (pBlobHeader->bType)
2227 case PRIVATEKEYBLOB:
2228 if ((dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY)) ||
2229 (pRSAPubKey->magic != RSAENH_MAGIC_RSA2) ||
2230 (dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) +
2231 (2 * pRSAPubKey->bitlen >> 3) + (5 * ((pRSAPubKey->bitlen+8)>>4))))
2233 SetLastError(NTE_BAD_DATA);
2237 *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, MAKELONG(0,pRSAPubKey->bitlen), &pCryptKey);
2238 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
2239 setup_key(pCryptKey);
2240 return import_private_key_impl((CONST BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2241 pRSAPubKey->bitlen/8, pRSAPubKey->pubexp);
2244 if ((dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY)) ||
2245 (pRSAPubKey->magic != RSAENH_MAGIC_RSA1) ||
2246 (dwDataLen < sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) + (pRSAPubKey->bitlen >> 3)))
2248 SetLastError(NTE_BAD_DATA);
2252 *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, MAKELONG(0,pRSAPubKey->bitlen), &pCryptKey);
2253 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
2254 setup_key(pCryptKey);
2255 return import_public_key_impl((CONST BYTE*)(pRSAPubKey+1), &pCryptKey->context,
2256 pRSAPubKey->bitlen >> 3, pRSAPubKey->pubexp);
2259 if (!lookup_handle(&handle_table, hPubKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pPubKey) ||
2260 pPubKey->aiAlgid != CALG_RSA_KEYX)
2262 SetLastError(NTE_BAD_PUBLIC_KEY); /* FIXME: error code? */
2266 if (dwDataLen < sizeof(BLOBHEADER)+sizeof(ALG_ID)+pPubKey->dwBlockLen)
2268 SetLastError(NTE_BAD_DATA); /* FIXME: error code */
2272 pbDecrypted = HeapAlloc(GetProcessHeap(), 0, pPubKey->dwBlockLen);
2273 if (!pbDecrypted) return FALSE;
2274 encrypt_block_impl(pPubKey->aiAlgid, &pPubKey->context, pbKeyStream, pbDecrypted,
2277 dwKeyLen = RSAENH_MAX_KEY_SIZE;
2278 if (!unpad_data(pbDecrypted, pPubKey->dwBlockLen, pbDecrypted, &dwKeyLen, dwFlags)) {
2279 HeapFree(GetProcessHeap(), 0, pbDecrypted);
2283 *phKey = new_key(hProv, pBlobHeader->aiKeyAlg, dwKeyLen<<19, &pCryptKey);
2284 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
2286 HeapFree(GetProcessHeap(), 0, pbDecrypted);
2289 memcpy(pCryptKey->abKeyValue, pbDecrypted, dwKeyLen);
2290 HeapFree(GetProcessHeap(), 0, pbDecrypted);
2291 setup_key(pCryptKey);
2295 SetLastError(NTE_BAD_TYPE); /* FIXME: error code? */
2300 /******************************************************************************
2301 * CPGenKey (RSAENH.@)
2303 * Generate a key in the key container
2306 * hProv [I] Key container for which a key is to be generated.
2307 * Algid [I] Crypto algorithm identifier for the key to be generated.
2308 * dwFlags [I] Upper 16 bits: Binary length of key. Lower 16 bits: Flags. See Notes
2309 * phKey [O] Handle to the generated key.
2316 * Flags currently not considered.
2319 * Private key-exchange- and signature-keys can be generated with Algid AT_KEYEXCHANGE
2320 * and AT_SIGNATURE values.
2322 BOOL WINAPI RSAENH_CPGenKey(HCRYPTPROV hProv, ALG_ID Algid, DWORD dwFlags, HCRYPTKEY *phKey)
2324 KEYCONTAINER *pKeyContainer;
2325 CRYPTKEY *pCryptKey;
2327 TRACE("(hProv=%08lx, aiAlgid=%d, dwFlags=%08lx, phKey=%p)\n", hProv, Algid, dwFlags, phKey);
2329 if (!lookup_handle(&handle_table, (unsigned int)hProv, RSAENH_MAGIC_CONTAINER,
2330 (OBJECTHDR**)&pKeyContainer))
2332 /* MSDN: hProv not containing valid context handle */
2333 SetLastError(NTE_BAD_UID);
2341 *phKey = new_key(hProv, CALG_RSA_SIGN, dwFlags, &pCryptKey);
2343 new_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen);
2344 setup_key(pCryptKey);
2345 if (Algid == AT_SIGNATURE) {
2346 RSAENH_CPDestroyKey(hProv, pKeyContainer->hSignatureKeyPair);
2347 copy_handle(&handle_table, *phKey, RSAENH_MAGIC_KEY,
2348 (unsigned int*)&pKeyContainer->hSignatureKeyPair);
2353 case AT_KEYEXCHANGE:
2355 *phKey = new_key(hProv, CALG_RSA_KEYX, dwFlags, &pCryptKey);
2357 new_key_impl(pCryptKey->aiAlgid, &pCryptKey->context, pCryptKey->dwKeyLen);
2358 setup_key(pCryptKey);
2359 if (Algid == AT_KEYEXCHANGE) {
2360 RSAENH_CPDestroyKey(hProv, pKeyContainer->hKeyExchangeKeyPair);
2361 copy_handle(&handle_table, *phKey, RSAENH_MAGIC_KEY,
2362 (unsigned int*)&pKeyContainer->hKeyExchangeKeyPair);
2372 case CALG_PCT1_MASTER:
2373 case CALG_SSL2_MASTER:
2374 case CALG_SSL3_MASTER:
2375 case CALG_TLS1_MASTER:
2376 *phKey = new_key(hProv, Algid, dwFlags, &pCryptKey);
2378 gen_rand_impl(pCryptKey->abKeyValue, RSAENH_MAX_KEY_SIZE);
2380 case CALG_SSL3_MASTER:
2381 pCryptKey->abKeyValue[0] = RSAENH_SSL3_VERSION_MAJOR;
2382 pCryptKey->abKeyValue[1] = RSAENH_SSL3_VERSION_MINOR;
2385 case CALG_TLS1_MASTER:
2386 pCryptKey->abKeyValue[0] = RSAENH_TLS1_VERSION_MAJOR;
2387 pCryptKey->abKeyValue[1] = RSAENH_TLS1_VERSION_MINOR;
2390 setup_key(pCryptKey);
2395 /* MSDN: Algorithm not supported specified by Algid */
2396 SetLastError(NTE_BAD_ALGID);
2400 return *phKey != (unsigned int)INVALID_HANDLE_VALUE;
2403 /******************************************************************************
2404 * CPGenRandom (RSAENH.@)
2406 * Generate a random byte stream.
2409 * hProv [I] Key container that is used to generate random bytes.
2410 * dwLen [I] Specifies the number of requested random data bytes.
2411 * pbBuffer [O] Random bytes will be stored here.
2417 BOOL WINAPI RSAENH_CPGenRandom(HCRYPTPROV hProv, DWORD dwLen, BYTE *pbBuffer)
2419 TRACE("(hProv=%08lx, dwLen=%ld, pbBuffer=%p)\n", hProv, dwLen, pbBuffer);
2421 if (!is_valid_handle(&handle_table, (unsigned int)hProv, RSAENH_MAGIC_CONTAINER))
2423 /* MSDN: hProv not containing valid context handle */
2424 SetLastError(NTE_BAD_UID);
2428 return gen_rand_impl(pbBuffer, dwLen);
2431 /******************************************************************************
2432 * CPGetHashParam (RSAENH.@)
2434 * Query parameters of an hash object.
2437 * hProv [I] The kea container, which the hash belongs to.
2438 * hHash [I] The hash object that is to be queried.
2439 * dwParam [I] Specifies the parameter that is to be queried.
2440 * pbData [I] Pointer to the buffer where the parameter value will be stored.
2441 * pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
2442 * dwFlags [I] None currently defined.
2449 * Valid dwParams are: HP_ALGID, HP_HASHSIZE, HP_HASHVALUE. The hash will be
2450 * finalized if HP_HASHVALUE is queried.
2452 BOOL WINAPI RSAENH_CPGetHashParam(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwParam, BYTE *pbData,
2453 DWORD *pdwDataLen, DWORD dwFlags)
2455 CRYPTHASH *pCryptHash;
2457 TRACE("(hProv=%08lx, hHash=%08lx, dwParam=%08lx, pbData=%p, pdwDataLen=%p, dwFlags=%08lx)\n",
2458 hProv, hHash, dwParam, pbData, pdwDataLen, dwFlags);
2460 if (!is_valid_handle(&handle_table, (unsigned int)hProv, RSAENH_MAGIC_CONTAINER))
2462 SetLastError(NTE_BAD_UID);
2468 SetLastError(NTE_BAD_FLAGS);
2472 if (!lookup_handle(&handle_table, (unsigned int)hHash, RSAENH_MAGIC_HASH,
2473 (OBJECTHDR**)&pCryptHash))
2475 SetLastError(NTE_BAD_HASH);
2481 SetLastError(ERROR_INVALID_PARAMETER);
2488 return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptHash->aiAlgid,
2492 return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptHash->dwHashSize,
2496 if (pCryptHash->aiAlgid == CALG_TLS1PRF) {
2497 return tls1_prf(hProv, pCryptHash->hKey, &pCryptHash->tpPRFParams.blobLabel,
2498 &pCryptHash->tpPRFParams.blobSeed, pbData, *pdwDataLen);
2501 if (pCryptHash->dwState == RSAENH_HASHSTATE_IDLE) {
2502 SetLastError(NTE_BAD_HASH_STATE);
2506 if (pbData && (pCryptHash->dwState != RSAENH_HASHSTATE_FINISHED))
2508 finalize_hash(pCryptHash);
2509 pCryptHash->dwState = RSAENH_HASHSTATE_FINISHED;
2512 return copy_param(pbData, pdwDataLen, (CONST BYTE*)pCryptHash->abHashValue,
2513 pCryptHash->dwHashSize);
2516 SetLastError(NTE_BAD_TYPE);
2521 /******************************************************************************
2522 * CPSetKeyParam (RSAENH.@)
2524 * Set a parameter of a key object
2527 * hProv [I] The key container to which the key belongs.
2528 * hKey [I] The key for which a parameter is to be set.
2529 * dwParam [I] Parameter type. See Notes.
2530 * pbData [I] Pointer to the parameter value.
2531 * dwFlags [I] Currently none defined.
2538 * Defined dwParam types are:
2539 * - KP_MODE: Values MODE_CBC, MODE_ECB, MODE_CFB.
2540 * - KP_MODE_BITS: Shift width for cipher feedback mode. (Currently ignored by MS CSP's)
2541 * - KP_PERMISSIONS: Or'ed combination of CRYPT_ENCRYPT, CRYPT_DECRYPT,
2542 * CRYPT_EXPORT, CRYPT_READ, CRYPT_WRITE, CRYPT_MAC
2543 * - KP_IV: Initialization vector
2545 BOOL WINAPI RSAENH_CPSetKeyParam(HCRYPTPROV hProv, HCRYPTKEY hKey, DWORD dwParam, BYTE *pbData,
2548 CRYPTKEY *pCryptKey;
2550 TRACE("(hProv=%08lx, hKey=%08lx, dwParam=%08lx, pbData=%p, dwFlags=%08lx)\n", hProv, hKey,
2551 dwParam, pbData, dwFlags);
2553 if (!is_valid_handle(&handle_table, (unsigned int)hProv, RSAENH_MAGIC_CONTAINER))
2555 SetLastError(NTE_BAD_UID);
2560 SetLastError(NTE_BAD_FLAGS);
2564 if (!lookup_handle(&handle_table, (unsigned int)hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2566 SetLastError(NTE_BAD_KEY);
2572 pCryptKey->dwMode = *(DWORD*)pbData;
2576 pCryptKey->dwModeBits = *(DWORD*)pbData;
2579 case KP_PERMISSIONS:
2580 pCryptKey->dwPermissions = *(DWORD*)pbData;
2584 memcpy(pCryptKey->abInitVector, pbData, pCryptKey->dwBlockLen);
2587 case KP_SCHANNEL_ALG:
2588 switch (((PSCHANNEL_ALG)pbData)->dwUse) {
2589 case SCHANNEL_ENC_KEY:
2590 memcpy(&pCryptKey->siSChannelInfo.saEncAlg, pbData, sizeof(SCHANNEL_ALG));
2593 case SCHANNEL_MAC_KEY:
2594 memcpy(&pCryptKey->siSChannelInfo.saMACAlg, pbData, sizeof(SCHANNEL_ALG));
2598 SetLastError(NTE_FAIL); /* FIXME: error code */
2603 case KP_CLIENT_RANDOM:
2604 return copy_data_blob(&pCryptKey->siSChannelInfo.blobClientRandom, (PCRYPT_DATA_BLOB)pbData);
2606 case KP_SERVER_RANDOM:
2607 return copy_data_blob(&pCryptKey->siSChannelInfo.blobServerRandom, (PCRYPT_DATA_BLOB)pbData);
2610 SetLastError(NTE_BAD_TYPE);
2615 /******************************************************************************
2616 * CPGetKeyParam (RSAENH.@)
2618 * Query a key parameter.
2621 * hProv [I] The key container, which the key belongs to.
2622 * hHash [I] The key object that is to be queried.
2623 * dwParam [I] Specifies the parameter that is to be queried.
2624 * pbData [I] Pointer to the buffer where the parameter value will be stored.
2625 * pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
2626 * dwFlags [I] None currently defined.
2633 * Defined dwParam types are:
2634 * - KP_MODE: Values MODE_CBC, MODE_ECB, MODE_CFB.
2635 * - KP_MODE_BITS: Shift width for cipher feedback mode.
2636 * (Currently ignored by MS CSP's - always eight)
2637 * - KP_PERMISSIONS: Or'ed combination of CRYPT_ENCRYPT, CRYPT_DECRYPT,
2638 * CRYPT_EXPORT, CRYPT_READ, CRYPT_WRITE, CRYPT_MAC
2639 * - KP_IV: Initialization vector.
2640 * - KP_KEYLEN: Bitwidth of the key.
2641 * - KP_BLOCKLEN: Size of a block cipher block.
2642 * - KP_SALT: Salt value.
2644 BOOL WINAPI RSAENH_CPGetKeyParam(HCRYPTPROV hProv, HCRYPTKEY hKey, DWORD dwParam, BYTE *pbData,
2645 DWORD *pdwDataLen, DWORD dwFlags)
2647 CRYPTKEY *pCryptKey;
2650 TRACE("(hProv=%08lx, hKey=%08lx, dwParam=%08lx, pbData=%p, pdwDataLen=%p dwFlags=%08lx)\n",
2651 hProv, hKey, dwParam, pbData, pdwDataLen, dwFlags);
2653 if (!is_valid_handle(&handle_table, (unsigned int)hProv, RSAENH_MAGIC_CONTAINER))
2655 SetLastError(NTE_BAD_UID);
2660 SetLastError(NTE_BAD_FLAGS);
2664 if (!lookup_handle(&handle_table, (unsigned int)hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pCryptKey))
2666 SetLastError(NTE_BAD_KEY);
2673 return copy_param(pbData, pdwDataLen, (CONST BYTE*)pCryptKey->abInitVector,
2674 pCryptKey->dwBlockLen);
2677 return copy_param(pbData, pdwDataLen,
2678 (CONST BYTE*)&pCryptKey->abKeyValue[pCryptKey->dwKeyLen], pCryptKey->dwSaltLen);
2681 dwBitLen = pCryptKey->dwKeyLen << 3;
2682 return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwBitLen, sizeof(DWORD));
2685 dwBitLen = pCryptKey->dwBlockLen << 3;
2686 return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwBitLen, sizeof(DWORD));
2689 return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptKey->dwMode, sizeof(DWORD));
2692 return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptKey->dwModeBits,
2695 case KP_PERMISSIONS:
2696 return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptKey->dwPermissions,
2700 return copy_param(pbData, pdwDataLen, (CONST BYTE*)&pCryptKey->aiAlgid, sizeof(DWORD));
2703 SetLastError(NTE_BAD_TYPE);
2708 /******************************************************************************
2709 * CPGetProvParam (RSAENH.@)
2711 * Query a CSP parameter.
2714 * hProv [I] The key container that is to be queried.
2715 * dwParam [I] Specifies the parameter that is to be queried.
2716 * pbData [I] Pointer to the buffer where the parameter value will be stored.
2717 * pdwDataLen [I/O] I: Buffer length at pbData, O: Length of the parameter value.
2718 * dwFlags [I] CRYPT_FIRST: Start enumeration (for PP_ENUMALGS{_EX}).
2724 * Defined dwParam types:
2725 * - PP_CONTAINER: Name of the key container.
2726 * - PP_NAME: Name of the cryptographic service provider.
2727 * - PP_SIG_KEYSIZE_INC: RSA signature keywidth granularity in bits.
2728 * - PP_KEYX_KEYSIZE_INC: RSA key-exchange keywidth granularity in bits.
2729 * - PP_ENUMALGS{_EX}: Query provider capabilities.
2731 BOOL WINAPI RSAENH_CPGetProvParam(HCRYPTPROV hProv, DWORD dwParam, BYTE *pbData,
2732 DWORD *pdwDataLen, DWORD dwFlags)
2734 KEYCONTAINER *pKeyContainer;
2735 PROV_ENUMALGS provEnumalgs;
2737 BYTE szRSABase[MAX_PATH];
2738 HKEY hKey, hRootKey;
2740 /* This is for dwParam 41, which does not seem to be documented
2741 * on MSDN. IE6 SP1 asks for it in the 'About' dialog, however.
2742 * Returning this BLOB seems to satisfy IE. The marked 0x00 seem
2743 * to be 'don't care's. If you know anything more specific about
2744 * provider parameter 41, please report to wine-devel@winehq.org */
2745 static CONST BYTE abWTF[96] = {
2746 0xb0, 0x25, 0x63, 0x86, 0x9c, 0xab, 0xb6, 0x37,
2747 0xe8, 0x82, /**/0x00,/**/ 0x72, 0x06, 0xb2, /**/0x00,/**/ 0x3b,
2748 0x60, 0x35, /**/0x00,/**/ 0x3b, 0x88, 0xce, /**/0x00,/**/ 0x82,
2749 0xbc, 0x7a, /**/0x00,/**/ 0xb7, 0x4f, 0x7e, /**/0x00,/**/ 0xde,
2750 0x92, 0xf1, /**/0x00,/**/ 0x83, 0xea, 0x5e, /**/0x00,/**/ 0xc8,
2751 0x12, 0x1e, 0xd4, 0x06, 0xf7, 0x66, /**/0x00,/**/ 0x01,
2752 0x29, 0xa4, /**/0x00,/**/ 0xf8, 0x24, 0x0c, /**/0x00,/**/ 0x33,
2753 0x06, 0x80, /**/0x00,/**/ 0x02, 0x46, 0x0b, /**/0x00,/**/ 0x6d,
2754 0x5b, 0xca, /**/0x00,/**/ 0x9a, 0x10, 0xf0, /**/0x00,/**/ 0x05,
2755 0x19, 0xd0, /**/0x00,/**/ 0x2c, 0xf6, 0x27, /**/0x00,/**/ 0xaa,
2756 0x7c, 0x6f, /**/0x00,/**/ 0xb9, 0xd8, 0x72, /**/0x00,/**/ 0x03,
2757 0xf3, 0x81, /**/0x00,/**/ 0xfa, 0xe8, 0x26, /**/0x00,/**/ 0xca
2760 TRACE("(hProv=%08lx, dwParam=%08lx, pbData=%p, pdwDataLen=%p, dwFlags=%08lx)\n",
2761 hProv, dwParam, pbData, pdwDataLen, dwFlags);
2764 SetLastError(ERROR_INVALID_PARAMETER);
2768 if (!lookup_handle(&handle_table, (unsigned int)hProv, RSAENH_MAGIC_CONTAINER,
2769 (OBJECTHDR**)&pKeyContainer))
2771 /* MSDN: hProv not containing valid context handle */
2772 SetLastError(NTE_BAD_UID);
2779 return copy_param(pbData, pdwDataLen, (CONST BYTE*)pKeyContainer->szName,
2780 strlen(pKeyContainer->szName)+1);
2783 return copy_param(pbData, pdwDataLen, (CONST BYTE*)pKeyContainer->szProvName,
2784 strlen(pKeyContainer->szProvName)+1);
2786 case PP_SIG_KEYSIZE_INC:
2787 case PP_KEYX_KEYSIZE_INC:
2789 return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwTemp, sizeof(dwTemp));
2792 dwTemp = CRYPT_IMPL_SOFTWARE;
2793 return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwTemp, sizeof(dwTemp));
2796 dwTemp = 0x00000200;
2797 return copy_param(pbData, pdwDataLen, (CONST BYTE*)&dwTemp, sizeof(dwTemp));
2799 case PP_ENUMCONTAINERS:
2800 if ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) pKeyContainer->dwEnumContainersCtr = 0;
2803 *pdwDataLen = (DWORD)MAX_PATH + 1;
2807 sprintf(szRSABase, RSAENH_REGKEY, "");
2809 if (dwFlags & CRYPT_MACHINE_KEYSET) {
2810 hRootKey = HKEY_LOCAL_MACHINE;
2812 hRootKey = HKEY_CURRENT_USER;
2815 if (RegOpenKeyExA(hRootKey, szRSABase, 0, KEY_READ, &hKey) != ERROR_SUCCESS)
2817 SetLastError(ERROR_NO_MORE_ITEMS);
2821 dwTemp = *pdwDataLen;
2822 switch (RegEnumKeyExA(hKey, pKeyContainer->dwEnumContainersCtr, pbData, &dwTemp,
2823 NULL, NULL, NULL, NULL))
2825 case ERROR_MORE_DATA:
2826 *pdwDataLen = (DWORD)MAX_PATH + 1;
2829 pKeyContainer->dwEnumContainersCtr++;
2833 case ERROR_NO_MORE_ITEMS:
2835 SetLastError(ERROR_NO_MORE_ITEMS);
2841 case PP_ENUMALGS_EX:
2842 if (((pKeyContainer->dwEnumAlgsCtr >= RSAENH_MAX_ENUMALGS-1) ||
2843 (!aProvEnumAlgsEx[pKeyContainer->dwPersonality]
2844 [pKeyContainer->dwEnumAlgsCtr+1].aiAlgid)) &&
2845 ((dwFlags & CRYPT_FIRST) != CRYPT_FIRST))
2847 SetLastError(ERROR_NO_MORE_ITEMS);
2851 if (dwParam == PP_ENUMALGS) {
2852 if (pbData && (*pdwDataLen >= sizeof(PROV_ENUMALGS)))
2853 pKeyContainer->dwEnumAlgsCtr = ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) ?
2854 0 : pKeyContainer->dwEnumAlgsCtr+1;
2856 provEnumalgs.aiAlgid = aProvEnumAlgsEx
2857 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].aiAlgid;
2858 provEnumalgs.dwBitLen = aProvEnumAlgsEx
2859 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].dwDefaultLen;
2860 provEnumalgs.dwNameLen = aProvEnumAlgsEx
2861 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].dwNameLen;
2862 memcpy(provEnumalgs.szName, aProvEnumAlgsEx
2863 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr].szName,
2866 return copy_param(pbData, pdwDataLen, (CONST BYTE*)&provEnumalgs,
2867 sizeof(PROV_ENUMALGS));
2869 if (pbData && (*pdwDataLen >= sizeof(PROV_ENUMALGS_EX)))
2870 pKeyContainer->dwEnumAlgsCtr = ((dwFlags & CRYPT_FIRST) == CRYPT_FIRST) ?
2871 0 : pKeyContainer->dwEnumAlgsCtr+1;
2873 return copy_param(pbData, pdwDataLen,
2874 (CONST BYTE*)&aProvEnumAlgsEx
2875 [pKeyContainer->dwPersonality][pKeyContainer->dwEnumAlgsCtr],
2876 sizeof(PROV_ENUMALGS_EX));
2879 case 41: /* Undocumented. Asked for by IE About dialog */
2880 return copy_param(pbData, pdwDataLen, abWTF, sizeof(abWTF));
2883 /* MSDN: Unknown parameter number in dwParam */
2884 SetLastError(NTE_BAD_TYPE);
2889 /******************************************************************************
2890 * CPDeriveKey (RSAENH.@)
2892 * Derives a key from a hash value.
2895 * hProv [I] Key container for which a key is to be generated.
2896 * Algid [I] Crypto algorithm identifier for the key to be generated.
2897 * hBaseData [I] Hash from whose value the key will be derived.
2898 * dwFlags [I] See Notes.
2899 * phKey [O] The generated key.
2907 * - CRYPT_EXPORTABLE: Key can be exported.
2908 * - CRYPT_NO_SALT: No salt is used for 40 bit keys.
2909 * - CRYPT_CREATE_SALT: Use remaining bits as salt value.
2911 BOOL WINAPI RSAENH_CPDeriveKey(HCRYPTPROV hProv, ALG_ID Algid, HCRYPTHASH hBaseData,
2912 DWORD dwFlags, HCRYPTKEY *phKey)
2914 CRYPTKEY *pCryptKey, *pMasterKey;
2915 CRYPTHASH *pCryptHash;
2916 BYTE abHashValue[RSAENH_MAX_HASH_SIZE*2];
2919 TRACE("(hProv=%08lx, Algid=%d, hBaseData=%08lx, dwFlags=%08lx phKey=%p)\n", hProv, Algid,
2920 hBaseData, dwFlags, phKey);
2922 if (!is_valid_handle(&handle_table, (unsigned int)hProv, RSAENH_MAGIC_CONTAINER))
2924 SetLastError(NTE_BAD_UID);
2928 if (!lookup_handle(&handle_table, (unsigned int)hBaseData, RSAENH_MAGIC_HASH,
2929 (OBJECTHDR**)&pCryptHash))
2931 SetLastError(NTE_BAD_HASH);
2937 SetLastError(ERROR_INVALID_PARAMETER);
2941 switch (GET_ALG_CLASS(Algid))
2943 case ALG_CLASS_DATA_ENCRYPT:
2944 *phKey = new_key(hProv, Algid, dwFlags, &pCryptKey);
2945 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
2948 * We derive the key material from the hash.
2949 * If the hash value is not large enough for the claimed key, we have to construct
2950 * a larger binary value based on the hash. This is documented in MSDN: CryptDeriveKey.
2952 dwLen = RSAENH_MAX_HASH_SIZE;
2953 RSAENH_CPGetHashParam(pCryptHash->hProv, hBaseData, HP_HASHVAL, abHashValue, &dwLen, 0);
2955 if (dwLen < pCryptKey->dwKeyLen) {
2956 BYTE pad1[RSAENH_HMAC_DEF_PAD_LEN], pad2[RSAENH_HMAC_DEF_PAD_LEN];
2957 BYTE old_hashval[RSAENH_MAX_HASH_SIZE];
2960 memcpy(old_hashval, pCryptHash->abHashValue, RSAENH_MAX_HASH_SIZE);
2962 for (i=0; i<RSAENH_HMAC_DEF_PAD_LEN; i++) {
2963 pad1[i] = RSAENH_HMAC_DEF_IPAD_CHAR ^ (i<dwLen ? abHashValue[i] : 0);
2964 pad2[i] = RSAENH_HMAC_DEF_OPAD_CHAR ^ (i<dwLen ? abHashValue[i] : 0);
2967 init_hash(pCryptHash);
2968 update_hash(pCryptHash, pad1, RSAENH_HMAC_DEF_PAD_LEN);
2969 finalize_hash(pCryptHash);
2970 memcpy(abHashValue, pCryptHash->abHashValue, pCryptHash->dwHashSize);
2972 init_hash(pCryptHash);
2973 update_hash(pCryptHash, pad2, RSAENH_HMAC_DEF_PAD_LEN);
2974 finalize_hash(pCryptHash);
2975 memcpy(abHashValue+pCryptHash->dwHashSize, pCryptHash->abHashValue,
2976 pCryptHash->dwHashSize);
2978 memcpy(pCryptHash->abHashValue, old_hashval, RSAENH_MAX_HASH_SIZE);
2981 memcpy(pCryptKey->abKeyValue, abHashValue,
2982 RSAENH_MIN(pCryptKey->dwKeyLen, sizeof(pCryptKey->abKeyValue)));
2985 case ALG_CLASS_MSG_ENCRYPT:
2986 if (!lookup_handle(&handle_table, pCryptHash->hKey, RSAENH_MAGIC_KEY,
2987 (OBJECTHDR**)&pMasterKey))
2989 SetLastError(NTE_FAIL); /* FIXME error code */
2995 /* See RFC 2246, chapter 6.3 Key calculation */
2996 case CALG_SCHANNEL_ENC_KEY:
2997 *phKey = new_key(hProv, pMasterKey->siSChannelInfo.saEncAlg.Algid,
2998 MAKELONG(LOWORD(dwFlags),pMasterKey->siSChannelInfo.saEncAlg.cBits),
3000 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
3001 memcpy(pCryptKey->abKeyValue,
3002 pCryptHash->abHashValue + (
3003 2 * (pMasterKey->siSChannelInfo.saMACAlg.cBits / 8) +
3004 ((dwFlags & CRYPT_SERVER) ?
3005 (pMasterKey->siSChannelInfo.saEncAlg.cBits / 8) : 0)),
3006 pMasterKey->siSChannelInfo.saEncAlg.cBits / 8);
3007 memcpy(pCryptKey->abInitVector,
3008 pCryptHash->abHashValue + (
3009 2 * (pMasterKey->siSChannelInfo.saMACAlg.cBits / 8) +
3010 2 * (pMasterKey->siSChannelInfo.saEncAlg.cBits / 8) +
3011 ((dwFlags & CRYPT_SERVER) ? pCryptKey->dwBlockLen : 0)),
3012 pCryptKey->dwBlockLen);
3015 case CALG_SCHANNEL_MAC_KEY:
3016 *phKey = new_key(hProv, Algid,
3017 MAKELONG(LOWORD(dwFlags),pMasterKey->siSChannelInfo.saMACAlg.cBits),
3019 if (*phKey == (HCRYPTKEY)INVALID_HANDLE_VALUE) return FALSE;
3020 memcpy(pCryptKey->abKeyValue,
3021 pCryptHash->abHashValue + ((dwFlags & CRYPT_SERVER) ?
3022 pMasterKey->siSChannelInfo.saMACAlg.cBits / 8 : 0),
3023 pMasterKey->siSChannelInfo.saMACAlg.cBits / 8);
3027 SetLastError(NTE_BAD_ALGID);
3033 SetLastError(NTE_BAD_ALGID);
3037 setup_key(pCryptKey);
3041 /******************************************************************************
3042 * CPGetUserKey (RSAENH.@)
3044 * Returns a handle to the user's private key-exchange- or signature-key.
3047 * hProv [I] The key container from which a user key is requested.
3048 * dwKeySpec [I] AT_KEYEXCHANGE or AT_SIGNATURE
3049 * phUserKey [O] Handle to the requested key or INVALID_HANDLE_VALUE in case of failure.
3056 * A newly created key container does not contain private user key. Create them with CPGenKey.
3058 BOOL WINAPI RSAENH_CPGetUserKey(HCRYPTPROV hProv, DWORD dwKeySpec, HCRYPTKEY *phUserKey)
3060 KEYCONTAINER *pKeyContainer;
3062 TRACE("(hProv=%08lx, dwKeySpec=%08lx, phUserKey=%p)\n", hProv, dwKeySpec, phUserKey);
3064 if (!lookup_handle(&handle_table, (unsigned int)hProv, RSAENH_MAGIC_CONTAINER,
3065 (OBJECTHDR**)&pKeyContainer))
3067 /* MSDN: hProv not containing valid context handle */
3068 SetLastError(NTE_BAD_UID);
3074 case AT_KEYEXCHANGE:
3075 copy_handle(&handle_table, pKeyContainer->hKeyExchangeKeyPair, RSAENH_MAGIC_KEY,
3076 (unsigned int*)phUserKey);
3080 copy_handle(&handle_table, pKeyContainer->hSignatureKeyPair, RSAENH_MAGIC_KEY,
3081 (unsigned int*)phUserKey);
3085 *phUserKey = (HCRYPTKEY)INVALID_HANDLE_VALUE;
3088 if (*phUserKey == (HCRYPTKEY)INVALID_HANDLE_VALUE)
3090 /* MSDN: dwKeySpec parameter specifies nonexistent key */
3091 SetLastError(NTE_NO_KEY);
3098 /******************************************************************************
3099 * CPHashData (RSAENH.@)
3101 * Updates a hash object with the given data.
3104 * hProv [I] Key container to which the hash object belongs.
3105 * hHash [I] Hash object which is to be updated.
3106 * pbData [I] Pointer to data with which the hash object is to be updated.
3107 * dwDataLen [I] Length of the data.
3108 * dwFlags [I] Currently none defined.
3115 * The actual hash value is queried with CPGetHashParam, which will finalize
3116 * the hash. Updating a finalized hash will fail with a last error NTE_BAD_HASH_STATE.
3118 BOOL WINAPI RSAENH_CPHashData(HCRYPTPROV hProv, HCRYPTHASH hHash, CONST BYTE *pbData,
3119 DWORD dwDataLen, DWORD dwFlags)
3121 CRYPTHASH *pCryptHash;
3123 TRACE("(hProv=%08lx, hHash=%08lx, pbData=%p, dwDataLen=%ld, dwFlags=%08lx)\n",
3124 hProv, hHash, pbData, dwDataLen, dwFlags);
3128 SetLastError(NTE_BAD_FLAGS);
3132 if (!lookup_handle(&handle_table, (unsigned int)hHash, RSAENH_MAGIC_HASH,
3133 (OBJECTHDR**)&pCryptHash))
3135 SetLastError(NTE_BAD_HASH);
3139 if (!get_algid_info(hProv, pCryptHash->aiAlgid) || pCryptHash->aiAlgid == CALG_SSL3_SHAMD5)
3141 SetLastError(NTE_BAD_ALGID);
3145 if (pCryptHash->dwState == RSAENH_HASHSTATE_IDLE)
3146 pCryptHash->dwState = RSAENH_HASHSTATE_HASHING;
3148 if (pCryptHash->dwState != RSAENH_HASHSTATE_HASHING)
3150 SetLastError(NTE_BAD_HASH_STATE);
3154 update_hash(pCryptHash, pbData, dwDataLen);
3158 /******************************************************************************
3159 * CPHashSessionKey (RSAENH.@)
3161 * Updates a hash object with the binary representation of a symmetric key.
3164 * hProv [I] Key container to which the hash object belongs.
3165 * hHash [I] Hash object which is to be updated.
3166 * hKey [I] The symmetric key, whose binary value will be added to the hash.
3167 * dwFlags [I] CRYPT_LITTLE_ENDIAN, if the binary key value shall be interpreted as little endian.
3173 BOOL WINAPI RSAENH_CPHashSessionKey(HCRYPTPROV hProv, HCRYPTHASH hHash, HCRYPTKEY hKey,
3176 BYTE abKeyValue[RSAENH_MAX_KEY_SIZE], bTemp;
3180 TRACE("(hProv=%08lx, hHash=%08lx, hKey=%08lx, dwFlags=%08lx)\n", hProv, hHash, hKey, dwFlags);
3182 if (!lookup_handle(&handle_table, (unsigned int)hKey, RSAENH_MAGIC_KEY, (OBJECTHDR**)&pKey) ||
3183 (GET_ALG_CLASS(pKey->aiAlgid) != ALG_CLASS_DATA_ENCRYPT))
3185 SetLastError(NTE_BAD_KEY);
3189 if (dwFlags & ~CRYPT_LITTLE_ENDIAN) {
3190 SetLastError(NTE_BAD_FLAGS);
3194 memcpy(abKeyValue, pKey->abKeyValue, pKey->dwKeyLen);
3195 if (!(dwFlags & CRYPT_LITTLE_ENDIAN)) {
3196 for (i=0; i<pKey->dwKeyLen/2; i++) {
3197 bTemp = abKeyValue[i];
3198 abKeyValue[i] = abKeyValue[pKey->dwKeyLen-i-1];
3199 abKeyValue[pKey->dwKeyLen-i-1] = bTemp;
3203 return RSAENH_CPHashData(hProv, hHash, abKeyValue, pKey->dwKeyLen, 0);
3206 /******************************************************************************
3207 * CPReleaseContext (RSAENH.@)
3209 * Release a key container.
3212 * hProv [I] Key container to be released.
3213 * dwFlags [I] Currently none defined.
3219 BOOL WINAPI RSAENH_CPReleaseContext(HCRYPTPROV hProv, DWORD dwFlags)
3221 TRACE("(hProv=%08lx, dwFlags=%08lx)\n", hProv, dwFlags);
3223 if (!release_handle(&handle_table, (unsigned int)hProv, RSAENH_MAGIC_CONTAINER))
3225 /* MSDN: hProv not containing valid context handle */
3226 SetLastError(NTE_BAD_UID);
3231 SetLastError(NTE_BAD_FLAGS);
3238 /******************************************************************************
3239 * CPSetHashParam (RSAENH.@)
3241 * Set a parameter of a hash object
3244 * hProv [I] The key container to which the key belongs.
3245 * hHash [I] The hash object for which a parameter is to be set.
3246 * dwParam [I] Parameter type. See Notes.
3247 * pbData [I] Pointer to the parameter value.
3248 * dwFlags [I] Currently none defined.
3255 * Currently only the HP_HMAC_INFO dwParam type is defined.
3256 * The HMAC_INFO struct will be deep copied into the hash object.
3257 * See Internet RFC 2104 for details on the HMAC algorithm.
3259 BOOL WINAPI RSAENH_CPSetHashParam(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwParam,
3260 BYTE *pbData, DWORD dwFlags)
3262 CRYPTHASH *pCryptHash;
3263 CRYPTKEY *pCryptKey;
3266 TRACE("(hProv=%08lx, hHash=%08lx, dwParam=%08lx, pbData=%p, dwFlags=%08lx)\n",
3267 hProv, hHash, dwParam, pbData, dwFlags);
3269 if (!is_valid_handle(&handle_table, (unsigned int)hProv, RSAENH_MAGIC_CONTAINER))
3271 SetLastError(NTE_BAD_UID);
3276 SetLastError(NTE_BAD_FLAGS);
3280 if (!lookup_handle(&handle_table, (unsigned int)hHash, RSAENH_MAGIC_HASH,
3281 (OBJECTHDR**)&pCryptHash))
3283 SetLastError(NTE_BAD_HASH);
3289 free_hmac_info(pCryptHash->pHMACInfo);
3290 if (!copy_hmac_info(&pCryptHash->pHMACInfo, (PHMAC_INFO)pbData)) return FALSE;
3292 if (!lookup_handle(&handle_table, pCryptHash->hKey, RSAENH_MAGIC_KEY,
3293 (OBJECTHDR**)&pCryptKey))
3295 SetLastError(NTE_FAIL); /* FIXME: correct error code? */
3299 for (i=0; i<RSAENH_MIN(pCryptKey->dwKeyLen,pCryptHash->pHMACInfo->cbInnerString); i++) {
3300 pCryptHash->pHMACInfo->pbInnerString[i] ^= pCryptKey->abKeyValue[i];
3302 for (i=0; i<RSAENH_MIN(pCryptKey->dwKeyLen,pCryptHash->pHMACInfo->cbOuterString); i++) {
3303 pCryptHash->pHMACInfo->pbOuterString[i] ^= pCryptKey->abKeyValue[i];
3306 init_hash(pCryptHash);
3310 memcpy(pCryptHash->abHashValue, pbData, pCryptHash->dwHashSize);
3311 pCryptHash->dwState = RSAENH_HASHSTATE_FINISHED;
3314 case HP_TLS1PRF_SEED:
3315 return copy_data_blob(&pCryptHash->tpPRFParams.blobSeed, (PCRYPT_DATA_BLOB)pbData);
3317 case HP_TLS1PRF_LABEL:
3318 return copy_data_blob(&pCryptHash->tpPRFParams.blobLabel, (PCRYPT_DATA_BLOB)pbData);
3321 SetLastError(NTE_BAD_TYPE);
3326 /******************************************************************************
3327 * CPSetProvParam (RSAENH.@)
3329 BOOL WINAPI RSAENH_CPSetProvParam(HCRYPTPROV hProv, DWORD dwParam, BYTE *pbData, DWORD dwFlags)
3335 /******************************************************************************
3336 * CPSignHash (RSAENH.@)
3338 * Sign a hash object
3341 * hProv [I] The key container, to which the hash object belongs.
3342 * hHash [I] The hash object to be signed.
3343 * dwKeySpec [I] AT_SIGNATURE or AT_KEYEXCHANGE: Key used to generate the signature.
3344 * sDescription [I] Should be NULL for security reasons.
3345 * dwFlags [I] 0, CRYPT_NOHASHOID or CRYPT_X931_FORMAT: Format of the signature.
3346 * pbSignature [O] Buffer, to which the signature will be stored. May be NULL to query SigLen.
3347 * pdwSigLen [I/O] Size of the buffer (in), Length of the signature (out)
3353 BOOL WINAPI RSAENH_CPSignHash(HCRYPTPROV hProv, HCRYPTHASH hHash, DWORD dwKeySpec,
3354 LPCWSTR sDescription, DWORD dwFlags, BYTE *pbSignature,
3357 HCRYPTKEY hCryptKey;
3358 CRYPTKEY *pCryptKey;
3360 BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
3363 TRACE("(hProv=%08lx, hHash=%08lx, dwKeySpec=%08lx, sDescription=%s, dwFlags=%08lx, "
3364 "pbSignature=%p, pdwSigLen=%p)\n", hProv, hHash, dwKeySpec, debugstr_w(sDescription),
3365 dwFlags, pbSignature, pdwSigLen);
3367 if (dwFlags & ~(CRYPT_NOHASHOID|CRYPT_X931_FORMAT)) {
3368 SetLastError(NTE_BAD_FLAGS);
3372 if (!RSAENH_CPGetUserKey(hProv, dwKeySpec, &hCryptKey)) return FALSE;
3374 if (!lookup_handle(&handle_table, (unsigned int)hCryptKey, RSAENH_MAGIC_KEY,
3375 (OBJECTHDR**)&pCryptKey))
3377 SetLastError(NTE_NO_KEY);
3382 *pdwSigLen = pCryptKey->dwKeyLen;
3385 if (pCryptKey->dwKeyLen > *pdwSigLen)
3387 SetLastError(ERROR_MORE_DATA);
3388 *pdwSigLen = pCryptKey->dwKeyLen;
3391 *pdwSigLen = pCryptKey->dwKeyLen;
3394 if (!RSAENH_CPHashData(hProv, hHash, (CONST BYTE*)sDescription,
3395 (DWORD)lstrlenW(sDescription)*sizeof(WCHAR), 0))
3401 dwHashLen = sizeof(DWORD);
3402 if (!RSAENH_CPGetHashParam(hProv, hHash, HP_ALGID, (BYTE*)&aiAlgid, &dwHashLen, 0)) return FALSE;
3404 dwHashLen = RSAENH_MAX_HASH_SIZE;
3405 if (!RSAENH_CPGetHashParam(hProv, hHash, HP_HASHVAL, abHashValue, &dwHashLen, 0)) return FALSE;
3408 if (!build_hash_signature(pbSignature, *pdwSigLen, aiAlgid, abHashValue, dwHashLen, dwFlags)) {
3412 return encrypt_block_impl(pCryptKey->aiAlgid, &pCryptKey->context, pbSignature, pbSignature, RSAENH_ENCRYPT);
3415 /******************************************************************************
3416 * CPVerifySignature (RSAENH.@)
3418 * Verify the signature of a hash object.
3421 * hProv [I] The key container, to which the hash belongs.
3422 * hHash [I] The hash for which the signature is verified.
3423 * pbSignature [I] The binary signature.
3424 * dwSigLen [I] Length of the signature BLOB.
3425 * hPubKey [I] Public key used to verify the signature.
3426 * sDescription [I] Should be NULL for security reasons.
3427 * dwFlags [I] 0, CRYPT_NOHASHOID or CRYPT_X931_FORMAT: Format of the signature.
3430 * Success: TRUE (Signature is valid)
3431 * Failure: FALSE (GetLastError() == NTE_BAD_SIGNATURE, if signature is invalid)
3433 BOOL WINAPI RSAENH_CPVerifySignature(HCRYPTPROV hProv, HCRYPTHASH hHash, CONST BYTE *pbSignature,
3434 DWORD dwSigLen, HCRYPTKEY hPubKey, LPCWSTR sDescription,
3437 BYTE *pbConstructed = NULL, *pbDecrypted = NULL;
3438 CRYPTKEY *pCryptKey;
3441 BYTE abHashValue[RSAENH_MAX_HASH_SIZE];
3444 TRACE("(hProv=%08lx, hHash=%08lx, pbSignature=%p, dwSigLen=%ld, hPubKey=%08lx, sDescription=%s, "
3445 "dwFlags=%08lx)\n", hProv, hHash, pbSignature, dwSigLen, hPubKey, debugstr_w(sDescription),
3448 if (dwFlags & ~(CRYPT_NOHASHOID|CRYPT_X931_FORMAT)) {
3449 SetLastError(NTE_BAD_FLAGS);
3453 if (!is_valid_handle(&handle_table, hProv, RSAENH_MAGIC_CONTAINER))
3455 SetLastError(NTE_BAD_UID);
3459 if (!lookup_handle(&handle_table, (unsigned int)hPubKey, RSAENH_MAGIC_KEY,
3460 (OBJECTHDR**)&pCryptKey))
3462 SetLastError(NTE_BAD_KEY);
3467 if (!RSAENH_CPHashData(hProv, hHash, (CONST BYTE*)sDescription,
3468 (DWORD)lstrlenW(sDescription)*sizeof(WCHAR), 0))
3474 dwHashLen = sizeof(DWORD);
3475 if (!RSAENH_CPGetHashParam(hProv, hHash, HP_ALGID, (BYTE*)&aiAlgid, &dwHashLen, 0)) return FALSE;
3477 dwHashLen = RSAENH_MAX_HASH_SIZE;
3478 if (!RSAENH_CPGetHashParam(hProv, hHash, HP_HASHVAL, abHashValue, &dwHashLen, 0)) return FALSE;
3480 pbConstructed = HeapAlloc(GetProcessHeap(), 0, dwSigLen);
3481 if (!pbConstructed) {
3482 SetLastError(NTE_NO_MEMORY);
3486 pbDecrypted = HeapAlloc(GetProcessHeap(), 0, dwSigLen);
3488 SetLastError(NTE_NO_MEMORY);
3492 if (!encrypt_block_impl(pCryptKey->aiAlgid, &pCryptKey->context, pbSignature, pbDecrypted,
3498 if (!build_hash_signature(pbConstructed, dwSigLen, aiAlgid, abHashValue, dwHashLen, dwFlags)) {
3502 if (memcmp(pbDecrypted, pbConstructed, dwSigLen)) {
3503 SetLastError(NTE_BAD_SIGNATURE);
3509 HeapFree(GetProcessHeap(), 0, pbConstructed);
3510 HeapFree(GetProcessHeap(), 0, pbDecrypted);
3514 static const WCHAR szProviderKeys[4][97] = {
3515 { 'S','o','f','t','w','a','r','e','\\',
3516 'M','i','c','r','o','s','o','f','t','\\','C','r','y','p','t','o','g','r',
3517 'a','p','h','y','\\','D','e','f','a','u','l','t','s','\\','P','r','o','v',
3518 'i','d','e','r','\\','M','i','c','r','o','s','o','f','t',' ','B','a','s',
3519 'e',' ','C','r','y','p','t','o','g','r','a','p','h','i','c',' ','P','r',
3520 'o','v','i','d','e','r',' ','v','1','.','0',0 },
3521 { 'S','o','f','t','w','a','r','e','\\',
3522 'M','i','c','r','o','s','o','f','t','\\','C','r','y','p','t','o','g','r',
3523 'a','p','h','y','\\','D','e','f','a','u','l','t','s','\\','P','r','o','v',
3524 'i','d','e','r','\\','M','i','c','r','o','s','o','f','t',' ',
3525 'E','n','h','a','n','c','e','d',
3526 ' ','C','r','y','p','t','o','g','r','a','p','h','i','c',' ','P','r',
3527 'o','v','i','d','e','r',' ','v','1','.','0',0 },
3528 { 'S','o','f','t','w','a','r','e','\\',
3529 'M','i','c','r','o','s','o','f','t','\\','C','r','y','p','t','o','g','r',
3530 'a','p','h','y','\\','D','e','f','a','u','l','t','s','\\','P','r','o','v',
3531 'i','d','e','r','\\','M','i','c','r','o','s','o','f','t',' ','S','t','r','o','n','g',
3532 ' ','C','r','y','p','t','o','g','r','a','p','h','i','c',' ','P','r',
3533 'o','v','i','d','e','r',0 },
3534 { 'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\',
3535 'C','r','y','p','t','o','g','r','a','p','h','y','\\','D','e','f','a','u','l','t','s','\\',
3536 'P','r','o','v','i','d','e','r','\\','M','i','c','r','o','s','o','f','t',' ',
3537 'R','S','A',' ','S','C','h','a','n','n','e','l',' ',
3538 'C','r','y','p','t','o','g','r','a','p','h','i','c',' ','P','r','o','v','i','d','e','r',0 }
3540 static const WCHAR szDefaultKeys[2][65] = {
3541 { 'S','o','f','t','w','a','r','e','\\',
3542 'M','i','c','r','o','s','o','f','t','\\','C','r','y','p','t','o','g','r',
3543 'a','p','h','y','\\','D','e','f','a','u','l','t','s','\\','P','r','o','v',
3544 'i','d','e','r',' ','T','y','p','e','s','\\','T','y','p','e',' ','0','0','1',0 },
3545 { 'S','o','f','t','w','a','r','e','\\',
3546 'M','i','c','r','o','s','o','f','t','\\','C','r','y','p','t','o','g','r',
3547 'a','p','h','y','\\','D','e','f','a','u','l','t','s','\\','P','r','o','v',
3548 'i','d','e','r',' ','T','y','p','e','s','\\','T','y','p','e',' ','0','1','2',0 }
3552 /******************************************************************************
3553 * DllRegisterServer (RSAENH.@)
3555 * Dll self registration.
3564 * Registers the following keys:
3565 * - HKLM\Software\Microsoft\Cryptography\Defaults\Provider\
3566 * Microsoft Base Cryptographic Provider v1.0
3567 * - HKLM\Software\Microsoft\Cryptography\Defaults\Provider\
3568 * Microsoft Enhanced Cryptographic Provider
3569 * - HKLM\Software\Microsoft\Cryptography\Defaults\Provider\
3570 * Microsoft Strong Cryptographpic Provider
3571 * - HKLM\Software\Microsoft\Cryptography\Defaults\Provider Types\Type 001
3573 HRESULT WINAPI RSAENH_DllRegisterServer()
3580 for (i=0; i<4; i++) {
3581 apiRet = RegCreateKeyExW(HKEY_LOCAL_MACHINE, szProviderKeys[i], 0, NULL,
3582 REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &key, &dp);
3584 if (apiRet == ERROR_SUCCESS)
3586 if (dp == REG_CREATED_NEW_KEY)
3588 static const WCHAR szImagePath[] = { 'I','m','a','g','e',' ','P','a','t','h',0 };
3589 static const WCHAR szRSABase[] = { 'r','s','a','e','n','h','.','d','l','l',0 };
3590 static const WCHAR szType[] = { 'T','y','p','e',0 };
3591 static const WCHAR szSignature[] = { 'S','i','g','n','a','t','u','r','e',0 };
3592 DWORD type = (i == 3) ? PROV_RSA_SCHANNEL : PROV_RSA_FULL;
3593 DWORD sign = 0xdeadbeef;
3594 RegSetValueExW(key, szImagePath, 0, REG_SZ, (LPBYTE)szRSABase,
3595 (lstrlenW(szRSABase) + 1) * sizeof(WCHAR));
3596 RegSetValueExW(key, szType, 0, REG_DWORD, (LPBYTE)&type, sizeof(type));
3597 RegSetValueExW(key, szSignature, 0, REG_BINARY, (LPBYTE)&sign, sizeof(sign));
3603 for (i=0; i<2; i++) {
3604 apiRet = RegCreateKeyExW(HKEY_LOCAL_MACHINE, szDefaultKeys[i], 0, NULL,
3605 REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &key, &dp);
3606 if (apiRet == ERROR_SUCCESS)
3608 if (dp == REG_CREATED_NEW_KEY)
3610 static const WCHAR szName[] = { 'N','a','m','e',0 };
3611 static const WCHAR szRSAName[2][46] = {
3612 { 'M','i','c','r','o','s','o','f','t',' ', 'B','a','s','e',' ',
3613 'C','r','y','p','t','o','g','r','a','p','h','i','c',' ',
3614 'P','r','o','v','i','d','e','r',' ','v','1','.','0',0 },
3615 { 'M','i','c','r','o','s','o','f','t',' ','R','S','A',' ',
3616 'S','C','h','a','n','n','e','l',' ',
3617 'C','r','y','p','t','o','g','r','a','p','h','i','c',' ',
3618 'P','r','o','v','i','d','e','r',0 } };
3619 static const WCHAR szTypeName[] = { 'T','y','p','e','N','a','m','e',0 };
3620 static const WCHAR szRSATypeName[2][38] = {
3621 { 'R','S','A',' ','F','u','l','l',' ',
3622 '(','S','i','g','n','a','t','u','r','e',' ','a','n','d',' ',
3623 'K','e','y',' ','E','x','c','h','a','n','g','e',')',0 },
3624 { 'R','S','A',' ','S','C','h','a','n','n','e','l',0 } };
3626 RegSetValueExW(key, szName, 0, REG_SZ, (LPBYTE)szRSAName[i], sizeof(szRSAName));
3627 RegSetValueExW(key, szTypeName, 0, REG_SZ,
3628 (LPBYTE)szRSATypeName[i],sizeof(szRSATypeName));
3634 return HRESULT_FROM_WIN32(apiRet);
3637 /******************************************************************************
3638 * DllUnregisterServer (RSAENH.@)
3640 * Dll self unregistration.
3648 * For the relevant keys see DllRegisterServer.
3650 HRESULT WINAPI RSAENH_DllUnregisterServer()
3652 RegDeleteKeyW(HKEY_LOCAL_MACHINE, szProviderKeys[0]);
3653 RegDeleteKeyW(HKEY_LOCAL_MACHINE, szProviderKeys[1]);
3654 RegDeleteKeyW(HKEY_LOCAL_MACHINE, szProviderKeys[2]);
3655 RegDeleteKeyW(HKEY_LOCAL_MACHINE, szProviderKeys[3]);
3656 RegDeleteKeyW(HKEY_LOCAL_MACHINE, szDefaultKeys[0]);
3657 RegDeleteKeyW(HKEY_LOCAL_MACHINE, szDefaultKeys[1]);