当前位置: 首页>>代码示例>>C++>>正文


C++ CryptDestroyKey函数代码示例

本文整理汇总了C++中CryptDestroyKey函数的典型用法代码示例。如果您正苦于以下问题:C++ CryptDestroyKey函数的具体用法?C++ CryptDestroyKey怎么用?C++ CryptDestroyKey使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了CryptDestroyKey函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: goodB2G

/* goodB2G() - use badsource and goodsink by reversing the blocks on the second goto statement */
static void goodB2G()
{
    wchar_t * data;
    wchar_t dataBuffer[100] = L"";
    data = dataBuffer;
    goto source;
source:
    {
        FILE *pFile;
        pFile = fopen("passwords.txt", "r");
        if (pFile != NULL)
        {
            /* POTENTIAL FLAW: Read the password from a file */
            if (fgetws(data, 100, pFile) == NULL)
            {
                data[0] = L'\0';
            }
            fclose(pFile);
        }
        else
        {
            data[0] = L'\0';
        }
    }
    goto sink;
sink:
    {
        HANDLE pHandle;
        wchar_t * username = L"User";
        wchar_t * domain = L"Domain";
        char hashData[100] = HASH_INPUT;
        HCRYPTPROV hCryptProv = 0;
        HCRYPTHASH hHash = 0;
        HCRYPTKEY hKey = 0;
        do
        {
            BYTE payload[(100 - 1) * sizeof(wchar_t)]; /* same size as data except for NUL terminator */
            DWORD payloadBytes;
            /* Hex-decode the input string into raw bytes */
            payloadBytes = decodeHexWChars(payload, sizeof(payload), data);
            /* Wipe the hex string, to prevent it from being given to LogonUserW if
             * any of the crypto calls fail. */
            SecureZeroMemory(data, 100 * sizeof(wchar_t));
            /* Aquire a Context */
            if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0))
            {
                break;
            }
            /* Create hash handle */
            if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash))
            {
                break;
            }
            /* Hash the input string */
            if(!CryptHashData(hHash, (BYTE*)hashData, strlen(hashData), 0))
            {
                break;
            }
            /* Derive an AES key from the hash */
            if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey))
            {
                break;
            }
            if(!CryptDecrypt(hKey, 0, 1, 0, payload, &payloadBytes))
            {
                break;
            }
            /* Copy back into data and NUL-terminate */
            memcpy(data, payload, payloadBytes);
            data[payloadBytes / sizeof(wchar_t)] = L'\0';
        }
        while (0);
        if (hKey)
        {
            CryptDestroyKey(hKey);
        }
        if (hHash)
        {
            CryptDestroyHash(hHash);
        }
        if (hCryptProv)
        {
            CryptReleaseContext(hCryptProv, 0);
        }
        /* FIX: Decrypt the password before using it for authentication  */
        if (LogonUserW(
                    username,
                    domain,
                    data,
                    LOGON32_LOGON_NETWORK,
                    LOGON32_PROVIDER_DEFAULT,
                    &pHandle) != 0)
        {
            printLine("User logged in successfully.");
            CloseHandle(pHandle);
        }
        else
        {
            printLine("Unable to login.");
//.........这里部分代码省略.........
开发者ID:gpwi970725,项目名称:testJuliet2,代码行数:101,代码来源:CWE256_Plaintext_Storage_of_Password__w32_wchar_t_18.c

示例2: SfcIsFileLegit


//.........这里部分代码省略.........
*
* 8. Use result MD5 as hash value; 
*
* 9. Verify embedded signature.
*
* If anything from the above fail - file is not legit by ZeroAccess opinion.
*
* If you copy ZeroAccess downloaded files without copying EA data, it cannot be verified.
*
*/
NTSTATUS SfcIsFileLegit(
	_In_ LPWSTR lpFileName,
	_In_ PBYTE BotKey,
	_In_ DWORD BotKeySize
	)
{
	BOOL                cond = FALSE;
	PVOID               pBuffer;
	MD5_CTX             context;
	ZA_FILEHEADER       zaHeader;
	HCRYPTPROV          lh_prov = 0;
	HCRYPTKEY           lh_key = 0;
	HANDLE              hFile = NULL;
	NTSTATUS            status = STATUS_UNSUCCESSFUL;
	OBJECT_ATTRIBUTES   ObjectAttributes;
	IO_STATUS_BLOCK     IoStatusBlock;
	UNICODE_STRING      usFileName;
	SIZE_T              memIO = 0;

	if (
		(lpFileName == NULL) ||
		(BotKey == NULL) ||
		(BotKeySize == 0)
		)
	{
		return status;
	}


	RtlSecureZeroMemory(&usFileName, sizeof(usFileName));

	do {

		if (RtlDosPathNameToNtPathName_U(lpFileName, &usFileName, NULL, NULL) == FALSE)
			break;

		InitializeObjectAttributes(&ObjectAttributes, &usFileName, OBJ_CASE_INSENSITIVE, NULL, NULL);
		status = NtOpenFile(&hFile, FILE_GENERIC_READ, &ObjectAttributes, &IoStatusBlock,
			FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
			FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT
			);

		if (!NT_SUCCESS(status))
			break;

		RtlFreeUnicodeString(&usFileName);

		RtlSecureZeroMemory(&zaHeader, sizeof(zaHeader));
		if (!SfNtfsQueryFileHeaderFromEa(hFile, &zaHeader)) {
			status = STATUS_EA_LIST_INCONSISTENT;
			break;
		}

		status = STATUS_UNSUCCESSFUL;
		memIO = zaHeader.Size;
		pBuffer = NULL;
		if (
			(NT_SUCCESS(NtAllocateVirtualMemory(NtCurrentProcess(), &pBuffer, 0, &memIO, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE))) &&
			(pBuffer != NULL)
			)
		{
			if (NT_SUCCESS(NtReadFile(hFile, NULL, NULL, NULL, &IoStatusBlock, pBuffer, zaHeader.Size, NULL, NULL))) {
				if (CryptAcquireContext(&lh_prov, NULL, MS_DEF_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
					if (CryptImportKey(lh_prov, (const BYTE *)BotKey, BotKeySize, 0, 0, &lh_key)) {
						RtlSecureZeroMemory(&context, sizeof(context));
						MD5Init(&context);
						MD5Update(&context, (UCHAR*)&zaHeader, (UINT)3 * sizeof(ULONG)); //note: ZA_FILEHEADER without signature
						if (SfcVerifyFile(lh_prov, lh_key, &context, pBuffer, zaHeader.Size))
							status = STATUS_SUCCESS;

						CryptDestroyKey(lh_key);
					}
					CryptReleaseContext(lh_prov, 0);
				}
			}
			memIO = 0;
			NtFreeVirtualMemory(NtCurrentProcess(), &pBuffer, &memIO, MEM_RELEASE);
		}
		NtClose(hFile);
		hFile = NULL;

	} while (cond);

	if (hFile != NULL) NtClose(hFile);

	if (usFileName.Buffer != NULL) {
		RtlFreeUnicodeString(&usFileName);
	}
	return status;
}
开发者ID:hangoversec,项目名称:ZeroAccess,代码行数:101,代码来源:za_crypto.c

示例3: rsaencrypt

void rsaencrypt(unsigned char *data, int length, struct RSAKey *rsakey) {

    int i;
    unsigned char *pKeybuf, *pKeyin;
    HCRYPTKEY hRsaKey;
    PUBLICKEYSTRUC *pBlob;
    RSAPUBKEY *pRPK;
    unsigned char *buf;
    DWORD dlen;
    DWORD bufsize;

    /* allocate buffer for public key blob */
    if((pBlob = malloc(sizeof(PUBLICKEYSTRUC) + sizeof(RSAPUBKEY) +
		       rsakey->bytes)) == NULL)
	fatalbox("Out of memory");

    /* allocate buffer for message encryption block */
    bufsize = (length + rsakey->bytes) << 1;
    if((buf = malloc(bufsize)) == NULL)
	fatalbox("Out of memory");

    /* construct public key blob from host public key */
    pKeybuf = ((unsigned char*)pBlob) + sizeof(PUBLICKEYSTRUC) +
	sizeof(RSAPUBKEY);
    pKeyin = ((unsigned char*)rsakey->modulus);
    /* change big endian to little endian */
    for(i=0; i<rsakey->bytes; i++)
	pKeybuf[i] = pKeyin[rsakey->bytes-i-1];
    pBlob->bType = PUBLICKEYBLOB;
    pBlob->bVersion = 0x02;
    pBlob->reserved = 0;
    pBlob->aiKeyAlg = CALG_RSA_KEYX;
    pRPK = (RSAPUBKEY*)(((unsigned char*)pBlob) + sizeof(PUBLICKEYSTRUC));
    pRPK->magic = 0x31415352; /* "RSA1" */
    pRPK->bitlen = rsakey->bits;
    pRPK->pubexp = rsakey->exponent;

    /* import public key blob into key container */
    if(CryptImportKey(hCryptProv, (void*)pBlob,
		      sizeof(PUBLICKEYSTRUC)+sizeof(RSAPUBKEY)+rsakey->bytes,
		      0, 0, &hRsaKey) == 0)
	fatalbox("Error importing RSA key!");

    /* copy message into buffer */
    memcpy(buf, data, length);
    dlen = length;

    /* using host public key, encrypt the message */
    if(CryptEncrypt(hRsaKey, 0, TRUE, 0, buf, &dlen, bufsize) == 0)
	fatalbox("Error encrypting using RSA key!");

    /*
     * For some strange reason, Microsoft CryptEncrypt using public
     * key, returns the cyphertext in backwards (little endian)
     * order, so reverse it!
     */
    for(i = 0; i < (int)dlen; i++)
	data[i] = buf[dlen - i - 1]; /* make it big endian */

    CryptDestroyKey(hRsaKey);
    free(buf);
    free(pBlob);

}
开发者ID:rdebath,项目名称:sgt,代码行数:64,代码来源:mscrypto.c

示例4: GetLastError

PCCERT_CONTEXT SslSocketCpServer::CreateOurCertificate()
{
	// CertCreateSelfSignCertificate(0,&SubjectName,0,0,0,0,0,0);
	HRESULT hr = 0;
	HCRYPTPROV hProv = NULL;
	PCCERT_CONTEXT p = 0;
	HCRYPTKEY hKey = 0;
	CERT_NAME_BLOB sib = { 0 };
	BOOL AX = 0;

	// Step by step to create our own certificate
	try
	{
		// Create the subject
		char cb[1000] = { 0 };
		sib.pbData = (BYTE*)cb;
		sib.cbData = 1000;
		wchar_t*	szSubject = L"CN=Certificate";
		if (!CertStrToName(CRYPT_ASN_ENCODING, szSubject, 0, 0, sib.pbData, &sib.cbData, NULL))
			throw;


		// Acquire Context
		wchar_t* pszKeyContainerName = L"Container";

		if (!CryptAcquireContext(&hProv, pszKeyContainerName, MS_DEF_PROV, PROV_RSA_FULL, CRYPT_NEWKEYSET | CRYPT_MACHINE_KEYSET))
		{
			hr = GetLastError();
			if (GetLastError() == NTE_EXISTS)
			{
				if (!CryptAcquireContext(&hProv, pszKeyContainerName, MS_DEF_PROV, PROV_RSA_FULL, CRYPT_MACHINE_KEYSET))
				{
					throw;
				}
			}
			else
				throw;
		}

		// Generate KeyPair
		if (!CryptGenKey(hProv, AT_KEYEXCHANGE, CRYPT_EXPORTABLE, &hKey))
			throw;

		// Generate the certificate
		CRYPT_KEY_PROV_INFO kpi = { 0 };
		kpi.pwszContainerName = pszKeyContainerName;
		kpi.pwszProvName = MS_DEF_PROV;
		kpi.dwProvType = PROV_RSA_FULL;
		kpi.dwFlags = CERT_SET_KEY_CONTEXT_PROP_ID;
		kpi.dwKeySpec = AT_KEYEXCHANGE;

		SYSTEMTIME et;
		GetSystemTime(&et);
		et.wYear += 1;

		CERT_EXTENSIONS exts = { 0 };
		p = CertCreateSelfSignCertificate(hProv, &sib, 0, &kpi, NULL, NULL, &et, &exts);

		AX = CryptFindCertificateKeyProvInfo(p, CRYPT_FIND_MACHINE_KEYSET_FLAG, NULL);
		hCS = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0, CERT_STORE_CREATE_NEW_FLAG, 0);
		/*AX = CertAddCertificateContextToStore(hCS,p,CERT_STORE_ADD_NEW,0);
		AX = CryptFindCertificateKeyProvInfo(p,CRYPT_FIND_MACHINE_KEYSET_FLAG,NULL);*/
	}

	catch (...)
	{
	}

	if (hKey)
		CryptDestroyKey(hKey);
	hKey = 0;

	if (hProv)
		CryptReleaseContext(hProv, 0);
	hProv = 0;
	return p;
}
开发者ID:MagnusTiberius,项目名称:iocphttpd,代码行数:77,代码来源:SslSocketCpServer.cpp

示例5: sqlite3_rekey

// Changes the encryption key for an existing database.
int sqlite3_rekey(sqlite3 *db, const unsigned char *pKey, int nKeySize)
{
  Btree *pbt = db->aDb[0].pBt;
  Pager *p = sqlite3BtreePager(pbt);
  LPCRYPTBLOCK pBlock = (LPCRYPTBLOCK)sqlite3pager_get_codecarg(p);
  HCRYPTKEY hKey = DeriveKey(pKey, nKeySize);
  int rc = SQLITE_ERROR;

  if (hKey == MAXDWORD)
  {
    sqlite3Error(db, rc, SQLITECRYPTERROR_PROVIDER);
    return rc;
  }

  if (!pBlock && !hKey) return SQLITE_OK; // Wasn't encrypted to begin with

  // To rekey a database, we change the writekey for the pager.  The readkey remains
  // the same
  if (!pBlock) // Encrypt an unencrypted database
  {
    pBlock = CreateCryptBlock(hKey, p, -1, NULL);
    if (!pBlock)
      return SQLITE_NOMEM;

    pBlock->hReadKey = 0; // Original database is not encrypted
    sqlite3PagerSetCodec(sqlite3BtreePager(pbt), sqlite3Codec, sqlite3CodecSizeChange, sqlite3CodecFree, pBlock);
    //db->aDb[0].pAux = pBlock;
    //db->aDb[0].xFreeAux = DestroyCryptBlock;
  }
  else // Change the writekey for an already-encrypted database
  {
    pBlock->hWriteKey = hKey;
  }

  // Start a transaction
  rc = sqlite3BtreeBeginTrans(pbt, 1);

  if (!rc)
  {
    // Rewrite all the pages in the database using the new encryption key
    Pgno nPage;
    Pgno nSkip = PAGER_MJ_PGNO(p);
    DbPage *pPage;
    Pgno n;

    rc = sqlite3PagerPagecount(p, &nPage);

    for(n = 1; rc == SQLITE_OK && n <= nPage; n ++)
    {
      if (n == nSkip) continue;
      rc = sqlite3PagerGet(p, n, &pPage);
      if(!rc)
      {
        rc = sqlite3PagerWrite(pPage);
        sqlite3PagerUnref(pPage);
      }
    }
  }

  // If we succeeded, try and commit the transaction
  if (!rc)
  {
    rc = sqlite3BtreeCommit(pbt);
  }

  // If we failed, rollback
  if (rc)
  {
    sqlite3BtreeRollback(pbt);
  }

  // If we succeeded, destroy any previous read key this database used
  // and make the readkey equal to the writekey
  if (!rc)
  {
    if (pBlock->hReadKey)
    {
      CryptDestroyKey(pBlock->hReadKey);
    }
    pBlock->hReadKey = pBlock->hWriteKey;
  }
  // We failed.  Destroy the new writekey (if there was one) and revert it back to
  // the original readkey
  else
  {
    if (pBlock->hWriteKey)
    {
      CryptDestroyKey(pBlock->hWriteKey);
    }
    pBlock->hWriteKey = pBlock->hReadKey;
  }

  // If the readkey and writekey are both empty, there's no need for a codec on this
  // pager anymore.  Destroy the crypt block and remove the codec from the pager.
  if (!pBlock->hReadKey && !pBlock->hWriteKey)
  {
    sqlite3PagerSetCodec(p, NULL, NULL, NULL, NULL);
  }

//.........这里部分代码省略.........
开发者ID:AugustoAngeletti,项目名称:blockspaces,代码行数:101,代码来源:crypt.c

示例6: goodB2G2Sink

/* goodB2G2() - use badsource and goodsink by reversing the blocks in the if in the sink function */
static void goodB2G2Sink(wchar_t * password)
{
    if(goodB2G2Static)
    {
        {
            HCRYPTPROV hCryptProv = 0;
            HCRYPTHASH hHash = 0;
            HCRYPTKEY hKey = 0;
            char hashData[100] = HASH_INPUT;
            HANDLE pHandle;
            wchar_t * username = L"User";
            wchar_t * domain = L"Domain";
            do
            {
                BYTE payload[(100 - 1) * sizeof(wchar_t)]; /* same size as password except for NUL terminator */
                DWORD payloadBytes;
                /* Hex-decode the input string into raw bytes */
                payloadBytes = decodeHexWChars(payload, sizeof(payload), password);
                /* Wipe the hex string, to prevent it from being given to LogonUserW if
                 * any of the crypto calls fail. */
                SecureZeroMemory(password, 100 * sizeof(wchar_t));
                /* Aquire a Context */
                if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0))
                {
                    break;
                }
                /* Create hash handle */
                if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash))
                {
                    break;
                }
                /* Hash the input string */
                if(!CryptHashData(hHash, (BYTE*)hashData, strlen(hashData), 0))
                {
                    break;
                }
                /* Derive an AES key from the hash */
                if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey))
                {
                    break;
                }
                /* FIX: Decrypt the password */
                if(!CryptDecrypt(hKey, 0, 1, 0, payload, &payloadBytes))
                {
                    break;
                }
                /* Copy back into password and NUL-terminate */
                memcpy(password, payload, payloadBytes);
                password[payloadBytes / sizeof(wchar_t)] = L'\0';
            }
            while (0);
            if (hKey)
            {
                CryptDestroyKey(hKey);
            }
            if (hHash)
            {
                CryptDestroyHash(hHash);
            }
            if (hCryptProv)
            {
                CryptReleaseContext(hCryptProv, 0);
            }
            /* Use the password in LogonUser() to establish that it is "sensitive" */
            if (LogonUserW(
                        username,
                        domain,
                        password,
                        LOGON32_LOGON_NETWORK,
                        LOGON32_PROVIDER_DEFAULT,
                        &pHandle) != 0)
            {
                printLine("User logged in successfully.");
                CloseHandle(pHandle);
            }
            else
            {
                printLine("Unable to login.");
            }
        }
    }
}
开发者ID:gpwi970725,项目名称:testJuliet2,代码行数:83,代码来源:CWE319_Cleartext_Tx_Sensitive_Info__w32_wchar_t_listen_socket_21.c

