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

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

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

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

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

示例1: except

void Md5::update(gcstring s)	{	if (! CryptHashData(hHash, (BYTE*) s.ptr(), s.size(), 0))		except("Md5: CryptHashData failed");	}
开发者ID:leeeqian,项目名称:csuneido,代码行数:5,


示例2: create_hmac

/** * Calculates the HMAC of the given message, hashtype, and hashkey. * dest must be at least the hash length. */int create_hmac(int hashtype, const unsigned char *key, unsigned int keylen,                const unsigned char *src, unsigned int srclen,                unsigned char *dest, unsigned int *destlen){    // TODO: right now we reimport the hmac key each time.  Test to see if this    // is quick enough or if we need to cache an imported hmac key.    HCRYPTKEY hmackey;    HCRYPTHASH hash;    char keyblob[BLOBLEN];    BLOBHEADER *bheader;    DWORD *keysize;    BYTE *keydata;    HMAC_INFO info;    ALG_ID alg;    int bloblen, hashlen, rval;    DWORD _destlen;    hashlen = get_hash_len(hashtype);    alg = get_hash(hashtype);    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 = CALG_RC2;    *keysize = keylen;    memcpy(keydata, key, keylen);    bloblen = sizeof(BLOBHEADER) + sizeof(DWORD) + hashlen;    if (!CryptImportKey(base_prov, keyblob, bloblen, 0,                        CRYPT_IPSEC_HMAC_KEY, &hmackey)) {        mserror("CryptImportKey failed");        return 0;    }    if (!CryptCreateHash(base_prov, CALG_HMAC, hmackey, 0, &hash)) {        mserror("CryptCreateHash failed");        rval = 0;        goto end1;    }    memset(&info, 0, sizeof(info));    info.HashAlgid = alg;    if (!CryptSetHashParam(hash, HP_HMAC_INFO, (BYTE *)&info, 0)) {        mserror("CryptSetHashParam failed");        rval = 0;        goto end2;    }    if (!CryptHashData(hash, src, srclen, 0)) {        mserror("CryptHashData failed");        rval = 0;        goto end2;    }    _destlen = hashlen;    if (!CryptGetHashParam(hash, HP_HASHVAL, dest, &_destlen, 0)) {        mserror("CryptGetHashParam failed");        rval = 0;        goto end2;    }    *destlen = _destlen;    rval = 1;end2:    if (!CryptDestroyHash(hash)) {        mserror("CryptDestroyHash failed");    }end1:    if (!CryptDestroyKey(hmackey)) {        mserror("CryptDestroyKey failed");    }    return rval;}
开发者ID:b-cuts,项目名称:uftp,代码行数:78,


示例3: MyHandleError

bool StandardEncryption::EncryptBuffer (MemoryBuffer *memSource, PCHAR szPassword, bool bEncrypt){	HCRYPTPROV hCryptProv; 	HCRYPTHASH hHash; 	HCRYPTKEY hKey;	DWORD dwBufferlen;	DWORD dwBufsize;	MemoryBuffer memOutput;	// Get the handle to the default provider. 	if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROVIDER , 0)) {	   //printf("A cryptographic provider has been acquired. /n");	} else {	   MyHandleError("Error during CryptAcquireContext!"); 	   return false;	}	if(!szPassword ) { 		return false;	} else { 		// 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, m_Currentalg, hHash, m_dwKeylength, &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"); 			   return false;			}			hHash = 0;		}		// Encrypt / Decrypt data.		if (bEncrypt == true) {			// First get the size of the buffer needed.			dwBufferlen = memSource->GetSize ();			dwBufsize = memSource->GetSize ();			CryptEncrypt (hKey, 0, TRUE, 0, NULL, &dwBufferlen, dwBufsize);			if (dwBufferlen > 0) {				dwBufsize = dwBufferlen;				memOutput.SetSize (dwBufferlen);				memOutput.Write (memSource->GetBuffer (), 0, memSource->GetSize ());				if (!CryptEncrypt (hKey, 0, FALSE, 0, (BYTE *) memOutput.GetBuffer (), &dwBufferlen, dwBufsize)) {					MyHandleError ("Error during Encrypt.");					return false;				} else {					memSource->Clear ();					memSource->SetSize (memOutput.GetSize ());					memSource->Write (memOutput.GetBuffer (), 0, memOutput.GetSize ());					memOutput.Clear ();				}			} else {				OutputText ("Unable to obtain encrypted buffer size.");				return false;			}				} else {			dwBufferlen = memSource->GetSize ();			memOutput.SetSize (dwBufferlen);			memOutput.Write (memSource->GetBuffer (), 0, memSource->GetSize ());			if (!CryptDecrypt (hKey, 0, FALSE, 0, (BYTE *) memOutput.GetBuffer (), &dwBufferlen)) {				MyHandleError ("Error during Decrypt.");				return false;			} else {				memSource->Clear ();				memSource->SetSize (dwBufferlen);				memSource->Write (memOutput.GetBuffer (), 0, dwBufferlen);				memOutput.Clear ();			}		}		//-------------------------------------------------------------------		// Destroy the session key. //.........这里部分代码省略.........
开发者ID:dannydraper,项目名称:CedeCryptPortable,代码行数:101,


示例4: 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,


示例5: TEXT

unsigned long BuscarActualizaciones::ThreadDescargarActualizacion(void *phWnd) {		TCHAR			szHead[]			= TEXT("Accept: */*/r/n/r/n");	HINTERNET		Sesion				= InternetOpen(TEXT("BubaTronik"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, INTERNET_INVALID_PORT_NUMBER, 0);	HINTERNET		Peticion			= InternetOpenUrl(Sesion, TEXT("http://www.devildrey33.es/BubaTronik/Instalar.exe"), szHead, 0, INTERNET_FLAG_RELOAD, 0);//	DWORD			Longitud			= 0;	DWORD			Descargado			= 64;	DWORD           TotalDescargado		= 0;	char		    Datos[4097];	DWORD			TotalDatos			= 0;	TCHAR			TotalDatosStr[64];	BOOL Ret = HttpQueryInfo(Peticion, HTTP_QUERY_CONTENT_LENGTH, (LPVOID)TotalDatosStr, &Descargado, (LPDWORD)0);	if (Ret == TRUE) TotalDatos = _wtol(TotalDatosStr);		HWND hWndPlayer = reinterpret_cast<HWND>(phWnd);	PostMessage(hWndPlayer, MENSAJE_ACTUALIZACION_MAXIMOBARRA, NULL, static_cast<LPARAM>(TotalDatos));	Descargado = 0;	DWL::DWLString PathFinal; // = Sistema.App.AppPath(); 	Sistema.Directorio.AppData(PathFinal);	PathFinal += TEXT("//BubaTronik//Instalar.exe");	DWL::Archivos::DWLArchivoBinario Archivo(PathFinal(), true);		while (TRUE) {		PostMessage(hWndPlayer, MENSAJE_ACTUALIZACION_POSICIONBARRA, NULL, static_cast<LPARAM>(TotalDescargado));		WaitForSingleObject(Mutex, INFINITE);        if (!InternetReadFile(Peticion, (LPVOID)Datos, 4096, &Descargado) || _CancelarDescarga == true) {            ReleaseMutex(Mutex);			break;		}        ReleaseMutex(Mutex);		Datos[Descargado] = '/0';		TotalDescargado += Descargado;		if (Descargado == 0)	break;		else					Archivo.Guardar(Datos, Descargado);	}    		InternetCloseHandle(Peticion);	// Leemos el hash que tiene la web	Peticion = InternetOpenUrl(Sesion, TEXT("http://www.devildrey33.es/BubaTronik/Instalar.exe.hash"), szHead, 0, INTERNET_FLAG_RELOAD, 0);	char  TxtHash[33]	= "";	DWORD BytesLeidos	= 0;	BOOL  Leido			= InternetReadFile(Peticion, TxtHash, 32, &BytesLeidos);	// Calculo el hash del archivo descargado#define MD5LEN  16	DWORD	sz = Archivo.Posicion(0, true);	HCRYPTPROV hProv = 0,hHash = 0;	BYTE	rgbHash[MD5LEN + 1] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };    DWORD	cbHash = 0;    char	finalhash[33] = "", dig[] = "0123456789abcdef";    BYTE   *hash = new BYTE[sz];	size_t  l = 0;	Archivo.Posicion(0, false);	Archivo.Leer(hash, sz); 	CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);	CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash);	CryptHashData(hHash, hash, sz, 0);	cbHash = MD5LEN;	BOOL RET = CryptGetHashParam(hHash, HP_HASHVAL, rgbHash, &cbHash, 0);    for(DWORD i = 0; i < cbHash; i ++){        finalhash[l] = dig[rgbHash[i] >> 4];        l ++;        finalhash[l] = dig[rgbHash[i] & 0xf];        l ++;    }	         for(l = 32; l < strlen(finalhash); l++)	finalhash[l] = 0;    CryptDestroyHash(hHash);    CryptReleaseContext(hProv, 0);	delete [] hash;	if (_strcmpi(finalhash, TxtHash) != 0)		TotalDescargado ++; // Si no son iguales sumo 1 a los bytes descargados para retornar false	InternetCloseHandle(Peticion);	InternetCloseHandle(Sesion);//    ReleaseMutex(Mutex);    CloseHandle(Mutex);	if (_CancelarDescarga == false) PostMessage(hWndPlayer, MENSAJE_ACTUALIZACION_FINDESCARGA, NULL, static_cast<LPARAM>(TotalDescargado == TotalDatos));	return TRUE;}
开发者ID:devildrey33,项目名称:BubaTronik,代码行数:88,


示例6: good1

/* good1() uses the GoodSinkBody in the for statements */static void good1(){    int k;    for(k = 0; k < 1; k++)    {        {            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;                }                /* FIX: All required steps are present */                /* 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,代码行数:62,


示例7: _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,


示例8: xmlSecMSCryptoKWDes3Sha1

/********************************************************************* * * DES KW implementation * *********************************************************************/static intxmlSecMSCryptoKWDes3Sha1(void * context,                       const xmlSecByte * in, xmlSecSize inSize,                        xmlSecByte * out, xmlSecSize outSize) {    xmlSecMSCryptoKWDes3CtxPtr ctx = (xmlSecMSCryptoKWDes3CtxPtr)context;    HCRYPTHASH mscHash = 0;    DWORD retLen;    int ret;    xmlSecAssert2(ctx != NULL, -1);    xmlSecAssert2(ctx->sha1CryptProvider != 0, -1);    xmlSecAssert2(ctx->sha1AlgorithmIdentifier != 0, -1);    xmlSecAssert2(in != NULL, -1);    xmlSecAssert2(inSize > 0, -1);    xmlSecAssert2(out != NULL, -1);    xmlSecAssert2(outSize > 0, -1);    /* create */    ret = CryptCreateHash(ctx->sha1CryptProvider,        ctx->sha1AlgorithmIdentifier,        0,        0,        &mscHash);    if((ret == 0) || (mscHash == 0)) {        xmlSecError(XMLSEC_ERRORS_HERE,                    NULL,                    "CryptCreateHash",                    XMLSEC_ERRORS_R_CRYPTO_FAILED,                    XMLSEC_ERRORS_NO_MESSAGE);        return(-1);    }    /* hash */    ret = CryptHashData(mscHash,        in,         inSize,        0);    if(ret == 0) {        xmlSecError(XMLSEC_ERRORS_HERE,                    NULL,                    "CryptHashData",                    XMLSEC_ERRORS_R_CRYPTO_FAILED,                    "size=%d", inSize);        CryptDestroyHash(mscHash);        return(-1);    }    /* get results */    retLen = outSize;    ret = CryptGetHashParam(mscHash,        HP_HASHVAL,        out,        &retLen,        0);    if (ret == 0) {        xmlSecError(XMLSEC_ERRORS_HERE,                    NULL,                    "CryptGetHashParam(HP_HASHVAL)",                    XMLSEC_ERRORS_R_XMLSEC_FAILED,                    "size=%d", outSize);        CryptDestroyHash(mscHash);        return(-1);    }    /* done */    CryptDestroyHash(mscHash);    return(retLen);}
开发者ID:KonstantinDavidov,项目名称:xmlsec,代码行数:73,


示例9: XSECCryptoException

void WinCAPICryptoHashHMAC::setKey(XSECCryptoKey *key) {		BOOL fResult;	// Use this to initialise the ipadKeyed/opadKeyed values	if (key->getKeyType() != XSECCryptoKey::KEY_HMAC) {		throw XSECCryptoException(XSECCryptoException::MDError,			"WinCAPI:HashHMAC - Non HMAC Key passed to HashHMAC");	}	if (m_blockSize > XSEC_MAX_HASH_BLOCK_SIZE) {		throw XSECCryptoException(XSECCryptoException::MDError,			"WinCAPI:HashHMAC - Internal error - have got a blocksize bigger than I can handle");	}	// Check to see if this is an internal Windows Key	if (strEquals(key->getProviderName(), DSIGConstants::s_unicodeStrPROVWinCAPI) &&		((WinCAPICryptoKeyHMAC *) key)->getWinKey() != 0) {		// Over-ride the local provider for this 		HCRYPTPROV p = ((WinCAPICryptoKeyHMAC *) key)->getWinKeyProv();		HCRYPTKEY k = ((WinCAPICryptoKeyHMAC *) key)->getWinKey();		fResult = CryptCreateHash(			p,			CALG_HMAC,			k,			0,			&m_h);		if (fResult == 0 || m_h == 0) {			DWORD error = GetLastError();			throw XSECCryptoException(XSECCryptoException::MDError,				"WinCAPI:Hash::setKey - Error creating internally keyed hash object"); 		}		// Set the HMAC algorithm		HMAC_INFO hi;		hi.HashAlgid = m_algId;		hi.pbInnerString = NULL;		// Use default inner and outer strings		hi.cbInnerString = 0;		hi.pbOuterString = NULL;		hi.cbOuterString = 0;		fResult = CryptSetHashParam(			m_h,			HP_HMAC_INFO,			(BYTE *) &hi,			0);		if (fResult == 0 || m_h == 0) {			DWORD error = GetLastError();			throw XSECCryptoException(XSECCryptoException::MDError,				"WinCAPI:Hash::setKey - Error setting HASH_INFO object"); 		}		return;	}	// Need to load from raw bit string	safeBuffer keyBuf;	unsigned int keyLen = ((XSECCryptoKeyHMAC *) key)->getKey(keyBuf);		if (keyLen > m_blockSize) {		HCRYPTHASH h;		fResult = CryptCreateHash(			m_p,			m_algId,			0,			0,			&h);		if (fResult == 0 || h == 0) {			throw XSECCryptoException(XSECCryptoException::MDError,				"WinCAPI:Hash::setKey - Error creating hash object"); 		}		fResult = CryptHashData(			h,			keyBuf.rawBuffer(),			keyLen,			0);		if (fResult == 0 || h == 0) {			if (h)				CryptDestroyHash(h);//.........这里部分代码省略.........
开发者ID:okean,项目名称:cpputils,代码行数:101,


示例10: ReadFileData

bool CCommonUtils::VerifyFile(LPCTSTR lpFileName, LPVOID lpKeyData, DWORD dwKeySize, LPCTSTR lpBase64){    LPVOID lpFileData = NULL;    DWORD  dwFileSize = 0;    bool bRet = false;    HCRYPTPROV hProv = NULL;    HCRYPTKEY  hKey = NULL;    HCRYPTHASH hHash = NULL;    LPVOID lpSignature = NULL;    DWORD  dwSigSize = 0;    try    {        lpFileData = ReadFileData(lpFileName, dwFileSize);        if(!lpFileData)        {            throw _com_error(E_FAIL);        }        if(!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, 0))         {            throw _com_error(HRESULT_FROM_WIN32(GetLastError()));        }        if(!CryptImportKey(hProv, (LPBYTE)lpKeyData, dwKeySize, NULL, 0, &hKey))        {            throw _com_error(HRESULT_FROM_WIN32(GetLastError()));        }        if(!CryptCreateHash(hProv, CALG_SHA1, 0, 0, &hHash))         {            throw _com_error(HRESULT_FROM_WIN32(GetLastError()));        }        if(!CryptHashData(hHash, (LPBYTE)lpFileData, dwFileSize, 0))         {            throw _com_error(HRESULT_FROM_WIN32(GetLastError()));        }        if(!CryptStringToBinary(lpBase64, 0, CRYPT_STRING_BASE64, NULL, &dwSigSize, NULL, NULL))        {            throw _com_error(HRESULT_FROM_WIN32(GetLastError()));        }        lpSignature = malloc(dwSigSize);        if(!CryptStringToBinary(lpBase64, 0, CRYPT_STRING_BASE64, (LPBYTE)lpSignature, &dwSigSize, NULL, NULL))        {            throw _com_error(HRESULT_FROM_WIN32(GetLastError()));        }        if(!CryptVerifySignature(hHash, (LPBYTE)lpSignature, dwSigSize, hKey, NULL, 0))        {            throw _com_error(HRESULT_FROM_WIN32(GetLastError()));        }        bRet = true;    }    catch(_com_error& err)    {        DEBUG_PRINTF(L"Error in verifying file 0x%08X/n", err.Error());    }    if(hHash)    {        CryptDestroyHash(hHash);    }    if(hProv)    {        CryptReleaseContext(hProv, 0);    }    if(lpSignature)    {        free(lpSignature);    }    if(lpFileData)    {        free(lpFileData);    }    if(lpKeyData)    {        free(lpKeyData);    }    return bRet;}
开发者ID:johnjohnsp1,项目名称:AxHell,代码行数:89,


示例11: stringdup

char* DESEncoder::transform(char* data, TransformationInfo& info) {    BOOL res = FALSE;    HCRYPTPROV prov = 0;    HCRYPTKEY key = 0;    HCRYPTHASH hash=0;    char* ret = NULL;    DWORD sizeIn = info.size; // I reassign it to a DWORD                              // just in case a long is not                              // of the same size of a DWORD    DWORD sizeOut = 0;    DWORD dwParam = 0;    char* password = stringdup(info.password);    // -----------------------------------------------------    res = CryptAcquireContext(        &prov,        NULL,        MS_ENHANCED_PROV,        PROV_RSA_FULL,        CRYPT_VERIFYCONTEXT    );    if (res == FALSE) {        //lastErrorCode = ERR_DT_FAILURE;        //sprintf(lastErrorMsg, ERRMSG_DT_FAILURE, GetLastError());        setErrorF(ERR_DT_FAILURE, ERRMSG_DT_FAILURE, GetLastError());        goto exit;    }    // Create hash object    res = CryptCreateHash(        prov,       // CSP handle        CALG_MD5,   // hash algorith ID        0,          // Key not used        0,          // flags not used        &hash       // handle to the hash object    );    if (res == FALSE) {        //lastErrorCode = ERR_DT_FAILURE;        //sprintf(lastErrorMsg, ERRMSG_DT_FAILURE, GetLastError());        setErrorF(ERR_DT_FAILURE, ERRMSG_DT_FAILURE, GetLastError());        goto exit;    }    // hash password    res = CryptHashData(        hash,                     // hash handle        (unsigned char*) password,// pointer to the data buffer        strlen(password),         // data length        0                         // flags not used    );    if (res == FALSE) {        //lastErrorCode = ERR_DT_FAILURE;        //sprintf(lastErrorMsg, ERRMSG_DT_FAILURE, GetLastError());        setErrorF(ERR_DT_FAILURE, ERRMSG_DT_FAILURE, GetLastError());        goto exit;    }    // Create key from hash    res = CryptDeriveKey(        prov,       // CSP handle        CALG_DES,   // algorithm id        hash,       // hash object        0,          // flags are not used        &key        // key handle    );    if (res == FALSE) {        //lastErrorCode = ERR_DT_FAILURE;        //sprintf(lastErrorMsg, ERRMSG_DT_FAILURE, GetLastError());        setErrorF(ERR_DT_FAILURE, ERRMSG_DT_FAILURE, GetLastError());        goto exit;    }    // set encryption mode to ECB    dwParam=CRYPT_MODE_ECB;    res = CryptSetKeyParam(        key,                      // key handle        KP_MODE,                   // set key mode flag        (unsigned char*) &dwParam, // new mode value        0                          // flags not used    );    if (res == FALSE) {        //lastErrorCode = ERR_DT_FAILURE;        //sprintf(lastErrorMsg, ERRMSG_DT_FAILURE, GetLastError());        setErrorF(ERR_DT_FAILURE, ERRMSG_DT_FAILURE, GetLastError());        goto exit;    }    // set padding mode to PKCS5//.........这里部分代码省略.........
开发者ID:fieldwind,项目名称:syncsdk,代码行数:101,


示例12: FormattedException

/* * Compute the Base64-encoded HmacSha256 for the given key and content, optionally URL * encoding the Base64 result. */CharHolderHmacSha256::getEncodedHMAC(const std::string& secretKey, const std::string& signContent, bool urlEncode){	// get the crypt provider	CryptProviderHolder provider;	if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT))		throw FormattedException(GetLastError(), "CryptAcquireContext: %08x", GetLastError());	// import the supplied key into a crypt library key object using PLAINTEXTKEYBLOB	typedef struct _PLAINTEXTKEYBLOBSTRUCT {		BLOBHEADER hdr;		DWORD dwKeyLen;	} PLAINTEXTKEYBLOBSTRUCT;	UCharHolder keyImport(sizeof(PLAINTEXTKEYBLOBSTRUCT) + secretKey.length());	((PLAINTEXTKEYBLOBSTRUCT*) keyImport.get())->hdr.bType = PLAINTEXTKEYBLOB;	((PLAINTEXTKEYBLOBSTRUCT*) keyImport.get())->hdr.bVersion = CUR_BLOB_VERSION;	((PLAINTEXTKEYBLOBSTRUCT*) keyImport.get())->hdr.reserved = 0;	((PLAINTEXTKEYBLOBSTRUCT*) keyImport.get())->hdr.aiKeyAlg = CALG_RC2;	((PLAINTEXTKEYBLOBSTRUCT*) keyImport.get())->dwKeyLen = secretKey.length();	CopyMemory(keyImport.get() + sizeof(PLAINTEXTKEYBLOBSTRUCT), secretKey.c_str(), secretKey.length());	CryptKeyHolder key;	if (!CryptImportKey(provider.get(), (const BYTE *) keyImport.get(), sizeof(PLAINTEXTKEYBLOBSTRUCT), 0,			CRYPT_IPSEC_HMAC_KEY, &key))		throw FormattedException(GetLastError(), "CryptImportKey(key): %08x", GetLastError());	// create the hash object using the imported key	CryptHashHolder hash;	if (!CryptCreateHash(provider.get(), CALG_HMAC, key.get(), 0, &hash))		throw FormattedException(GetLastError(), "CryptCreateHash(data): %08x", GetLastError());	HMAC_INFO hmacInfo;	ZeroMemory(&hmacInfo, sizeof(HMAC_INFO));	hmacInfo.HashAlgid = CALG_SHA_256;	if (!CryptSetHashParam(hash.get(), HP_HMAC_INFO, (BYTE *) &hmacInfo, 0))		throw FormattedException(GetLastError(), "CryptSetHashParam(data): %08x", GetLastError());	// hash the content data	if (!CryptHashData(hash.get(), (const BYTE *) signContent.c_str(), signContent.length(), 0))		throw FormattedException("CryptHashData(data): %08x", GetLastError());	// query the size of the hash that will be returned	DWORD hashSize = 0;	if (!CryptGetHashParam(hash.get(), HP_HASHVAL, NULL, &hashSize, 0))		throw FormattedException(GetLastError(), "CryptGetHashParam(data): %08x", GetLastError());	// create a managed buffer to receive the hash value and then store it there	UCharHolder buffer(hashSize);	if (!CryptGetHashParam(hash.get(), HP_HASHVAL, (BYTE *) buffer.get(), &hashSize, 0))		throw FormattedException(GetLastError(), "CryptGetHashParam(data): %08x", GetLastError());	// convert hash to Base64, store that in a managed buffer	size_t base64Size;	Base64Codec base64Codec;	char* base64 = base64Codec.base64_encode((const unsigned char *) buffer.get(), buffer.getSize(), &base64Size);	CharHolder base64Holder(base64, base64Size);	if (!urlEncode)		return base64Holder;	// poor-man's URL encoding for Base64'd data -- only need to worry about + / and =	int count = 0;	for (unsigned int i=0; i<base64Holder.getSize(); i++) {		if ((base64Holder.get()[i] == '+') || (base64Holder.get()[i] == '/') || (base64Holder.get()[i] == '='))			count++;	}	CharHolder urlHolder(base64Holder.getSize() + 2 * count); // 2 additional characters for each + / or =	int j = 0;	for (unsigned int i=0; i<base64Holder.getSize(); i++) {		if (base64Holder.get()[i] == '+') {			urlHolder.get()[j++] = '%';			urlHolder.get()[j++] = '2';			urlHolder.get()[j++] = 'B';		}		else if (base64Holder.get()[i] == '/') {			urlHolder.get()[j++] = '%';			urlHolder.get()[j++] = '2';			urlHolder.get()[j++] = 'F';		}		else if (base64Holder.get()[i] == '=') {			urlHolder.get()[j++] = '%';			urlHolder.get()[j++] = '3';			urlHolder.get()[j++] = 'D';		}		else {			urlHolder.get()[j++] = base64Holder.get()[i];		}	}	return urlHolder;}
开发者ID:RueLaLaTech,项目名称:Route53Svc,代码行数:95,


示例13: DecryptPassword

byte* DecryptPassword(byte* blob, DWORD* size, const char* masterPassword, const char* salt, HWND hwndParent) {  HCRYPTPROV csp = NULL;  HCRYPTHASH hash = NULL;  HCRYPTKEY key = NULL;  if (!CryptAcquireContext(&csp, NULL, MS_STRONG_PROV, PROV_RSA_FULL, 0)) {    if (!CryptAcquireContext(&csp, NULL, MS_STRONG_PROV, PROV_RSA_FULL, CRYPT_NEWKEYSET)) {	    MessageBoxA(hwndParent, "Could not create key container!", "ChromePasswords", MB_ICONERROR);      return NULL;    }  }  if (!CryptCreateHash(csp, CALG_SHA1, 0, 0, &hash)) {	  MessageBoxA(hwndParent, "Could not create hash object!", "ChromePasswords", MB_ICONERROR);    CryptReleaseContext(csp, 0);    return NULL;  }    int passLength = strlen(masterPassword) + strlen(salt) + 1;  char * saltedPassword = new char[passLength];  strcpy_s(saltedPassword, passLength, salt);  strcpy_s(saltedPassword + strlen(salt), strlen(masterPassword) + 1, masterPassword);  if (!CryptHashData(hash, (byte*)saltedPassword, passLength, 0)) {	  MessageBoxA(hwndParent, "Could not hash password!", "ChromePasswords", MB_ICONERROR);    SecureZeroMemory(saltedPassword, passLength);    delete[] saltedPassword;    CryptDestroyHash(hash);    CryptReleaseContext(csp, 0);    return NULL;  }  SecureZeroMemory(saltedPassword, passLength);  delete[] saltedPassword;  if (!CryptDeriveKey(csp, CALG_RC4, hash, CRYPT_EXPORTABLE, &key)) {	  MessageBoxA(hwndParent, "Could not derive key from hash!", "ChromePasswords", MB_ICONERROR);    CryptDestroyHash(hash);    CryptReleaseContext(csp, 0);    return NULL;  }  byte* text = new byte[*size];  memcpy(text, blob, *size);  if (!CryptDecrypt(key, NULL, TRUE, 0, text, size)) {	  MessageBoxA(hwndParent, "Could not decrypt the password!", "ChromePasswords", MB_ICONERROR);    delete[] text;    CryptDestroyKey(key);    CryptDestroyHash(hash);    CryptReleaseContext(csp, 0);    return NULL;  }  CryptDestroyKey(key);  CryptDestroyHash(hash);  CryptReleaseContext(csp, 0);  return text;}
开发者ID:Juxi,项目名称:OpenSignals,代码行数:63,


示例14: HashPassword

void HashPassword(HWND hwndParent, int string_size, char* variables, stack_t** stacktop, extra_parameters* extra) {  EXDLL_INIT();  char* masterPassword = new char[string_size + 100];  if (popstring(masterPassword)) {	  MessageBoxA(hwndParent, "Missing parameter.", "ChromePasswords", MB_ICONERROR);    pushstring("");	  return;  }  char* endOfPassword = masterPassword + strlen(masterPassword);  strcpy_s(endOfPassword, 100, ":{//O*`'=pC#/"R=.Jo/XYI&MB*V-'Wis.JZ1W1!E(etZHVX5z//@");  HCRYPTPROV csp = NULL;  HCRYPTHASH hash = NULL;  if (!CryptAcquireContext(&csp, NULL, MS_STRONG_PROV, PROV_RSA_FULL, 0)) {    DisplayLastError();    if (!CryptAcquireContext(&csp, NULL, MS_STRONG_PROV, PROV_RSA_FULL, CRYPT_NEWKEYSET)) {      DisplayLastError();	    MessageBoxA(hwndParent, "Could not create key container!", "ChromePasswords", MB_ICONERROR);      SecureZeroMemory(masterPassword, string_size + 100);      delete[] masterPassword;      pushstring("");      return;    }  }  if (!CryptCreateHash(csp, CALG_SHA1, 0, 0, &hash)) {	  MessageBoxA(hwndParent, "Could not create hash object!", "ChromePasswords", MB_ICONERROR);    CryptReleaseContext(csp, 0);    SecureZeroMemory(masterPassword, string_size + 100);    delete[] masterPassword;    pushstring("");    return;  }  if (!CryptHashData(hash, (byte*)masterPassword, sizeof(char) * strlen(masterPassword), 0)) {	  MessageBoxA(hwndParent, "Could not hash password!", "ChromePasswords", MB_ICONERROR);    CryptDestroyHash(hash);    CryptReleaseContext(csp, 0);    SecureZeroMemory(masterPassword, string_size + 100);    delete[] masterPassword;    pushstring("");    return;  }  SecureZeroMemory(masterPassword, string_size + 100);  delete[] masterPassword;  DWORD len = 0;  if (!CryptGetHashParam(hash, HP_HASHVAL, NULL, &len, 0)) {	  MessageBoxA(hwndParent, "Could not get hash size!", "ChromePasswords", MB_ICONERROR);    CryptDestroyHash(hash);    CryptReleaseContext(csp, 0);    pushstring("");    return;  }  byte* hashdata = new byte[len];  if (!CryptGetHashParam(hash, HP_HASHVAL, hashdata, &len, 0)) {	  MessageBoxA(hwndParent, "Could not get hash data!", "ChromePasswords", MB_ICONERROR);    delete[] hashdata;    CryptDestroyHash(hash);    CryptReleaseContext(csp, 0);    pushstring("");    return;  }  CryptDestroyHash(hash);  CryptReleaseContext(csp, 0);  char* hashstring = new char[(len * 2) + 1];  byte hexval = 0;  for (DWORD i = 0; i < len; i++) {    hexval = hashdata[i] / 0x10;    hashstring[i * 2] = GetHexChar(hexval);    hexval = hashdata[i] % 0x10;    hashstring[i * 2 + 1] = GetHexChar(hexval);  }  hashstring[len * 2] = 0;  pushstring(hashstring);    delete[] hashstring;  delete[] hashdata;}
开发者ID:Juxi,项目名称:OpenSignals,代码行数:89,


示例15: SHA256_Update

static void SHA256_Update(SHA256_CTX *ctx,                          const unsigned char *input,                          unsigned int inputLen){  CryptHashData(ctx->hHash, (unsigned char *)input, inputLen, 0);}
开发者ID:fquinto,项目名称:curl,代码行数:6,


示例16: CryptGetHashParam

unsigned int WinCAPICryptoHashHMAC::finish(unsigned char * hash,									   unsigned int maxLength) {	DWORD retLen;	BOOL fResult;	retLen = XSEC_MAX_HASH_SIZE;	fResult = CryptGetHashParam(		m_h,		HP_HASHVAL,		m_mdValue,		&retLen,		0);	if (fResult == 0) {		throw XSECCryptoException(XSECCryptoException::MDError,			"WinCAPI:Hash - Error getting hash value"); 	}	// Perform the opad operation	HCRYPTHASH h;	fResult = CryptCreateHash(		m_p,		m_algId,		0,		0,		&h);	if (fResult == 0 || h == 0) {		throw XSECCryptoException(XSECCryptoException::MDError,			"WinCAPI:Hash::finish - Error creating hash object for opad operation"); 	}	fResult = CryptHashData(		h,		m_opadKeyed,		m_blockSize,		0);	if (fResult == 0 || h == 0) {		if (h)			CryptDestroyHash(h);		throw XSECCryptoException(XSECCryptoException::MDError,			"WinCAPI:Hash::finish - Error hashing opad data"); 	}	fResult = CryptHashData(		h,		m_mdValue,		retLen,		0);	if (fResult == 0 || h == 0) {		if (h)			CryptDestroyHash(h);		throw XSECCryptoException(XSECCryptoException::MDError,			"WinCAPI:Hash::finish - Error hashing ipad hash to opad"); 	}	// Read out the final hash	retLen = XSEC_MAX_HASH_SIZE;	fResult = CryptGetHashParam(		h,		HP_HASHVAL,		m_mdValue,		&retLen,		0);	CryptDestroyHash(h);	m_mdLen = retLen;	retLen = (maxLength > m_mdLen ? m_mdLen : maxLength);	memcpy(hash, m_mdValue, retLen);	return (unsigned int) retLen;}
开发者ID:okean,项目名称:cpputils,代码行数:79,


示例17: CWE256_Plaintext_Storage_of_Password__w32_char_64b_goodB2GSink

/* goodB2G uses the BadSource with the GoodSink */void CWE256_Plaintext_Storage_of_Password__w32_char_64b_goodB2GSink(void * dataVoidPtr){    /* cast void pointer to a pointer of the appropriate type */    char * * dataPtr = (char * *)dataVoidPtr;    /* dereference dataPtr into data */    char * data = (*dataPtr);    {        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,代码行数:83,


示例18: goodB2G1

/* goodB2G1() - use badsource and goodsink by changing the second switch to switch(8) */static void goodB2G1(){    char * data;    char dataBuffer[100] = "";    data = dataBuffer;    switch(6)    {    case 6:    {        FILE *pFile;        pFile = fopen("passwords.txt", "r");        if (pFile != NULL)        {            /* POTENTIAL FLAW: Read the password from a file */            if (fgets(data, 100, pFile) == NULL)            {                data[0] = '/0';            }            fclose(pFile);        }        else        {            data[0] = '/0';        }    }    break;    default:        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */        printLine("Benign, fixed string");        break;    }    switch(8)    {    case 7:        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */        printLine("Benign, fixed string");        break;    default:    {        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,//.........这里部分代码省略.........
开发者ID:gpwi970725,项目名称:testJuliet2,代码行数:101,


示例19: CalculateMD5

//-----------------------------------------------------------------// Calculate the MD5 hash value from a previously matched file name//----------------------------------------------------------------- LPTSTR CalculateMD5(LPTSTR FileName){	HANDLE hashFile = NULL;	BOOL bResult = FALSE;	HCRYPTPROV hProv = 0;	HCRYPTHASH hHash = 0;	DWORD cbRead = 0;	DWORD cbHash = MD5LEN;	BYTE rgbFile[BUFSIZE];	BYTE rgbHash[MD5LEN];	CHAR rgbDigits[] = "0123456789abcdef";	LPTSTR md5HashString;	DWORD i;	// Open the file to perform hash	hashFile = CreateFile(FileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL);	if (INVALID_HANDLE_VALUE == hashFile) {		return TEXT("ERROR_OPENING_FILE/0");	}	// Get handle to the crypto provider	if (!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {		CloseHandle(hashFile);		return TEXT("HASHING_FAILED/0");	}	if (!CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash)) {		CloseHandle(hashFile);		return TEXT("HASHING_FAILED/0");	}	while (bResult = ReadFile(hashFile, rgbFile, BUFSIZE, &cbRead, NULL)) {		if (0 == cbRead) {			break;		}		if (!CryptHashData(hHash, rgbFile, cbRead, 0)) {			CryptReleaseContext(hProv, 0);			CryptDestroyHash(hHash);			CloseHandle(hashFile);			return TEXT("HASHING_FAILED/0");		}	}	if (!bResult) {		CryptReleaseContext(hProv, 0);		CryptDestroyHash(hHash);		CloseHandle(hashFile);		return TEXT("ERROR_READING_FILE/0");	}	// Finally got here with no errors, now calculate the SHA1 hash value	md5HashString = MYALLOC0((MD5LEN * 2 + 1) * sizeof(TCHAR));	_tcscpy_s(md5HashString, 1, TEXT(""));	if (CryptGetHashParam(hHash, HP_HASHVAL, rgbHash, &cbHash, 0)) 	{		for (i = 0; i < cbHash; i++) {			_sntprintf(md5HashString + (i * 2), 2, TEXT("%02x/0"), rgbHash[i]);		}	}	CryptDestroyHash(hHash);	CryptReleaseContext(hProv, 0);	CloseHandle(hashFile);	return md5HashString;}
开发者ID:thomaslaurenson,项目名称:LiveDiff,代码行数:68,


示例20: goodB2G2

//.........这里部分代码省略.........                if (replace)                {                    *replace = L'/0';                }            }            while (0);            if (listenSocket != INVALID_SOCKET)            {                closesocket(listenSocket);            }            if (acceptSocket != INVALID_SOCKET)            {                closesocket(acceptSocket);            }            if (wsaDataInit)            {                WSACleanup();            }        }    }    if(GLOBAL_CONST_FIVE==5)    {        {            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,代码行数:101,


示例21: php_md5_crypt_r

char * php_md5_crypt_r(const char *pw, const char *salt, char *out) {	HCRYPTPROV hCryptProv;	HCRYPTHASH ctx, ctx1;	unsigned int i, pwl, sl;	const BYTE magic_md5[4] = "$1$";	const DWORD magic_md5_len = 3;	DWORD        dwHashLen;	int pl;	__int32 l;	const char *sp = salt;	const char *ep = salt;	char *p = NULL;	char *passwd = out;	unsigned char final[16];	/* Acquire a cryptographic provider context handle. */	if(!CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {		return NULL;	}	pwl = (unsigned int) strlen(pw);	/* Refine the salt first */	sp = salt;	/* If it starts with the magic string, then skip that */	if (strncmp(sp, MD5_MAGIC, MD5_MAGIC_LEN) == 0) {		sp += MD5_MAGIC_LEN;	}	/* It stops at the first '$', max 8 chars */	for (ep = sp; *ep != '/0' && *ep != '$' && ep < (sp + 8); ep++) {		continue;	}	/* get the length of the true salt */	sl = ep - sp;	/* Create an empty hash object. */	if(!CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &ctx)) {		goto _destroyProv;	}	/* The password first, since that is what is most unknown */	if(!CryptHashData(ctx, (BYTE *)pw, pwl, 0)) {		goto _destroyCtx0;	}	/* Then our magic string */	if(!CryptHashData(ctx, magic_md5, magic_md5_len, 0)) {		goto _destroyCtx0;	}	/* Then the raw salt */	if(!CryptHashData( ctx, (BYTE *)sp, sl, 0)) {		goto _destroyCtx0;	}	/* MD5(pw,salt,pw), valid. */	/* Then just as many characters of the MD5(pw,salt,pw) */	if(!CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &ctx1)) {		goto _destroyCtx0;	}	if(!CryptHashData(ctx1, (BYTE *)pw, pwl, 0)) {		goto _destroyCtx1;	}	if(!CryptHashData(ctx1, (BYTE *)sp, sl, 0)) {		goto _destroyCtx1;	}	if(!CryptHashData(ctx1, (BYTE *)pw, pwl, 0)) {		goto _destroyCtx1;	}	dwHashLen = 16;	CryptGetHashParam(ctx1, HP_HASHVAL, final, &dwHashLen, 0);	/*  MD5(pw,salt,pw). Valid. */	for (pl = pwl; pl > 0; pl -= 16) {		CryptHashData(ctx, final, (DWORD)(pl > 16 ? 16 : pl), 0);	}	/* Don't leave anything around in vm they could use. */	memset(final, 0, sizeof(final));	/* Then something really weird... */	for (i = pwl; i != 0; i >>= 1) {		if ((i & 1) != 0) {			CryptHashData(ctx, (const BYTE *)final, 1, 0);		} else {
开发者ID:NieHao,项目名称:Tomato-RAF,代码行数:89,


示例22: CWE327_Use_Broken_Crypto__w32_DES_14_bad

void CWE327_Use_Broken_Crypto__w32_DES_14_bad(){    if(globalFive==5)    {        {            FILE *pFile;            HCRYPTPROV hCryptProv;            HCRYPTKEY hKey;            HCRYPTHASH hHash;            char password[100];            size_t passwordLen;            char toBeDecrypted[100];            DWORD toBeDecryptedLen = sizeof(toBeDecrypted)-1;            /* Read the password from the console */            printLine("Enter the password: ");            if (fgets(password, 100, stdin) == NULL)            {                printLine("fgets() failed");                /* Restore NUL terminator if fgets fails */                password[0] = '/0';            }            /* The next 3 lines remove the carriage return from the string that is             * inserted by fgets() */            passwordLen = strlen(password);            if (passwordLen > 0)            {                password[passwordLen-1] = '/0';            }            /* Read the data to be decrypted from a file */            pFile = fopen("encrypted.txt", "rb");            if (pFile == NULL)            {                exit(1);            }            if (fread(toBeDecrypted, sizeof(char), 100, pFile) != 100)            {                fclose(pFile);                exit(1);            }            toBeDecrypted[99] = '/0';            /* Try to get a context with and without a new key set */            if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0))            {                if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_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 password */            if(!CryptHashData(hHash, (BYTE *) password, passwordLen, 0))            {                printLine("Error in hashing password");                exit(1);            }            /* Derive a DES key from the Hashed password */            if(!CryptDeriveKey(hCryptProv, CALG_DES, hHash, 0, &hKey))            {                printLine("Error in CryptDeriveKey");                exit(1);            }            /* FLAW: Decrypt using DES */            if(!CryptDecrypt(hKey, 0, 1, 0, (BYTE *)toBeDecrypted, &toBeDecryptedLen))            {                printLine("Error in decryption");                exit(1);            }            /* Ensure the plaintext is NUL-terminated */            toBeDecrypted[toBeDecryptedLen] = '/0';            printLine(toBeDecrypted);            /* Cleanup */            if (hKey)            {                CryptDestroyKey(hKey);            }            if (hHash)            {                CryptDestroyHash(hHash);            }            if (hCryptProv)            {                CryptReleaseContext(hCryptProv, 0);            }            if (pFile)            {                fclose(pFile);            }        }    }}
开发者ID:gpwi970725,项目名称:testJuliet2,代码行数:96,


示例23: 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,


示例24: 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,


示例25: 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,


示例26: CryptAcquireContext

bool vmsSecurity::VerifySign(LPCTSTR ptszFile, LPCTSTR ptszPubKey){	HCRYPTPROV hProv = NULL;	BOOL bOK = CryptAcquireContext (&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);		if (!bOK)		return false;		BYTE abKey [1000];	DWORD dwKeySize;		HANDLE h = CreateFile (ptszPubKey, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);	if (h == INVALID_HANDLE_VALUE)		return false;	ReadFile (h, abKey, sizeof (abKey), &dwKeySize, NULL);	CloseHandle (h);		HCRYPTKEY hKey;	if (FALSE == CryptImportKey (hProv, abKey, dwKeySize, NULL, 0, &hKey))		return false;		LPBYTE pbData;	DWORD dwDataSize;		h = CreateFile (ptszFile, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);	if (h == INVALID_HANDLE_VALUE)		return FALSE;	dwDataSize = GetFileSize (h, NULL);	if (dwDataSize < strlen (FdmCryptSignatureMarker))	{		CloseHandle (h);		return false;	}	pbData = new BYTE [dwDataSize];	DWORD dw;	ReadFile (h, pbData, dwDataSize, &dw, NULL);	CloseHandle (h);		int nSigLen = strlen (FdmCryptSignatureMarker);	LPBYTE pbSig = pbData + dwDataSize - nSigLen;	while (pbSig != pbData && strncmp ((char*)pbSig, FdmCryptSignatureMarker, nSigLen) != 0)		pbSig--;	if (pbData == pbSig)	{		delete [] pbData;		return false;	}		HCRYPTHASH hHash;	if (FALSE == CryptCreateHash (hProv, CALG_MD5, 0, 0, &hHash))		return false;		if (FALSE == CryptHashData (hHash, pbData, pbSig - pbData, 0))		return false;		BOOL bResult = CryptVerifySignature (hHash, pbSig + nSigLen,		pbData + dwDataSize - pbSig - nSigLen, hKey, NULL, 0);			CryptDestroyHash (hHash);		delete [] pbData;		CryptDestroyKey (hKey);		CryptReleaseContext (hProv, 0);		return bResult != FALSE;}
开发者ID:ratever930,项目名称:freedownload,代码行数:67,


示例27: create_RSA_sig

/** * Hashes a block of data and signs it with an RSA private key. * Output buffer must be at least the key size. */int create_RSA_sig(RSA_key_t rsa, int hashtype,                   const unsigned char *mes, unsigned int meslen,                   unsigned char *sig, unsigned int *siglen){    HCRYPTHASH hash;    DWORD _siglen;    int idx, found;    ALG_ID alg;    int hashlen, rval;    unsigned int i;    unsigned char *outsig;    for (idx = 0, found = 0; (idx < MAXLIST) && (!found); idx++) {        if (private_key_list[idx].key == rsa) {            found = 1;        }    }    if (!found) {        log(0, 0, "Couldn't find provider for RSA key");        return 0;    }    idx--;    hashlen = get_hash_len(hashtype);    alg = get_hash(hashtype);    if (!CryptCreateHash(private_key_list[idx].provider, alg, 0, 0, &hash)) {        mserror("CryptCreateHash failed");        return 0;    }    if (!CryptHashData(hash, mes, meslen, 0)) {        mserror("CryptHashData failed");        rval = 0;        goto end;    }    _siglen = RSA_keylen(rsa);    outsig = calloc(_siglen, 1);    if (outsig == NULL) {        syserror(0, 0, "calloc failed!");        exit(1);    }    if (!CryptSignHash(hash, AT_KEYEXCHANGE, NULL, 0, outsig, &_siglen)) {        mserror("CryptSignHash failed");        free(outsig);        rval = 0;        goto end;    }    *siglen = _siglen;    // CryptoAPI returns signatures in little endian, so reverse the bytes    for (i = 0; i < _siglen; i++) {        sig[i] = outsig[_siglen - i - 1];    }    free(outsig);    rval = 1;end:    if (!CryptDestroyHash(hash)) {        mserror("CryptDestroyHash failed");    }    return rval;}
开发者ID:b-cuts,项目名称:uftp,代码行数:67,


示例28: 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,


示例29: CWE319_Cleartext_Tx_Sensitive_Info__w32_wchar_t_connect_socket_65b_goodB2GSink

/* goodB2G uses the BadSource with the GoodSink */void CWE319_Cleartext_Tx_Sensitive_Info__w32_wchar_t_connect_socket_65b_goodB2GSink(wchar_t * password){    {        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,代码行数:80,



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


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