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


C++ CryptHashData函数代码示例

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


在下文中一共展示了CryptHashData函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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,代码来源:sumd5.cpp

示例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,代码来源:encrypt_cryptoapi.c

示例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,代码来源:StandardEncryption.cpp

示例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,代码来源:CWE321_Hard_Coded_Cryptographic_Key__w32_char_06.c

示例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,代码来源:BuscarActualizaciones.cpp

示例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,代码来源:CWE325_Missing_Required_Cryptographic_Step__w32_CryptHashData_17.c

示例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,代码来源:SessionKey.cpp

示例8: xmlSecMSCryptoKWDes3Sha1

/*********************************************************************
 *
 * DES KW implementation
 *
 *********************************************************************/
static int
xmlSecMSCryptoKWDes3Sha1(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,代码来源:kw_des.c

示例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,代码来源:WinCAPICryptoHashHMAC.cpp

示例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,代码来源:CommonUtils.cpp

示例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,代码来源:DESEncoder.cpp

示例12: FormattedException

/*
 * Compute the Base64-encoded HmacSha256 for the given key and content, optionally URL
 * encoding the Base64 result.
 */
CharHolder
HmacSha256::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,代码来源:HmacSha256.cpp

示例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,代码来源:dllmain.cpp

示例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,代码来源:dllmain.cpp

示例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,代码来源:tool_metalink.c


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