示例7: decrypt_block

/**
 * Takes a block of data encrypted with a symmetric cypher and decrypts it.
 * The output buffer must be at least the size of source data.
 */
int decrypt_block(int keytype, const unsigned char *IV,
                  const unsigned char *key,
                  const unsigned char *aad, unsigned int aadlen,
                  unsigned char *src, unsigned int srclen,
                  unsigned char *dest, unsigned int *destlen)
{
    // TODO: right now we reimport the key each time.  Test to see if this
    // is quick enough or if we need to cache an imported key.
    HCRYPTKEY hckey;
    char keyblob[BLOBLEN];
    BLOBHEADER *bheader;
    DWORD *keysize;
    BYTE *keydata;
    int bloblen, keylen, ivlen, rval;
    ALG_ID alg;
    DWORD mode, _destlen;

    get_key_info(keytype, &keylen, &ivlen);
    alg = get_cipher(keytype);
    if (alg == 0) {
        log0(0, 0, 0, "Invalid keytype");
        return 0;
    }

    bheader = (BLOBHEADER *)keyblob;
    keysize = (DWORD *)(keyblob + sizeof(BLOBHEADER));
    keydata = (BYTE *)((char *)keysize + sizeof(DWORD));

    memset(keyblob, 0, sizeof(keyblob));
    bheader->bType = PLAINTEXTKEYBLOB;
    bheader->bVersion = CUR_BLOB_VERSION;
    bheader->aiKeyAlg = alg;
    *keysize = keylen;
    memcpy(keydata, key, keylen);
    bloblen = sizeof(BLOBHEADER) + sizeof(DWORD) + keylen;

    if (!CryptImportKey(base_prov, keyblob, bloblen, 0, 0, &hckey)) {
        mserror("CryptImportKey failed");
        return 0;
    }

    mode = CRYPT_MODE_CBC;
    if (!CryptSetKeyParam(hckey, KP_MODE, (BYTE *)&mode, 0)) {
        mserror("CryptSetKeyParam failed on KP_MODE");
        rval = 0;
        goto end;
    }
    if (!CryptSetKeyParam(hckey, KP_IV, IV, 0)) {
        mserror("CryptSetKeyParam failed on KP_IV");
        rval = 0;
        goto end;
    }
    memcpy(dest, src, srclen);
    _destlen = srclen;
    if (!CryptDecrypt(hckey, 0, 1, 0, dest, &_destlen)) {
        mserror("CryptDecrypt failed");
        rval = 0;
        goto end;
    }
    *destlen = _destlen;
    rval = 1;

end:
    if (!CryptDestroyKey(hckey)) {
        mserror("CryptDestroyKey failed");
    }
    return rval;
}
开发者ID:PumpkinSpace,项目名称:uftp,代码行数:72,代码来源:encrypt_cryptoapi.c

