您当前的位置:首页 > IT编程 > C++
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:C++ CryptDeriveKey函数代码示例

51自学网 2021-06-01 20:15:35
  C++
这篇教程C++ CryptDeriveKey函数代码示例写得很实用,希望能帮到您。

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

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

示例1: DeriveKey

bool Encryption::DeriveKey(){    if(!CryptDeriveKey(hCryptProv, CALG_RC2, hHash, CRYPT_EXPORTABLE, &hKey))        return false;    return true;}
开发者ID:xausee,项目名称:SecreteIt,代码行数:7,


示例2: init

void Crytography:: init(){	hProv   = 0;   hKey     = 0;     hXchgKey = 0;    hHash   = 0;	//status = FALSE;	//_szPassword;	//_szPassword = "khoa";	CString Loi="";	if(!CryptAcquireContext(&hProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, 0)) {       // printf("Error %x during CryptAcquireContext!/n", GetLastError());		AfxMessageBox("Error during CryptAcquireContext!",MB_OK);		return;    }	 if(!CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash)) {           // printf("Error %x during CryptCreateHash!/n", GetLastError());			//MessageBox("Error %x during CryptCreateHash!/n"+GetLastError());		 AfxMessageBox("Error during CryptCreateHash!",MB_OK);			return;            //goto done;        }        // Hash in the password data.        if(!CryptHashData(hHash, (const unsigned char *)_szPassword, (DWORD)strlen(_szPassword), 0)) {			//MessageBox("Error %x during CryptHashData!/n"+GetLastError());			AfxMessageBox("Error during CryptHashData!",MB_OK);			return;            //printf("Error %x during CryptHashData!/n", GetLastError());            //goto done;        }        // Derive a session key from the hash object.		if(_typeOfCrytography=="RC2")		{			if(!CryptDeriveKey(hProv, ENCRYPT_ALGORITHM1, hHash, KEYLENGTH, &hKey)) {				//MessageBox("Error %x during CryptDeriveKey!/n"+GetLastError());				AfxMessageBox("Error during CryptDeriveKey!",MB_OK);				return;			   // printf("Error %x during CryptDeriveKey!/n", GetLastError());			   // goto done;			}		}		else//RC4		{			if(!CryptDeriveKey(hProv, ENCRYPT_ALGORITHM2, hHash, KEYLENGTH, &hKey)) {				//MessageBox("Error %x during CryptDeriveKey!/n"+GetLastError());				AfxMessageBox("Error during CryptDeriveKey!",MB_OK);				return;			   // printf("Error %x during CryptDeriveKey!/n", GetLastError());			   // goto done;			}		}        // Destroy the hash object.        CryptDestroyHash(hHash);        hHash = 0;}
开发者ID:hksonngan,项目名称:mytesgnikrow,代码行数:57,


示例3: good2

/* good2() reverses the bodies in the if statement */static void good2(){    if(staticTrue)    {        {            BYTE payload[100];            DWORD payloadLen = strlen(PAYLOAD);            HCRYPTPROV hCryptProv = (HCRYPTPROV)NULL;            HCRYPTHASH hHash = (HCRYPTHASH)NULL;            HCRYPTKEY hKey = (HCRYPTKEY)NULL;            char hashData[100] = HASH_INPUT;            do            {                /* Copy plaintext into payload buffer */                memcpy(payload, PAYLOAD, payloadLen);                /* Aquire a Context */                if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0))                {                    break;                }                /* FIX: All required steps are present */                /* 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;                }                /* Encrypt the payload */                if(!CryptEncrypt(hKey, 0, 1, 0, payload, &payloadLen, sizeof(payload)))                {                    break;                }            }            while (0);            if (hKey)            {                CryptDestroyKey(hKey);            }            if (hHash)            {                CryptDestroyHash(hHash);            }            if (hCryptProv)            {                CryptReleaseContext(hCryptProv, 0);            }            /* Do something with the encrypted data */            printBytesLine(payload, payloadLen);        }    }}
开发者ID:gpwi970725,项目名称:testJuliet2,代码行数:61,


示例4: Encrypt

/* * Simple, native encryption using RC4, inspired from one of Howard's  * old books. * * In a nutshell: Acquire the CSP handle, create an empty hash, put  * the hash of the key in it, derive the crypto key from it. Note * (from Howard) the key also stores the algorithm in order to * perform the encryption. * * Return: TRUE if completed successfully, FALSE otherwise. */BOOL Encrypt(LPBYTE bKey, LPBYTE bPlaintext, LPBYTE bCipherText, DWORD dwHowMuch) {		HCRYPTPROV hProv;	HCRYPTKEY  hKey;	HCRYPTHASH hHash;	LPBYTE lpExpKey;	DWORD dwBuff = dwHowMuch;	CopyMemory(bCipherText, bPlaintext, dwHowMuch);	lpExpKey = Expand(bKey);	if (!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, 								CRYPT_VERIFYCONTEXT))		return FALSE;	if (!CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash))		return FALSE;	if (!CryptHashData(hHash, lpExpKey, strlen((char *) lpExpKey), 0))		return FALSE;	if (!CryptDeriveKey(hProv, CALG_RC4, hHash, 						CRYPT_EXPORTABLE, 						&hKey))		return FALSE;	if (!CryptEncrypt(hKey, 0, TRUE, 0, 						bCipherText, 						&dwBuff, 						dwHowMuch))		return FALSE;	if (hKey)  CryptDestroyKey(hKey);	if (hHash) CryptDestroyHash(hHash);	if (hProv) CryptReleaseContext(hProv, 0);	return TRUE;}
开发者ID:apoly,项目名称:beaver,代码行数:45,