示例8: ReadPasswordFromRegistry

// The following function reads the password from the registry and decrypts it. 
// Note that the szPassword parameter should be already allocated with a minimum 
// size of 32 characters (64 bytes if using UNICODE). 
// The account buffer must be able to hold 100 characters.
BOOL ReadPasswordFromRegistry(TCHAR *szAccount, TCHAR *szPassword) 
{
	int nError;
	BOOL bResult = TRUE;
	
	TCHAR szKey[256];
	HKEY hRegKey = NULL;
	_tcscpy(szKey, MPICHKEY);
	
	if (RegOpenKeyEx(HKEY_CURRENT_USER, szKey, 0, KEY_QUERY_VALUE, &hRegKey) == ERROR_SUCCESS) 
	{
		DWORD dwLength = 100;
		*szAccount = TEXT('\0');
		if (RegQueryValueEx(
				hRegKey, 
				_T("Account"), NULL, 
				NULL, 
				(BYTE*)szAccount, 
				&dwLength)!=ERROR_SUCCESS)
		{
			nError = GetLastError();
			//printf("ReadPasswordFromRegistry:RegQueryValueEx(...) failed, error: %d\n", nError);
			::RegCloseKey(hRegKey);
			return FALSE;
		}
		if (_tcslen(szAccount) < 1)
			return FALSE;

		HCRYPTPROV hProv = NULL;
		HCRYPTKEY hKey = NULL;
		HCRYPTKEY hXchgKey = NULL;
		HCRYPTHASH hHash = NULL;
		// has to be the same used to encrypt!
		TCHAR szLocalPassword[] = _T("[email protected]*I%Ll");

		// Get handle to user default provider.
		//if (CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, 0))
		if (CryptAcquireContext(&hProv, "MPICH", NULL, PROV_RSA_FULL, 0))
		{
			// Create hash object.
			if (CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash))
			{
				// Hash password string.
				dwLength = sizeof(TCHAR)*_tcslen(szLocalPassword);
				if (CryptHashData(hHash, (BYTE *)szLocalPassword, dwLength, 0))
				{
					// Create block cipher session key based on hash of the password.
					if (CryptDeriveKey(hProv, CALG_RC4, hHash, CRYPT_EXPORTABLE, &hKey))
					{
						// the password is less than 32 characters
						dwLength = 32*sizeof(TCHAR);
						DWORD dwType = REG_BINARY;
						if (RegQueryValueEx(hRegKey, _T("Password"), NULL, &dwType, (BYTE*)szPassword, &dwLength)==ERROR_SUCCESS)
						{
							if (!CryptDecrypt(hKey, 0, TRUE, 0, (BYTE *)szPassword, &dwLength))
							{
								nError = GetLastError();
								//printf("ReadPasswordFromRegistry:CryptDecrypt(...) failed, error: %d\n", nError);
								bResult = FALSE;
							}
						}
						else
						{
							nError = GetLastError();
							//printf("ReadPasswordFromRegistry:RegQueryValueEx(...) failed, error: %d\n", nError);
							bResult = FALSE;
						}
						CryptDestroyKey(hKey);  // Release provider handle.
					}
					else
					{
						// Error during CryptDeriveKey!
						nError = GetLastError();
						//printf("ReadPasswordFromRegistry:CryptDeriveKey(...) failed, error: %d\n", nError);
						bResult = FALSE;
					}
				}
				else
				{
					// Error during CryptHashData!
					nError = GetLastError();
					//printf("ReadPasswordFromRegistry:CryptHashData(...) failed, error: %d\n", nError);
					bResult = FALSE;
				}
				CryptDestroyHash(hHash); // Destroy session key.
			}
			else
			{
				// Error during CryptCreateHash!
				nError = GetLastError();
				//printf("ReadPasswordFromRegistry:CryptCreateHash(...) failed, error: %d\n", nError);
				bResult = FALSE;
			}
			CryptReleaseContext(hProv, 0);
		}
		::RegCloseKey(hRegKey);
//.........这里部分代码省略.........
开发者ID:hpc,项目名称:mvapich-cce,代码行数:101,代码来源:MPICH_pwd.cpp

示例9: SetupCryptoClient

BOOL SetupCryptoClient()
{
	// Ensure that the default cryptographic client is set up.
	HCRYPTPROV hProv;
	HCRYPTKEY hKey;
	int nError;
	
	// Attempt to acquire a handle to the default key container.
	//if (!CryptAcquireContext(&hProv, NULL, MS_DEF_PROV, PROV_RSA_FULL, 0))
	if (!CryptAcquireContext(&hProv, "MPICH", MS_DEF_PROV, PROV_RSA_FULL, 0))
	{
		// Some sort of error occured, create default key container.
		//if (!CryptAcquireContext(&hProv, NULL, MS_DEF_PROV, PROV_RSA_FULL, CRYPT_NEWKEYSET))
		if (!CryptAcquireContext(&hProv, "MPICH", MS_DEF_PROV, PROV_RSA_FULL, CRYPT_NEWKEYSET))
		{
			// Error creating key container!
			nError = GetLastError();
			printf("SetupCryptoClient:CryptAcquireContext(...) failed, error: %d\n", nError);
			return FALSE;
		}
	}

	// Attempt to get handle to signature key.
	if (!CryptGetUserKey(hProv, AT_SIGNATURE, &hKey))
	{
		if ((nError = GetLastError()) == NTE_NO_KEY)
		{
			// Create signature key pair.
			if (!CryptGenKey(hProv, AT_SIGNATURE, 0, &hKey))
			{
				// Error during CryptGenKey!
				nError = GetLastError();
				CryptReleaseContext(hProv, 0);
				printf("SetupCryptoClient:CryptGenKey(...) failed, error: %d\n", nError);
				return FALSE;
			}
			else
			{
				CryptDestroyKey(hKey);
			}
		}
		else 
		{
			// Error during CryptGetUserKey!
			CryptReleaseContext(hProv, 0);
			printf("SetupCryptoClient:CryptGetUserKey(...) failed, error: %d\n", nError);
			return FALSE;
		}
	}

	// Attempt to get handle to exchange key.
	if (!CryptGetUserKey(hProv,AT_KEYEXCHANGE,&hKey))
	{
		if ((nError = GetLastError()) == NTE_NO_KEY)
		{
			// Create key exchange key pair.
			if (!CryptGenKey(hProv,AT_KEYEXCHANGE,0,&hKey))
			{
				// Error during CryptGenKey!
				nError = GetLastError();
				CryptReleaseContext(hProv, 0);
				printf("SetupCryptoClient:CryptGenKey(...) failed, error: %d\n", nError);
				return FALSE;
			}
			else
			{
				CryptDestroyKey(hKey);
			}
		}
		else
		{
			// Error during CryptGetUserKey!
			CryptReleaseContext(hProv, 0);
			printf("SetupCryptoClient:CryptGetUserKey(...) failed, error: %d\n", nError);
			return FALSE;
		}
	}

	CryptReleaseContext(hProv, 0);
	return TRUE;
}
开发者ID:hpc,项目名称:mvapich-cce,代码行数:81,代码来源:MPICH_pwd.cpp

示例10: testSign


//.........这里部分代码省略.........
       errors++;
       goto done;
   }

   // Init hash
   if (!CryptCreateHash(hProv, CALG_SHA1, 0, 0, &hHash)) {
       err = GetLastError();
       printf("ERR: CryptCreateHash: %s (0x%0x)\n", e2str(err), err);
       errors++;
       goto done;
   }

   // Done by Office2007
   dwDataLen = sizeof(dwAlgId);
   if (!CryptGetKeyParam(hKey, KP_ALGID, (BYTE *) &dwAlgId, &dwDataLen, 0)) {
       err = GetLastError();
       printf("ERR: CryptGetKeyParam: %s (0x%0x)\n", e2str(err), err);
       errors++;
       goto done;
   }
   if (dwAlgId != CALG_RSA_KEYX) {
       printf("ERR: CryptGetKeyParam() should return CALG_RSA_KEYX instead of 0x%0x\n", dwAlgId);
       errors++;
   }

   // Done by Office2007
   if (!CryptExportKey(hKey, 0, PUBLICKEYBLOB, 0, NULL, &dwDataLen)) {
       err = GetLastError();
       printf("ERR: CryptExportKey: %s (0x%0x)\n", e2str(err), err);
       errors++;
       goto done;
   }
   if (!CryptExportKey(hKey, 0, PUBLICKEYBLOB, 0, data, &dwDataLen)) {
       err = GetLastError();
       printf("ERR: CryptExportKey: %s (0x%0x)\n", e2str(err), err);
       errors++;
       goto done;
   }

   memset(pbData, 0x31, sizeof(pbData));

   // Hash data -- first part
   if (!CryptHashData(hHash, pbData, 50, 0)) {
       err = GetLastError();
       printf("ERR: CryptHashData(1): %s (0x%0x)\n", e2str(err), err);
       errors++;
       goto done;
   }

   // Hash data -- second part
   if (!CryptHashData(hHash, pbData + 50, sizeof(pbData) - 50, 0)) {
       err = GetLastError();
       printf("ERR: CryptHashData(1): %s (0x%0x)\n", e2str(err), err);
       errors++;
       goto done;
   }

   // Sign hash (get length)
   siglen = 0;
   if (!CryptSignHash(hHash, dwKeyUsage, NULL, 0, NULL, &siglen)) {
       err = GetLastError();
       printf("ERR: CryptSignHash(HP_HASHSIZE): %s (0x%0x)\n", e2str(err), err);
       errors++;
       goto done;
   }

   // Sign hash
   if (!CryptSignHash(hHash, dwKeyUsage, NULL, 0, sig, &siglen)) {
       err = GetLastError();
       printf("ERR: CryptSignHash(): %s (0x%0x)\n", e2str(err), err);
       errors++;
       goto done;
   }

   // Destroy hash
   if (!CryptDestroyHash(hHash)) {
       err = GetLastError();
       printf("ERR: CryptDestroyHash(): %s (0x%0x)\n", e2str(err), err);
       errors++;
   }

   // Done by Office2007
   if (!CryptDestroyKey(hKey)) {
       err = GetLastError();
       printf("ERR: CryptDestroyKey(): %s (0x%0x)\n", e2str(err), err);
       errors++;
   }

done:
   /* Release the provider handle */
   if(!CryptReleaseContext(hProv, 0)) {
       err = GetLastError();
       printf("ERR: CryptReleaseContext(): %s (0x%0x)\n", e2str(err), err);
       errors++;
   }

   printf("Done, %d error(s)\n\n", errors);

   return errors;
}
开发者ID:12019,项目名称:svn.gov.pt,代码行数:101,代码来源:main.c

示例11: SavePasswordToRegistry


//.........这里部分代码省略.........
			(BYTE*)szAccount, 
			sizeof(TCHAR)*(_tcslen(szAccount)+1)
			)!=ERROR_SUCCESS)
	{
		nError = GetLastError();
		printf("SavePasswordToRegistry:RegSetValueEx(...) failed, error: %d\n", nError);
		::RegCloseKey(hRegKey);
		return FALSE;
	}

	HCRYPTPROV hProv = NULL;
	HCRYPTKEY hKey = NULL;
	HCRYPTKEY hXchgKey = NULL;
	HCRYPTHASH hHash = NULL;
	DWORD dwLength;
	// Used to encrypt the real password
	TCHAR szLocalPassword[] = _T("[email protected]*I%Ll");

	// Get handle to user default provider.
	//if (CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, 0))
	if (CryptAcquireContext(&hProv, "MPICH", NULL, PROV_RSA_FULL, 0))
	{
		// Create hash object.
		if (CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash))
		{
			// Hash password string.
			dwLength = sizeof(TCHAR)*_tcslen(szLocalPassword);
			if (CryptHashData(hHash, (BYTE *)szLocalPassword, dwLength, 0))
			{
				// Create block cipher session key based on hash of the password.
				if (CryptDeriveKey(hProv, CALG_RC4, hHash, CRYPT_EXPORTABLE, &hKey))
				{
					// Determine number of bytes to encrypt at a time.
					dwLength = sizeof(TCHAR)*(_tcslen(szPassword)+1);

					// Allocate memory.
					BYTE *pbBuffer = (BYTE *)malloc(dwLength);
					if (pbBuffer != NULL)
					{
						memcpy(pbBuffer, szPassword, dwLength);
						// Encrypt data
						if (CryptEncrypt(hKey, 0, TRUE, 0, pbBuffer, &dwLength, dwLength)) 
						{
							// Write data to registry.
							DWORD dwType = REG_BINARY;
							// Add the password.
							if (::RegSetValueEx(hRegKey, _T("Password"), 0, REG_BINARY, pbBuffer, dwLength)!=ERROR_SUCCESS)
							{
								nError = GetLastError();
								printf("SavePasswordToRegistry:RegSetValueEx(...) failed, error: %d\n", nError);
								bResult = FALSE;
							}
							::RegCloseKey(hRegKey);
						}	
						else
						{
							nError = GetLastError();
							printf("SavePasswordToRegistry:CryptEncrypt(...) failed, error: %d\n", nError);
							bResult = FALSE;
						}
						// Free memory.
					  free(pbBuffer);
					}
					else
					{
						nError = GetLastError();
						printf("SavePasswordToRegistry:malloc(...) failed, error: %d\n", nError);
						bResult = FALSE;
					}
					CryptDestroyKey(hKey);  // Release provider handle.
				}
				else
				{
					// Error during CryptDeriveKey!
					nError = GetLastError();
					printf("SavePasswordToRegistry:CryptDeriveKey(...) failed, error: %d\n", nError);
					bResult = FALSE;
				}
			}
			else
			{
				// Error during CryptHashData!
				nError = GetLastError();
				printf("SavePasswordToRegistry:CryptHashData(...) failed, error: %d\n", nError);
				bResult = FALSE;
			}
			CryptDestroyHash(hHash); // Destroy session key.
		}
		else
		{
			// Error during CryptCreateHash!
			nError = GetLastError();
			printf("SavePasswordToRegistry:CryptCreateHash(...) failed, error: %d\n", nError);
			bResult = FALSE;
		}
		CryptReleaseContext(hProv, 0);
	}

	return bResult;
}
开发者ID:hpc,项目名称:mvapich-cce,代码行数:101,代码来源:MPICH_pwd.cpp