示例5: CreateKey

HCRYPTKEY CreateKey(const BYTE *a1, DWORD a2){	HCRYPTKEY result;	HCRYPTHASH v3; 	HCRYPTKEY phKey;	v3 = 0;	if ( a1 && a2 )	{		if ( Init() )		{			if ( CryptCreateHash(g_hProv, 0x8004u, 0, 0, &v3) )			{				if ( CryptHashData(v3, a1, a2, 0) )					CryptDeriveKey(g_hProv, 0x6801u, v3, 0, &phKey);				CryptDestroyHash(v3);			}			result = phKey;		}		else		{			result = -1;		}	}	else	{		result = 0;	}	return result;}
开发者ID:pyq881120,项目名称:urltraveler,代码行数:30,


示例6: swCryptDeriveKey

//-----------------------------------------------------------------------------// swCryptDeriveKey()//-----------------------------------------------------------------------------// Calcul de la clé de chiffrement des mots de passe par dérivation du mot de // passe maitre//-----------------------------------------------------------------------------// [in] cszMasterPwd = mot de passe maitre// [out] hKey = handle de clé// [out] pAESKeyData = bloc de données pour ceux qui voudraient reconstruire la clé//-----------------------------------------------------------------------------// Retour : 0 si OK//-----------------------------------------------------------------------------int swCryptDeriveKey(const char *pszMasterPwd,HCRYPTKEY *phKey,BYTE *pAESKeyData,BOOL bForceOldDerivationFunction){	TRACE((TRACE_ENTER,_F_,""));	BOOL brc;	int rc=-1;	HCRYPTHASH hHash=NULL;		// si la clé a déjà été créée, on la libère	if (*phKey!=NULL) { CryptDestroyKey(*phKey); *phKey=NULL; }	// création d'un hash	brc=CryptCreateHash(ghProv,CALG_SHA1,0,0,&hHash);           	if (!brc) {	TRACE((TRACE_ERROR,_F_,"CryptCreateHash()")); goto end; }	if (bForceOldDerivationFunction)	{		// hash du mot de passe		brc=CryptHashData(hHash,(unsigned char*)pszMasterPwd,strlen(pszMasterPwd),0); 		if (!brc) {	TRACE((TRACE_ERROR,_F_,"CryptHashData()")); goto end; }		// dérivation		brc=CryptDeriveKey(ghProv,CALG_AES_256,hHash,0,phKey); 		TRACE((TRACE_INFO,_F_,"CryptDeriveKey(CALG_AES_256)"));	}	else if (atoi(gszCfgVersion)<93)	{		// hash du mot de passe		brc=CryptHashData(hHash,(unsigned char*)pszMasterPwd,strlen(pszMasterPwd),0); 		if (!brc) {	TRACE((TRACE_ERROR,_F_,"CryptHashData()")); goto end; }		// dérivation		brc=CryptDeriveKey(ghProv,CALG_3DES,hHash,0,phKey); 		TRACE((TRACE_INFO,_F_,"CryptDeriveKey(CALG_3DES)"));	}	else // nouveau mécanisme +secure en 0.93 (PBKDF2) ISSUE#56	{		// Obtient 256 bits (32 octets) auprès de PBKDF2 pour générer une clé AES-256		if (!swIsPBKDF2KeySaltReady()) { TRACE((TRACE_ERROR,_F_,"swIsPBKDF2SaltReady()=FALSE")); goto end; }		if (swPBKDF2(pAESKeyData,AES256_KEY_LEN,pszMasterPwd,gSalts.bufPBKDF2KeySalt,PBKDF2_SALT_LEN,10000)!=0) goto end;		if (swCreateAESKeyFromKeyData(pAESKeyData,phKey)!=0) goto end;	}	if (!brc) { TRACE((TRACE_ERROR,_F_,"CryptDeriveKey()=0x%08lx",GetLastError())); goto end; }	rc=0;end:	if (hHash!=NULL) CryptDestroyHash(hHash);	TRACE((TRACE_LEAVE,_F_,"rc=%d",rc));	return rc;}
开发者ID:hackthem,项目名称:swsso,代码行数:58,


示例7: aes_decrypt