示例12: main


//.........这里部分代码省略.........
    fprintf(stderr, "Can't open memory mapped file. Error code: %lu\n",
            GetLastError());
    goto err;
  }
  indata = (PBYTE)MapViewOfFile(inmmf, FILE_MAP_READ, 0, 0, 0);
  if (indata == NULL) {
    fprintf(stderr, "Can't map view of file. Error code: %lu\n", GetLastError());
    goto err;
  }

  GetFileSizeEx(inf, &insz);
  outsz.QuadPart = (insz.QuadPart / 8 + 2) * 8;

  outf = CreateFileA(argv[3], GENERIC_READ | GENERIC_WRITE, 0, NULL,
                     CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  outmmf = CreateFileMappingA(outf, NULL, PAGE_READWRITE,
                              outsz.HighPart, outsz.LowPart, NULL);
  if (outmmf == NULL) {
    fprintf(stderr, "Can't open memory mapped file. Error code: %lu\n",
            GetLastError());
    goto err;
  }

  outdata = (PBYTE)MapViewOfFile(outmmf, FILE_MAP_WRITE, 0, 0, 0);
  if (outdata == NULL) {
    fprintf(stderr, "Can't map view of file. Error code: %lu\n", GetLastError());
    goto err;
  }

  // Crypto stuff
  BOOL res;
  HCRYPTPROV prov;

  if (!CryptAcquireContext(&prov, 0, MS_ENHANCED_PROV, PROV_RSA_FULL,
                           CRYPT_VERIFYCONTEXT)) {
    fputs("Cannot acquire crypt context.", stderr);
    goto err;
  }

  HCRYPTKEY key = generateKey(prov, CALG_3DES, argv[4]);
  crash_if(key == 0, "Cannot make a key.");

  for (LARGE_INTEGER i = {.QuadPart = 0}; i.QuadPart < insz.QuadPart;
       (i.QuadPart) += buf_size) {

    unsigned char buf[buf_size + block_size];
    DWORD len = buf_size;
    void *inp = indata + i.QuadPart,
         *outp = outdata + i.QuadPart;
    BOOL final = insz.QuadPart - i.QuadPart <= buf_size;

    if (final) {
      len = insz.QuadPart - i.QuadPart;
    }

    memcpy(buf, inp, len);
    if (mod == ENC) {
      res = CryptEncrypt(key, 0, final, 0, buf, &len, buf_size + block_size);
    } else {
      res = CryptDecrypt(key, 0, final, 0, buf, &len);
    }

    if (res) {
      memcpy(outp, buf, len);
      if (final) {
        outsz.QuadPart = i.QuadPart + len;
      }
    } else {
      fprintf(stderr, "Can't crypt the block 0x%lx. Error code: %lu\n",
              i.QuadPart, GetLastError());
      goto err;
    }
  }

  CryptDestroyKey(key);
  CryptReleaseContext(prov,0);

  err = 0;

err:
  // Freeing resources.
  apply_not_null(indata, UnmapViewOfFile);
  apply_not_null(inmmf, CloseHandle);
  apply_not_null(inf, CloseHandle);

  apply_not_null(outdata, UnmapViewOfFile);
  apply_not_null(outmmf, CloseHandle);

  if (outf) {
    SetFilePointer(outf, outsz.LowPart, &(outsz.HighPart), FILE_BEGIN);
    SetEndOfFile(outf);
  }

  apply_not_null(outf, CloseHandle);

  if (err)
    return -1;
  else
    return 0;
}
开发者ID:gekola,项目名称:BSUIR-labs,代码行数:101,代码来源:lab1.c