BOOL aes_decrypt(BYTE *inbuf, BYTE *outbuf, size_t buf_size, LPCWSTR key_str, size_t key_len){    if (inbuf == NULL || outbuf == NULL) return FALSE;    BOOL dwStatus = FALSE;    BOOL bResult = FALSE;    wchar_t info[] = L"Microsoft Enhanced RSA and AES Cryptographic Provider";    HCRYPTPROV hProv;    if (!CryptAcquireContextW(&hProv, NULL, info, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)){        dwStatus = GetLastError();        printf("CryptAcquireContext failed: %x/n", dwStatus);        CryptReleaseContext(hProv, 0);        return dwStatus;    }    HCRYPTHASH hHash;    if (!CryptCreateHash(hProv, CALG_SHA_256, 0, 0, &hHash)){        dwStatus = GetLastError();        printf("CryptCreateHash failed: %x/n", dwStatus);        CryptReleaseContext(hProv, 0);        return dwStatus;    }    if (!CryptHashData(hHash, (BYTE*)key_str, key_len, 0)) {        DWORD err = GetLastError();        printf ("CryptHashData Failed : %#x/n", err);        return dwStatus;    }    HCRYPTKEY hKey;    if (!CryptDeriveKey(hProv, CALG_AES_128, hHash, 0,&hKey)){        dwStatus = GetLastError();        printf("CryptDeriveKey failed: %x/n", dwStatus);        CryptReleaseContext(hProv, 0);        return dwStatus;    }        const size_t chunk_size = BLOCK_LEN;    DWORD read = 0;    DWORD written = 0;    DWORD ciphertextLen = BLOCK_LEN;    memcpy(outbuf, inbuf, chunk_size);    if (CryptDecrypt(hKey, NULL, FALSE, 0,outbuf, &ciphertextLen)) {        //printf ("[+] crypt OK!/n");        dwStatus = TRUE;    }    CryptReleaseContext(hProv, 0);    CryptDestroyKey(hKey);    CryptDestroyHash(hHash);    return dwStatus;}
开发者ID:ezhangle,项目名称:decryptors_archive,代码行数:57,


示例8: CWE325_Missing_Required_Cryptographic_Step__w32_CryptHashData_17_bad

void CWE325_Missing_Required_Cryptographic_Step__w32_CryptHashData_17_bad(){    int j;    for(j = 0; j < 1; j++)    {        {            BYTE payload[100];            DWORD payloadLen = strlen(PAYLOAD);            HCRYPTPROV hCryptProv = (HCRYPTPROV)NULL;            HCRYPTHASH hHash = (HCRYPTHASH)NULL;            HCRYPTKEY hKey = (HCRYPTKEY)NULL;            char hashData[100] = HASH_INPUT;            do            {                /* Copy plaintext into payload buffer */                memcpy(payload, PAYLOAD, payloadLen);                /* 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;                }                /* FLAW: Missing required step (CryptHashData) does not use hash input when generating AES key */                /* Derive an AES key from the hash */                if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey))                {                    break;                }                /* Encrypt the payload */                if(!CryptEncrypt(hKey, 0, 1, 0, payload, &payloadLen, sizeof(payload)))                {                    break;                }            }            while (0);            if (hKey)            {                CryptDestroyKey(hKey);            }            if (hHash)            {                CryptDestroyHash(hHash);            }            if (hCryptProv)            {                CryptReleaseContext(hCryptProv, 0);            }            /* Do something with the encrypted data */            printBytesLine(payload, payloadLen);        }    }}
开发者ID:gpwi970725,项目名称:testJuliet2,代码行数:56,


示例9: Password

void Password(char*parol,int len)        {        if(hProv!=NULL)CryptReleaseContext(hProv,0);        CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);        CryptCreateHash(hProv,CALG_SHA,0,0,&hash);        CryptHashData(hash,parol,len,0);        CryptDeriveKey(hProv,CALG_RC4,hash,0,&key);        CryptDestroyHash(hash);        }
开发者ID:MOROZIL-nic,项目名称:craft,代码行数:10,


示例10: CWE325_Missing_Required_Cryptographic_Step__w32_CryptCreateHash_05_bad

void CWE325_Missing_Required_Cryptographic_Step__w32_CryptCreateHash_05_bad(){    if(staticTrue)    {        {            BYTE payload[100];            DWORD payloadLen = strlen(PAYLOAD);            HCRYPTPROV hCryptProv = (HCRYPTPROV)NULL;            HCRYPTHASH hHash = (HCRYPTHASH)NULL;            HCRYPTKEY hKey = (HCRYPTKEY)NULL;            char hashData[100] = HASH_INPUT;            do            {                /* Copy plaintext into payload buffer */                memcpy(payload, PAYLOAD, payloadLen);                /* Aquire a Context */                if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0))                {                    break;                }                /* FLAW: Missing required step (CryptCreateHash) causes the payload to remain in plaintext form */                /* 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;                }                /* Encrypt the payload */                if(!CryptEncrypt(hKey, 0, 1, 0, payload, &payloadLen, sizeof(payload)))                {                    break;                }            }            while (0);            if (hKey)            {                CryptDestroyKey(hKey);            }            if (hHash)            {                CryptDestroyHash(hHash);            }            if (hCryptProv)            {                CryptReleaseContext(hCryptProv, 0);            }            /* Do something with the encrypted data */            printBytesLine(payload, payloadLen);        }    }}
开发者ID:gpwi970725,项目名称:testJuliet2,代码行数:55,


示例11: DWORD

std::string CStringUtils::Decrypt(const std::string& s, const std::string& password){    std::string decryptstring;    HCRYPTPROV hProv = NULL;    // Get handle to user default provider.    if (CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT | CRYPT_SILENT))    {        HCRYPTHASH hHash = NULL;        // Create hash object.        if (CryptCreateHash(hProv, CALG_SHA_512, 0, 0, &hHash))        {            // Hash password string.            DWORD dwLength = DWORD(sizeof(WCHAR)*password.size());            if (CryptHashData(hHash, (BYTE *)password.c_str(), dwLength, 0))            {                HCRYPTKEY hKey = NULL;                // Create block cipher session key based on hash of the password.                if (CryptDeriveKey(hProv, CALG_AES_256, hHash, CRYPT_EXPORTABLE, &hKey))                {                    dwLength = DWORD(s.size() + 1024); // 1024 bytes should be enough for padding                    std::unique_ptr<BYTE[]> buffer(new BYTE[dwLength]);                    std::unique_ptr<BYTE[]> strIn(new BYTE[s.size() + 1]);                    if (buffer && strIn)                    {                        if (CStringUtils::FromHexString(s, strIn.get()))                        {                            // copy encrypted password to temporary buffer                            memcpy(buffer.get(), strIn.get(), s.size());                            dwLength = DWORD(s.size() / 2);                            CryptDecrypt(hKey, 0, true, 0, (BYTE *)buffer.get(), &dwLength);                            decryptstring = std::string((char*)buffer.get(), dwLength);                            if (!decryptstring.empty() && (decryptstring[0] == '*'))                            {                                decryptstring = decryptstring.substr(1);                            }                            else                                decryptstring.clear();                        }                    }                    CryptDestroyKey(hKey);  // Release provider handle.                }            }            CryptDestroyHash(hHash); // Destroy session key.        }        CryptReleaseContext(hProv, 0);    }    else        DebugBreak();    return decryptstring;}
开发者ID:Kasper8660,项目名称:tortoisesvn,代码行数:52,


示例12: exsltCryptoCryptoApiRc4Decrypt

static voidexsltCryptoCryptoApiRc4Decrypt (xmlXPathParserContextPtr ctxt,				const unsigned char *key,				const unsigned char *msg, int msglen,				unsigned char *dest, int destlen) {    HCRYPTPROV hCryptProv;    HCRYPTKEY hKey;    HCRYPTHASH hHash;    DWORD dwDataLen;    unsigned char hash[HASH_DIGEST_LENGTH];    if (msglen > destlen) {	xsltTransformError (xsltXPathGetTransformContext (ctxt), NULL,			    NULL,			    "exslt:crypto : internal error exsltCryptoCryptoApiRc4Encrypt dest buffer too small./n");	return;    }    if (!CryptAcquireContext (&hCryptProv, NULL, NULL, PROV_RSA_FULL,			      CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {	exsltCryptoCryptoApiReportError (ctxt, __LINE__);	return;    }    hHash = exsltCryptoCryptoApiCreateHash (ctxt, hCryptProv,					    CALG_SHA1, key,					    RC4_KEY_LENGTH, hash,					    HASH_DIGEST_LENGTH);    if (!CryptDeriveKey	(hCryptProv, CALG_RC4, hHash, 0x00800000, &hKey)) {	exsltCryptoCryptoApiReportError (ctxt, __LINE__);	goto fail;    }/* Now encrypt data. */    dwDataLen = msglen;    memcpy (dest, msg, msglen);    if (!CryptDecrypt (hKey, 0, TRUE, 0, dest, &dwDataLen)) {	exsltCryptoCryptoApiReportError (ctxt, __LINE__);	goto fail;    }  fail:    if (0 != hHash) {	CryptDestroyHash (hHash);    }    CryptDestroyKey (hKey);    CryptReleaseContext (hCryptProv, 0);}
开发者ID:Ashod,项目名称:WinCairoRequirements,代码行数:50,


示例13: generateKey

HCRYPTKEY generateKey(HCRYPTPROV provider, ALG_ID algid, LPTSTR password) {  BOOL       res;  DWORD      data;  HCRYPTKEY  key;  HCRYPTHASH hash;  if (!CryptCreateHash(provider, CALG_SHA, 0, 0, &hash))    return 0;  data = strlen(password);  if (!CryptHashData(hash, (BYTE *)password, data, 0)) {    CryptDestroyHash(hash);    return 0;  }  res = CryptDeriveKey(provider, algid, hash, CRYPT_EXPORTABLE, &key);  CryptDestroyHash(hash);  return (res ? key : 0);}
开发者ID:gekola,项目名称:BSUIR-labs,代码行数:17,


示例14: GenKey

HCRYPTKEY GenKey(HCRYPTPROV hCrProv, QString keyText, QByteArray* key, DWORD& keyBlobLen, bool flag){    HCRYPTKEY hKey = 0;    HCRYPTHASH hHash = 0;    if (flag)    {        CryptGenKey(hCrProv, CALG_AES_256, CRYPT_EXPORTABLE, &hKey);    }    else    {        CryptCreateHash(hCrProv, CALG_MD5, 0, 0, &hHash);        CryptHashData(hHash, (BYTE *)keyText.toUtf8().constData(), keyText.length(), 0);        CryptDeriveKey(hCrProv, CALG_AES_256, hHash, 0, &hKey);    }    CryptExportKey(hKey, 0, PLAINTEXTKEYBLOB, 0, NULL, &keyBlobLen);    key->resize(keyBlobLen);    CryptExportKey(hKey, 0, PLAINTEXTKEYBLOB, 0, (BYTE*)key->data(), &keyBlobLen);    return hKey;}
开发者ID:Naxik,项目名称:Lab2,代码行数:19,


示例15: derive_cryptkey_ptr

	inline cryptkey_ptr_t derive_cryptkey_ptr(HCRYPTPROV hProv, ALG_ID Algid, HCRYPTHASH hBaseData, DWORD dwFlags)	{		HCRYPTKEY tmp;				if( !CryptDeriveKey(hProv, Algid, hBaseData, dwFlags, &tmp ) )		{			DWORD const errc = GetLastError();			STCRYPT_THROW_EXCEPTION( exception::cryptoapi_error() << exception::cryptoapi_einfo(errc) );		}		std::auto_ptr<HCRYPTKEY> HCRYPTKEY_mem;		try {			HCRYPTKEY_mem.reset(new HCRYPTKEY(tmp));		}catch(...){			BOOL const r = CryptDestroyKey(tmp); assert(r);			throw;		}		return cryptkey_ptr_t  ( HCRYPTKEY_mem.release(), delete_HCRYPTKEY );	}
开发者ID:abelepereira,项目名称:stcrypt,代码行数:20,


示例16: DeriveKey

// Derive an encryption key from a user-supplied bufferstatic HCRYPTKEY DeriveKey(const void *pKey, int nKeyLen){  HCRYPTHASH hHash = 0;  HCRYPTKEY  hKey;  if (!pKey || !nKeyLen) return 0;  if (!InitializeProvider())  {    return MAXDWORD;  }  if (CryptCreateHash(g_hProvider, CALG_SHA1, 0, 0, &hHash))  {    if (CryptHashData(hHash, (LPBYTE)pKey, nKeyLen, 0))    {      CryptDeriveKey(g_hProvider, CALG_RC4, hHash, 0, &hKey);    }    CryptDestroyHash(hHash);  }    return hKey;}
开发者ID:AugustoAngeletti,项目名称:blockspaces,代码行数:23,


示例17: memset

bool CEncryptSyncData::InitEncryptHandle(const char * pchrPassWord){	memset(m_chKeyPassWord,0,sizeof(m_chKeyPassWord));	memcpy(m_chKeyPassWord,pchrPassWord,strlen(pchrPassWord));	if(!CryptAcquireContext(&hCryptProv,NULL,NULL,PROV_RSA_FULL,0))	{		return false;	}	if(!CryptCreateHash(hCryptProv,CALG_MD5,0,0,&hHash))	{		return false;	}	if(!CryptHashData(hHash,(BYTE *)m_chKeyPassWord,strlen(m_chKeyPassWord),0)) 	{		return false;	}	if(!CryptDeriveKey(hCryptProv,ENCRYPT_ALGORITHM, hHash, KEYLENGTH,&hKey))	{ 		return false;	} 	CryptDestroyHash(hHash); 	hHash = 0; 	return true;}
开发者ID:guangminghan,项目名称:CyclonicGameEngine,代码行数:24,


示例18: aes_decrypt_file

BOOL aes_decrypt_file(LPWSTR filename, LPWSTR filename2, LPCWSTR key_str, size_t key_len){    if (filename == NULL || filename2 == NULL) return FALSE;    BOOL dwStatus = FALSE;    printf("Key: %S/n", key_str);    printf("Key len: %#x/n", key_len);    printf("Input File: %S/n", filename);    printf("Output File: %S/n", filename2);    printf("----/n");    wchar_t info[] = L"Microsoft Enhanced RSA and AES Cryptographic Provider";    HCRYPTPROV hProv;    if (!CryptAcquireContextW(&hProv, NULL, info, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)){        dwStatus = GetLastError();        printf("CryptAcquireContext failed: %x/n", dwStatus);        CryptReleaseContext(hProv, 0);        return dwStatus;    }    HCRYPTHASH hHash;    if (!CryptCreateHash(hProv, CALG_SHA_256, 0, 0, &hHash)){        dwStatus = GetLastError();        printf("CryptCreateHash failed: %x/n", dwStatus);        CryptReleaseContext(hProv, 0);        return dwStatus;    }    if (!CryptHashData(hHash, (BYTE*)key_str, key_len, 0)) {        DWORD err = GetLastError();        printf ("CryptHashData Failed : %#x/n", err);        return dwStatus;    }    HCRYPTKEY hKey;    if (!CryptDeriveKey(hProv, CALG_AES_128, hHash, 0,&hKey)){        dwStatus = GetLastError();        printf("CryptDeriveKey failed: %x/n", dwStatus);        CryptReleaseContext(hProv, 0);        return dwStatus;    }        const size_t chunk_size = BLOCK_LEN;    BYTE chunk[chunk_size];    DWORD read = 0;    DWORD written = 0;    HANDLE hInpFile = CreateFileW(filename, GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_FLAG_SEQUENTIAL_SCAN,NULL);    HANDLE hOutFile = CreateFileW(filename2, GENERIC_WRITE, 0,  NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);              if (hInpFile == NULL) {        printf("Cannot open input file!/n");        return dwStatus;    }    if (hOutFile == NULL) {        printf("Cannot open output file!/n");        return dwStatus;    }    while (ReadFile(hInpFile, chunk, chunk_size, &read, NULL)) {        if (0 == read){            break;        }        DWORD ciphertextLen = BLOCK_LEN;        if (!CryptDecrypt(hKey, NULL, FALSE, 0,chunk, &ciphertextLen)) {                printf("failed!/n");                dwStatus = FALSE;                break;        } else {            dwStatus = TRUE;        }        if (!WriteFile(hOutFile, chunk, ciphertextLen, &written, NULL)) {            printf("writing failed!/n");            break;        }        memset(chunk, 0, chunk_size);    }    CryptReleaseContext(hProv, 0);    CryptDestroyKey(hKey);    CryptDestroyHash(hHash);    CloseHandle(hInpFile);    CloseHandle(hOutFile);    return dwStatus;}
开发者ID:ezhangle,项目名称:decryptors_archive,代码行数:83,


示例19: goodB2G1

/* goodB2G1() - use badsource and goodsink by changing the second globalReturnsTrue() to globalReturnsFalse() */static void goodB2G1(){    wchar_t * data;    wchar_t dataBuffer[100] = L"";    data = dataBuffer;    if(globalReturnsTrue())    {        {            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';            }        }    }    if(globalReturnsFalse())    {        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */        printLine("Benign, fixed string");    }    else    {        {            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)            {//.........这里部分代码省略.........
开发者ID:gpwi970725,项目名称:testJuliet2,代码行数:101,


示例20: MyHandleError

bool StandardEncryption::EncryptFile(PCHAR szSource, PCHAR szDestination, PCHAR szPassword, bool bEncrypt) {	//-------------------------------------------------------------------	// Parameters passed are:	//  szSource, the name of the input, a plaintext file.	//  szDestination, the name of the output, an encrypted file to be 	//   created.	//  szPassword, either NULL if a password is not to be used or the 	//   string that is the password.	//-------------------------------------------------------------------	// Declare and initialize local variables.	FILE *hSource; 	FILE *hDestination; 	HCRYPTPROV hCryptProv; 	HCRYPTKEY hKey;	HCRYPTKEY hXchgKey; 	HCRYPTHASH hHash; 	PBYTE pbKeyBlob; 	DWORD dwKeyBlobLen; 	PBYTE pbBuffer; 	DWORD dwBlockLen; 	DWORD dwBufferLen; 	DWORD dwCount;  	unsigned long ltemp = 0;	char szSpeed[SIZE_STRING];	char szAverage[SIZE_STRING];		//-------------------------------------------------------------------	// Open source file. 	if(hSource = fopen(szSource,"rb")) {	   //printf("The source plaintext file, %s, is open. /n", szSource);	} else {	   MyHandleError("Error opening source plaintext file!");	   return false;	} 	//-------------------------------------------------------------------	// Open destination file. 	if(hDestination = fopen(szDestination,"wb")) {		 //printf("Destination file %s is open. /n", szDestination);	} else {		MyHandleError("Error opening destination ciphertext file!"); 		return false;	}	// Get the handle to the default provider. 	if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_AES , CRYPT_VERIFYCONTEXT)) {	//if(CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL , 0)) {	   //printf("A cryptographic provider has been acquired. /n");	} else {	   MyHandleError("Error during CryptAcquireContext!");	   return false;	}	//-------------------------------------------------------------------	// Create the session key.	if(!szPassword ) { 		return false;	} else { 		//-------------------------------------------------------------------		// The file will be encrypted with a session key derived from a		// password.		// The session key will be recreated when the file is decrypted		// only if the password used to create the key is available.		//-------------------------------------------------------------------		// Create a hash object. 		if(CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hHash)) {			//printf("A hash object has been created. /n");		} else { 			 MyHandleError("Error during CryptCreateHash!");			 return false;		}		//-------------------------------------------------------------------		// Hash the password.		if(CryptHashData(hHash, (BYTE *)szPassword, strlen(szPassword), 0)) {			//printf("The password has been added to the hash. /n");		} else {			MyHandleError("Error during CryptHashData."); 			return false;		}		//-------------------------------------------------------------------		// Derive a session key from the hash object. 		if(CryptDeriveKey(hCryptProv, ENCRYPT_ALGORITHM, hHash, KEYLENGTH, &hKey)) {			//printf("An encryption key is derived from the password hash. /n"); 		} else {			MyHandleError("Error during CryptDeriveKey!");			return false;		}		//-------------------------------------------------------------------		// Destroy hash object. 		if(hHash) {			if(!(CryptDestroyHash(hHash))) {			   MyHandleError("Error during CryptDestroyHash"); //.........这里部分代码省略.........
开发者ID:dannydraper,项目名称:CedeCryptPortable,代码行数:101,


示例21: CWE506_Embedded_Malicious_Code__w32_aes_encrypted_payload_04_bad

void CWE506_Embedded_Malicious_Code__w32_aes_encrypted_payload_04_bad(){    if(STATIC_CONST_TRUE)    {        {            /* FLAW: encrytped "calc.exe" */            BYTE payload[20] = {0xfb, 0x50, 0xe5, 0x8d, 0xc5, 0x4b, 0xdd, 0xe0, 0x26, 0x2b, 0x98, 0x49, 0x73, 0xfb, 0x4c, 0xf6};            DWORD payloadLen = strlen((char *)payload);            HCRYPTPROV hCryptProv = 0;            HCRYPTHASH hHash = 0;            HCRYPTKEY hKey = 0;            char hashData[100] = HASH_INPUT;            do            {                /* 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;                }                /* Decrypt the payload */                if(!CryptDecrypt(hKey, 0, 1, 0, (BYTE *)payload, &payloadLen))                {                    break;                }                /* null terminate */                payload[payloadLen] = '/0';                if(system((char*)payload) <= 0)                {                    printLine("command execution failed!");                    exit(1);                }            }            while (0);            if (hKey)            {                CryptDestroyKey(hKey);            }            if (hHash)            {                CryptDestroyHash(hHash);            }            if (hCryptProv)            {                CryptReleaseContext(hCryptProv, 0);            }        }    }}
开发者ID:maurer,项目名称:tiamat,代码行数:63,


示例22: CWE321_Hard_Coded_Cryptographic_Key__w32_char_06_bad

void CWE321_Hard_Coded_Cryptographic_Key__w32_char_06_bad(){    char * cryptoKey;    char cryptoKeyBuffer[100] = "";    cryptoKey = cryptoKeyBuffer;    if(STATIC_CONST_FIVE==5)    {        /* FLAW: Use a hardcoded value for the hash input causing a hardcoded crypto key in the sink */        strcpy(cryptoKey, CRYPTO_KEY);    }    {        HCRYPTPROV hCryptProv;        HCRYPTKEY hKey;        HCRYPTHASH hHash;        char toBeEncrypted[] = "String to be encrypted";        DWORD encryptedLen = strlen(toBeEncrypted)*sizeof(char);        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, strlen(cryptoKey)*sizeof(char), 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,代码行数:69,


示例23: goodG2B2

/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */static void goodG2B2(){    char * cryptoKey;    char cryptoKeyBuffer[100] = "";    cryptoKey = cryptoKeyBuffer;    if(STATIC_CONST_FIVE==5)    {        {            size_t cryptoKeyLen = strlen(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 (fgets(cryptoKey+cryptoKeyLen, (int)(100-cryptoKeyLen), stdin) == NULL)                {                    printLine("fgets() failed");                    /* Restore NUL terminator if fgets fails */                    cryptoKey[cryptoKeyLen] = '/0';                }                /* The next 3 lines remove the carriage return from the string that is                 * inserted by fgets() */                cryptoKeyLen = strlen(cryptoKey);                if (cryptoKeyLen > 0)                {                    cryptoKey[cryptoKeyLen-1] = '/0';                }            }        }    }    {        HCRYPTPROV hCryptProv;        HCRYPTKEY hKey;        HCRYPTHASH hHash;        char toBeEncrypted[] = "String to be encrypted";        DWORD encryptedLen = strlen(toBeEncrypted)*sizeof(char);        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, strlen(cryptoKey)*sizeof(char), 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,代码行数:89,


示例24: _tmain

void _tmain(int argc, TCHAR *argv[]){   BOOL fResult = FALSE;   HCRYPTPROV hProv = NULL;   HCRYPTHASH hHash = NULL;   HCRYPTKEY hSessionKey = NULL;   HANDLE hInFile = INVALID_HANDLE_VALUE;   HANDLE hOutFile = INVALID_HANDLE_VALUE;   BOOL fEncrypt = FALSE;   BOOL finished = FALSE;   BYTE pbBuffer[OUT_BUFFER_SIZE];   DWORD dwByteCount = 0;   DWORD dwBytesWritten = 0;   if (argc != 5)   {      PrintUsage();      return;   }   __try   {      /* Check whether the action to be performed is encrypt or decrypt */      if (_tcsicmp(argv[2], _T("/e")) == 0)      {         fEncrypt = TRUE;      }      else if (_tcsicmp(argv[2], _T("/d")) == 0)      {         fEncrypt = FALSE;      }      else      {         PrintUsage();         return;      }      // Open the input file to be encrypted or decrypted      hInFile = CreateFile(argv[3],                  GENERIC_READ,                  0,                  NULL,                  OPEN_EXISTING,                   FILE_ATTRIBUTE_NORMAL,                  NULL);      if (hInFile == INVALID_HANDLE_VALUE)      {         _tprintf(_T("CreateFile failed with %d/n"), GetLastError());         __leave;      }      // Open the output file to write the encrypted or decrypted data      hOutFile = CreateFile(argv[4],                  GENERIC_WRITE,                  0,                  NULL,                  CREATE_ALWAYS,                   FILE_ATTRIBUTE_NORMAL,                  NULL);      if (hOutFile == INVALID_HANDLE_VALUE)      {         _tprintf(_T("CreateFile failed with %d/n"), GetLastError());         __leave;      }           // Acquire a handle to MS_DEF_PROV using CRYPT_VERIFYCONTEXT for dwFlags      // parameter as we are going to do only session key encryption or decryption      fResult = CryptAcquireContext(&hProv,                                    NULL,                                    MS_DEF_PROV,                                     PROV_RSA_FULL,                                    CRYPT_VERIFYCONTEXT);      if (!fResult)      {         _tprintf(_T("CryptAcquireContext failed with %X/n"), GetLastError());         __leave;      }      fResult = CryptCreateHash(hProv, CALG_SHA1, 0, 0, &hHash);      if (!fResult)      {         _tprintf(_T("CryptCreateHash failed with %X/n"), GetLastError());         __leave;      }      // Hash the supplied secret password      fResult = CryptHashData(hHash, (LPBYTE)argv[1], (DWORD)_tcslen(argv[1]), 0);      if (!fResult)      {         _tprintf(_T("CryptHashData failed with %X/n"), GetLastError());         __leave;      }      // Derive a symmetric session key from password hash      fResult = CryptDeriveKey(hProv, CALG_RC4, hHash, 0, &hSessionKey);      if (!fResult)      {         _tprintf(_T("CryptDeriveKey failed with %X/n"), GetLastError());         __leave;      }//.........这里部分代码省略.........
开发者ID:Essjay1,项目名称:Windows-classic-samples,代码行数:101,


示例25: CWE321_Hard_Coded_Cryptographic_Key__w32_char_64b_goodG2BSink

/* goodG2B uses the GoodSource with the BadSink */void CWE321_Hard_Coded_Cryptographic_Key__w32_char_64b_goodG2BSink(void * cryptoKeyVoidPtr){    /* cast void pointer to a pointer of the appropriate type */    char * * cryptoKeyPtr = (char * *)cryptoKeyVoidPtr;    /* dereference cryptoKeyPtr into cryptoKey */    char * cryptoKey = (*cryptoKeyPtr);    {        HCRYPTPROV hCryptProv;        HCRYPTKEY hKey;        HCRYPTHASH hHash;        char toBeEncrypted[] = "String to be encrypted";        DWORD encryptedLen = strlen(toBeEncrypted)*sizeof(char);        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, strlen(cryptoKey)*sizeof(char), 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,代码行数:66,


示例26: 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_64b_goodG2BSink(&data);}
开发者ID:gpwi970725,项目名称:testJuliet2,代码行数:78,


示例27: CWE256_Plaintext_Storage_of_Password__w32_char_53d_goodB2GSink

/* goodB2G uses the BadSource with the GoodSink */void CWE256_Plaintext_Storage_of_Password__w32_char_53d_goodB2GSink(char * data){    {        HANDLE pHandle;        char * username = "User";        char * domain = "Domain";        char hashData[100] = HASH_INPUT;        HCRYPTPROV hCryptProv = 0;        HCRYPTHASH hHash = 0;        HCRYPTKEY hKey = 0;        do        {            BYTE payload[(100 - 1) * sizeof(char)]; /* same size as data except for NUL terminator */            DWORD payloadBytes;            /* Hex-decode the input string into raw bytes */            payloadBytes = decodeHexChars(payload, sizeof(payload), data);            /* Wipe the hex string, to prevent it from being given to LogonUserA if             * any of the crypto calls fail. */            SecureZeroMemory(data, 100 * sizeof(char));            /* 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(char)] = '/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 (LogonUserA(                    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,代码行数:79,


示例28: bad

void bad(){    wchar_t * cryptoKey;    wchar_t cryptoKeyBuffer[100] = L"";    cryptoKey = cryptoKeyBuffer;    badSource(cryptoKey);    {        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,代码行数:65,



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


C++ CryptDestroyHash函数代码示例
C++ CryptDecrypt函数代码示例
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。