示例13: goodG2B

static void goodG2B()
{
    wchar_t * data;
    wchar_t dataBuffer[100] = L"";
    data = dataBuffer;
    {
        FILE *pFile;
        HCRYPTPROV hCryptProv = 0;
        HCRYPTHASH hHash = 0;
        HCRYPTKEY hKey = 0;
        char hashData[100] = HASH_INPUT;
        pFile = fopen("passwords.txt", "r");
        if (pFile != NULL)
        {
            if (fgetws(data, 100, pFile) == NULL)
            {
                data[0] = L'\0';
            }
            fclose(pFile);
        }
        else
        {
            data[0] = L'\0';
        }
        do
        {
            BYTE payload[(100 - 1) * sizeof(wchar_t)]; /* same size as data except for NUL terminator */
            DWORD payloadBytes;
            /* Hex-decode the input string into raw bytes */
            payloadBytes = decodeHexWChars(payload, sizeof(payload), data);
            /* Wipe the hex string, to prevent it from being given to LogonUserW if
             * any of the crypto calls fail. */
            SecureZeroMemory(data, 100 * sizeof(wchar_t));
            /* Aquire a Context */
            if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0))
            {
                break;
            }
            /* Create hash handle */
            if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash))
            {
                break;
            }
            /* Hash the input string */
            if(!CryptHashData(hHash, (BYTE*)hashData, strlen(hashData), 0))
            {
                break;
            }
            /* Derive an AES key from the hash */
            if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey))
            {
                break;
            }
            /* FIX: Decrypt the password before passing it to the sink */
            if(!CryptDecrypt(hKey, 0, 1, 0, payload, &payloadBytes))
            {
                break;
            }
            /* Copy back into data and NUL-terminate */
            memcpy(data, payload, payloadBytes);
            data[payloadBytes / sizeof(wchar_t)] = L'\0';
        }
        while (0);
        if (hKey)
        {
            CryptDestroyKey(hKey);
        }
        if (hHash)
        {
            CryptDestroyHash(hHash);
        }
        if (hCryptProv)
        {
            CryptReleaseContext(hCryptProv, 0);
        }
    }
    CWE256_Plaintext_Storage_of_Password__w32_wchar_t_53b_goodG2BSink(data);
}
开发者ID:gpwi970725,项目名称:testJuliet2,代码行数:78,代码来源:CWE256_Plaintext_Storage_of_Password__w32_wchar_t_53a.c

示例14: kuhl_m_crypto_l_certificates

NTSTATUS kuhl_m_crypto_l_certificates(int argc, wchar_t * argv[])
{
	HCERTSTORE hCertificateStore;
	PCCERT_CONTEXT pCertContext;
	DWORD i, j, dwSizeNeeded, keySpec;
	wchar_t *certName;
	PCRYPT_KEY_PROV_INFO pBuffer;
	HCRYPTPROV_OR_NCRYPT_KEY_HANDLE monProv;
	HCRYPTKEY maCle;
	BOOL keyToFree;

	PCWCHAR szSystemStore, szStore;
	DWORD dwSystemStore = 0;

	BOOL export = kull_m_string_args_byName(argc, argv, L"export", NULL, NULL);

	kull_m_string_args_byName(argc, argv, L"systemstore", &szSystemStore, kuhl_m_crypto_system_stores[0].name);
	dwSystemStore = kuhl_m_crypto_system_store_to_dword(szSystemStore);
	kull_m_string_args_byName(argc, argv, L"store", &szStore, L"My");

	kprintf(L" * System Store  : \'%s\' (0x%08x)\n"
			L" * Store         : \'%s\'\n\n",
			szSystemStore, dwSystemStore,
			szStore);

	if(hCertificateStore = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, (HCRYPTPROV_LEGACY) NULL, dwSystemStore | CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG, szStore))
	{
		for (i = 0, pCertContext = CertEnumCertificatesInStore(hCertificateStore, NULL); pCertContext != NULL; pCertContext = CertEnumCertificatesInStore(hCertificateStore, pCertContext), i++)
		{
			for(j = 0; j < ARRAYSIZE(nameSrc); j++)
			{
				dwSizeNeeded = CertGetNameString(pCertContext, nameSrc[j], 0, NULL, NULL, 0);
				if(dwSizeNeeded > 0)
				{
					if(certName = (wchar_t *) LocalAlloc(LPTR, dwSizeNeeded * sizeof(wchar_t)))
					{
						if(CertGetNameString(pCertContext, nameSrc[j], 0, NULL, certName, dwSizeNeeded) == dwSizeNeeded)
						{
							kprintf(L"%2u. %s\n", i, certName);

							dwSizeNeeded = 0;
							if(CertGetCertificateContextProperty(pCertContext, CERT_KEY_PROV_INFO_PROP_ID, NULL, &dwSizeNeeded))
							{
								if(pBuffer = (PCRYPT_KEY_PROV_INFO) LocalAlloc(LPTR, dwSizeNeeded))
								{
									if(CertGetCertificateContextProperty(pCertContext, CERT_KEY_PROV_INFO_PROP_ID, pBuffer, &dwSizeNeeded))
									{
										kprintf(
											L"\tKey Container  : %s\n"
											L"\tProvider       : %s\n",
											(pBuffer->pwszContainerName ? pBuffer->pwszContainerName : L"(null)"),
											(pBuffer->pwszProvName ? pBuffer->pwszProvName : L"(null)"));
										
										if(CryptAcquireCertificatePrivateKey(pCertContext, CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG /* CRYPT_ACQUIRE_SILENT_FLAG NULL */, NULL, &monProv, &keySpec, &keyToFree))
										{
											kprintf(L"\tType           : %s (0x%08x)\n", kuhl_m_crypto_keytype_to_str(keySpec), keySpec);

											if(keySpec != CERT_NCRYPT_KEY_SPEC)
											{
												if(CryptGetUserKey(monProv, keySpec, &maCle))
												{
													kuhl_m_crypto_printKeyInfos(0, maCle);
													CryptDestroyKey(maCle);
												}
												else PRINT_ERROR_AUTO(L"CryptGetUserKey");

												if(keyToFree)
													CryptReleaseContext(monProv, 0);
											}
											else if(kuhl_m_crypto_hNCrypt)
											{
												kuhl_m_crypto_printKeyInfos(monProv, 0);
												if(keyToFree)
													K_NCryptFreeObject(monProv);
											}
											else PRINT_ERROR(L"keySpec == CERT_NCRYPT_KEY_SPEC without CNG Handle ?\n");

										} else PRINT_ERROR_AUTO(L"CryptAcquireCertificatePrivateKey");
									} else PRINT_ERROR_AUTO(L"CertGetCertificateContextProperty");
								}
								LocalFree(pBuffer);
								if(!export)
									kprintf(L"\n");
							}

							if(export)
								kuhl_m_crypto_exportCert(pCertContext, (BOOL) dwSizeNeeded, szSystemStore, szStore, i, certName);

						} else PRINT_ERROR_AUTO(L"CertGetNameString");
						LocalFree(certName);
					}
					break;
				} else PRINT_ERROR_AUTO(L"CertGetNameString (for len)");	
			}
开发者ID:deamwork,项目名称:mimikatz,代码行数:94,代码来源:kuhl_m_crypto.c

示例15: goodG2B

/* goodG2B() - use goodsource and badsink by changing the conditions on the for statements */
static void goodG2B()
{
    int h;
    wchar_t * cryptoKey;
    wchar_t cryptoKeyBuffer[100] = L"";
    cryptoKey = cryptoKeyBuffer;
    for(h = 0; h < 1; h++)
    {
        {
            size_t cryptoKeyLen = wcslen(cryptoKey);
            /* if there is room in cryptoKey, read into it from the console */
            if(100-cryptoKeyLen > 1)
            {
                /* FIX: Obtain the hash input from the console */
                if (fgetws(cryptoKey+cryptoKeyLen, (int)(100-cryptoKeyLen), stdin) == NULL)
                {
                    printLine("fgetws() failed");
                    /* Restore NUL terminator if fgetws fails */
                    cryptoKey[cryptoKeyLen] = L'\0';
                }
                /* The next 3 lines remove the carriage return from the string that is
                 * inserted by fgetws() */
                cryptoKeyLen = wcslen(cryptoKey);
                if (cryptoKeyLen > 0)
                {
                    cryptoKey[cryptoKeyLen-1] = L'\0';
                }
            }
        }
    }
    {
        HCRYPTPROV hCryptProv;
        HCRYPTKEY hKey;
        HCRYPTHASH hHash;
        wchar_t toBeEncrypted[] = L"String to be encrypted";
        DWORD encryptedLen = wcslen(toBeEncrypted)*sizeof(wchar_t);
        BYTE encrypted[200];    /* buffer should be larger than toBeEncrypted to have room for IV and padding */
        /* Copy plaintext (without NUL terminator) into byte buffer */
        memcpy(encrypted, toBeEncrypted, encryptedLen);
        /* Try to get a context with and without a new key set */
        if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_AES, 0))
        {
            if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_AES, CRYPT_NEWKEYSET))
            {
                printLine("Error in acquiring cryptographic context");
                exit(1);
            }
        }
        /* Create Hash handle */
        if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash))
        {
            printLine("Error in creating hash");
            exit(1);
        }
        /* Hash the cryptoKey */
        if(!CryptHashData(hHash, (BYTE *) cryptoKey, wcslen(cryptoKey)*sizeof(wchar_t), 0))
        {
            printLine("Error in hashing cryptoKey");
            exit(1);
        }
        /* Derive an AES key from the Hashed cryptoKey */
        if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey))
        {
            printLine("Error in CryptDeriveKey");
            exit(1);
        }
        /* POTENTIAL FLAW: Possibly using a hardcoded crypto key */
        /* Use the derived key to encrypt something */
        if(!CryptEncrypt(hKey, (HCRYPTHASH)NULL, 1, 0, encrypted, &encryptedLen, sizeof(encrypted)))
        {
            printLine("Error in CryptEncrypt");
            exit(1);
        }
        /* use encrypted block */
        printBytesLine(encrypted, encryptedLen);
        if (hKey)
        {
            CryptDestroyKey(hKey);
        }
        if (hHash)
        {
            CryptDestroyHash(hHash);
        }
        if (hCryptProv)
        {
            CryptReleaseContext(hCryptProv, 0);
        }
    }
}
开发者ID:gpwi970725,项目名称:testJuliet2,代码行数:90,代码来源:CWE321_Hard_Coded_Cryptographic_Key__w32_wchar_t_17.c


注:本文中的CryptDestroyKey函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。