Esempio n. 1
0
BOOL kull_m_crypto_pkcs5_pbkdf2_hmac(DWORD calgid, LPCVOID password, DWORD passwordLen, LPCVOID salt, DWORD saltLen, DWORD iterations, BYTE *key, DWORD keyLen, BOOL isDpapiInternal)
{
	BOOL status = FALSE;
	HCRYPTPROV hProv;
	HCRYPTHASH hHash;
	DWORD sizeHmac, count, i, j, r;
	PBYTE asalt, obuf, d1;

	if(CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT))
	{
		if(CryptCreateHash(hProv, calgid, 0, 0, &hHash))
		{
			if(CryptGetHashParam(hHash, HP_HASHVAL, NULL, &sizeHmac, 0))
			{
				if(asalt = (PBYTE) LocalAlloc(LPTR, saltLen + sizeof(DWORD)))
				{
					if(obuf = (PBYTE) LocalAlloc(LPTR, sizeHmac))
					{
						if(d1 = (PBYTE) LocalAlloc(LPTR, sizeHmac))
						{
							status = TRUE;
							RtlCopyMemory(asalt, salt, saltLen);
							for (count = 1; keyLen > 0; count++)
							{
								*(PDWORD) (asalt + saltLen) = _byteswap_ulong(count);
								kull_m_crypto_hmac(calgid, password, passwordLen, asalt, saltLen + 4, d1, sizeHmac);
								RtlCopyMemory(obuf, d1, sizeHmac);
								for (i = 1; i < iterations; i++)
								{
									kull_m_crypto_hmac(calgid, password, passwordLen, d1, sizeHmac, d1, sizeHmac);
									for (j = 0; j < sizeHmac; j++)
										obuf[j] ^= d1[j];
									if(isDpapiInternal) // thank you MS!
										RtlCopyMemory(d1, obuf, sizeHmac);
								}
								r = KIWI_MINIMUM(keyLen, sizeHmac);
								RtlCopyMemory(key, obuf, r);
								key += r;
								keyLen -= r;
							}
							LocalFree(d1);
						}
						LocalFree(obuf);
					}
					LocalFree(asalt);
				}
			}
			CryptDestroyHash(hHash);
		}
		CryptReleaseContext(hProv, 0);
	}
	return status;
}
Esempio n. 2
0
/*
 * Class:     org_company_security_csp_NativeCrypto
 * Method:    digestInit
 * Signature: (Lorg/company/security/csp/CSPDigest;Ljava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_org_company_security_csp_NativeCrypto_digestInit(
		JNIEnv *env, jclass clazz, jobject jMessageDigest, jstring jHashAlgorithm) {

	HCRYPTPROV hCryptProv = (HCRYPTPROV) NULL;
	HCRYPTHASH hCryptHash = (HCRYPTHASH) NULL;
	DWORD dwBlockSize;
	BOOL result = FALSE;

	{
		ALG_ID algId = MapHashAlgorithm(env, jHashAlgorithm);
		DWORD dwProvId;
		jclass clazzCSPDigest;
		jmethodID mCSPPublicKeyInit;

		if(! FindProviderByAlg(env, NULL, algId, &dwProvId, &dwBlockSize)) {
			goto _m_leave;
		}

		if(! CryptAcquireContext(&hCryptProv, NULL, NULL, dwProvId, CRYPT_VERIFYCONTEXT)) {
			ThrowException(env, PROVIDER_EXCEPTION, GetLastError());
			goto _m_leave;
		}

		// выделяем контекст хеш функции
		if(! CryptCreateHash(hCryptProv, algId, 0, 0, &hCryptHash)) {
			ThrowException(env, DIGEST_EXCEPTION, GetLastError());
			goto _m_leave;
		}

		// Get the method ID for the CSPPublicKey constructor
		clazzCSPDigest =
				(*env)->FindClass(env, "org/company/security/csp/CSPDigest");

		mCSPPublicKeyInit =
				(*env)->GetMethodID(env, clazzCSPDigest, "initDigest", "(JJI)V");

		// Create a new CSP public key
		(*env)->CallVoidMethod(env, jMessageDigest, mCSPPublicKeyInit,
				(jlong) hCryptProv, (jlong) hCryptHash, (jint) dwBlockSize);

		result = TRUE;
	}
	_m_leave:
	{
		if(! result) {
			if (hCryptHash)
				CryptDestroyHash((HCRYPTHASH) hCryptHash);

			if(hCryptProv)
				CryptReleaseContext((HCRYPTPROV) hCryptProv, 0);
		}
	}
}
// generates SHA-1 hash of input
BOOL open_hash(void)
{
    BOOL bStatus = FALSE;

    // create hash object
    if (CryptCreateHash(hProv, CALG_SHA, 0, 0, &hHash)) {
        // hash input
        bStatus = CryptHashData(hHash, input, lstrlen(input), 0);
    }

    return bStatus;
}
Esempio n. 4
0
int cryptoapi_hash_vector(ALG_ID alg, size_t hash_len, size_t num_elem,
						  const u8 *addr[], const size_t *len, u8 *mac)
{
	HCRYPTPROV prov;
	HCRYPTHASH hash;
	size_t i;
	DWORD hlen;
	int ret = 0;

	/*
	if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, 0)) {
		cryptoapi_report_error("CryptAcquireContext");
		return -1;
	}
	*/

	BOOL r = CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, 0);
	if (!r) {
		if (GetLastError() == NTE_BAD_KEYSET) {
			r = CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET);
		}
	}

	if (!r) {
		cryptoapi_report_error("CryptAcquireContext");
		return -1;
	}

	if (!CryptCreateHash(prov, alg, 0, 0, &hash)) {
		cryptoapi_report_error("CryptCreateHash");
		CryptReleaseContext(prov, 0);
		return -1;
	}

	for (i = 0; i < num_elem; i++) {
		if (!CryptHashData(hash, (BYTE *) addr[i], len[i], 0)) {
			cryptoapi_report_error("CryptHashData");
			CryptDestroyHash(hash);
			CryptReleaseContext(prov, 0);
		}
	}

	hlen = hash_len;
	if (!CryptGetHashParam(hash, HP_HASHVAL, mac, &hlen, 0)) {
		cryptoapi_report_error("CryptGetHashParam");
		ret = -1;
	}

	CryptDestroyHash(hash);
	CryptReleaseContext(prov, 0);

	return ret;
}
Esempio n. 5
0
void lw_sha1 (char * output, const char * input, size_t length)
{
   HCRYPTPROV hash_prov;
   DWORD hash_length = 20;

   crypt_init ();

   CryptCreateHash (crypt_prov, CALG_SHA1, 0, 0, &hash_prov);
   CryptHashData (hash_prov, (BYTE *) input, (DWORD) length, 0);
   CryptGetHashParam (hash_prov, HP_HASHVAL, (BYTE *) output, &hash_length, 0);
   CryptDestroyHash (hash_prov);
}
Esempio n. 6
0
struct mesa_sha1 *
_mesa_sha1_init(void)
{
    HCRYPTHASH *ctx = malloc(sizeof(*ctx));

    if (!ctx)
        return NULL;

    CryptAcquireContext(&hProv, NULL, MS_DEF_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
    CryptCreateHash(hProv, CALG_SHA1, 0, 0, ctx);
    return (struct mesa_sha1 *) ctx;
}
Esempio n. 7
0
bool getUUID(std::string& uuid) {
	// Get the buffer length required for IP_ADAPTER_INFO.
	ULONG BufferLength = 0;
	BYTE* pBuffer = 0;
	if (ERROR_BUFFER_OVERFLOW == GetAdaptersInfo( 0, &BufferLength )) {
		// Now the BufferLength contain the required buffer length.
		// Allocate necessary buffer.
		pBuffer = new BYTE[ BufferLength ];
	} else {
		// Error occurred. handle it accordingly.
		return false;
	}

	// Get the Adapter Information.
	PIP_ADAPTER_INFO pAdapterInfo = reinterpret_cast<PIP_ADAPTER_INFO>(pBuffer);
	GetAdaptersInfo( pAdapterInfo, &BufferLength );
/*
	// Iterate the network adapters and print their MAC address.
	while( pAdapterInfo ) {
		// Assuming pAdapterInfo->AddressLength is 6.
		printf ("%02x:%02x:%02x:%02x:%02x:%02x \n",
			pAdapterInfo->Address[0],pAdapterInfo->Address[1],pAdapterInfo->Address[2],
			pAdapterInfo->Address[3],pAdapterInfo->Address[4],pAdapterInfo->Address[5]);
		// Get next adapter info.
		pAdapterInfo = pAdapterInfo->Next;
	}
*/
	// start encrypt
	HCRYPTPROV hProv = 0;
    HCRYPTHASH hHash = 0;
	CryptAcquireContext(&hProv, NULL,  NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
	CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash);
	CryptHashData(hHash, pAdapterInfo->Address, 6, 0);

	const int MD5LEN = 16;
	const CHAR rgbDigits[] = "0123456789abcdef";
	DWORD cbHash = MD5LEN;
	BYTE rgbHash[MD5LEN];
	uuid.resize(MD5LEN*2);
    if (CryptGetHashParam(hHash, HP_HASHVAL, rgbHash, &cbHash, 0)) {
        for (DWORD i = 0; i < cbHash; i++) {
			uuid[2*i] = rgbDigits[rgbHash[i] >> 4];
			uuid[2*i+1] = rgbDigits[rgbHash[i] & 0xf];
        }
    }
    CryptDestroyHash(hHash);
    CryptReleaseContext(hProv, 0);

	// deallocate the buffer.
	delete[] pBuffer;
	return true;
}
Esempio n. 8
0
std::string CStringUtils::Decrypt(const std::string& s, const std::string& password)
{
    std::string decryptstring;
    HCRYPTPROV hProv = NULL;
    // Get handle to user default provider.
    if (CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
    {
        HCRYPTHASH hHash = NULL;
        // Create hash object.
        if (CryptCreateHash(hProv, CALG_SHA_512, 0, 0, &hHash))
        {
            // Hash password string.
            DWORD dwLength = DWORD(sizeof(WCHAR)*password.size());
            if (CryptHashData(hHash, (BYTE *)password.c_str(), dwLength, 0))
            {
                HCRYPTKEY hKey = NULL;
                // Create block cipher session key based on hash of the password.
                if (CryptDeriveKey(hProv, CALG_AES_256, hHash, CRYPT_EXPORTABLE, &hKey))
                {
                    dwLength = DWORD(s.size() + 1024); // 1024 bytes should be enough for padding
                    std::unique_ptr<BYTE[]> buffer(new BYTE[dwLength]);

                    std::unique_ptr<BYTE[]> strIn(new BYTE[s.size() + 1]);
                    if (buffer && strIn)
                    {
                        if (CStringUtils::FromHexString(s, strIn.get()))
                        {
                            // copy encrypted password to temporary buffer
                            memcpy(buffer.get(), strIn.get(), s.size());
                            dwLength = DWORD(s.size() / 2);
                            CryptDecrypt(hKey, 0, true, 0, (BYTE *)buffer.get(), &dwLength);
                            decryptstring = std::string((char*)buffer.get(), dwLength);
                            if (!decryptstring.empty() && (decryptstring[0] == '*'))
                            {
                                decryptstring = decryptstring.substr(1);
                            }
                            else
                                decryptstring.clear();
                        }
                    }
                    CryptDestroyKey(hKey);  // Release provider handle.
                }
            }
            CryptDestroyHash(hHash); // Destroy session key.
        }
        CryptReleaseContext(hProv, 0);
    }
    else
        DebugBreak();

    return decryptstring;
}
Esempio n. 9
0
/**
  * Begins a signature verification hash context
  *
  * @param provider The crypt provider to use
  * @param hash     Out parameter for a handle to the hash context
  * @return CryptoX_Success on success, CryptoX_Error on error.
*/
CryptoX_Result
CryptoAPI_VerifyBegin(HCRYPTPROV provider, HCRYPTHASH* hash)
{
  BOOL result;
  if (!provider || !hash) {
    return CryptoX_Error;
  }

  *hash = (HCRYPTHASH)NULL;
  result = CryptCreateHash(provider, CALG_SHA1,
                           0, 0, hash);
  return result ? CryptoX_Success : CryptoX_Error;
}
Esempio n. 10
0
		HCRYPTHASH create()
		{
			HCRYPTHASH ret;
			if (CryptCreateHash(get_provider(), AlgId, 0, 0, &ret) == false)
			{
#ifndef BOOST_NO_EXCEPTIONS
				throw system_error(error_code(GetLastError(), system_category()));
#else
				std::terminate();
#endif
			}
			return ret;
		}
Esempio n. 11
0
GIT_INLINE(int) hash_cryptoapi_init(git_hash_ctx *ctx)
{
    if (ctx->ctx.cryptoapi.valid)
        CryptDestroyHash(ctx->ctx.cryptoapi.hash_handle);

    if (!CryptCreateHash(ctx->prov->prov.cryptoapi.handle, CALG_SHA1, 0, 0, &ctx->ctx.cryptoapi.hash_handle)) {
        ctx->ctx.cryptoapi.valid = 0;
        return -1;
    }

    ctx->ctx.cryptoapi.valid = 1;
    return 0;
}
Esempio n. 12
0
/**
 * Calculates an MD5 hash for the given input binary data
 *
 * @param  data     Any sequence of bytes
 * @param  dataSize The number of bytes inside @data
 * @param  hash     Output buffer to store hash, must be freed by the caller
 * @param  hashSize The number of bytes in the output buffer
 * @return TRUE on success
*/
static BOOL
CalculateMD5(const char *data, DWORD dataSize, 
             BYTE **hash, DWORD &hashSize)
{
  HCRYPTPROV hProv = 0;
  HCRYPTHASH hHash = 0;

  if (!CryptAcquireContext(&hProv, nullptr, nullptr, PROV_RSA_FULL,
                           CRYPT_VERIFYCONTEXT)) {
    if (NTE_BAD_KEYSET != GetLastError()) {
      return FALSE;
    }
 
    // Maybe it doesn't exist, try to create it.
    if (!CryptAcquireContext(&hProv, nullptr, nullptr, PROV_RSA_FULL, 
                             CRYPT_VERIFYCONTEXT | CRYPT_NEWKEYSET)) {
      return FALSE;
    }
  }

  if (!CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash)) {
    return FALSE;
  }

  if (!CryptHashData(hHash, reinterpret_cast<const BYTE*>(data), 
                    dataSize, 0)) {
    return FALSE;
  }

  DWORD dwCount = sizeof(DWORD);
  if (!CryptGetHashParam(hHash, HP_HASHSIZE, (BYTE *)&hashSize, 
                        &dwCount, 0)) {
    return FALSE;
  }
  
  *hash = new BYTE[hashSize];
  ZeroMemory(*hash, hashSize);
  if (!CryptGetHashParam(hHash, HP_HASHVAL, *hash, &hashSize, 0)) {
    return FALSE;
  }

  if (hHash) {
    CryptDestroyHash(hHash);
  }

  if (hProv) {
    CryptReleaseContext(hProv,0);
  }

  return TRUE;
}
Esempio n. 13
0
CString &Cmd5Capi::Digest(CString & csBuffer)
{
    HCRYPTPROV hCryptProv; 
    HCRYPTHASH hHash; 
    BYTE bHash[0x7f]; 
    DWORD dwHashLen= 16; // The MD5 algorithm always returns 16 bytes. 
    DWORD cbContent= csBuffer.GetLength(); 
    BYTE* pbContent= (BYTE*)csBuffer.GetBuffer(cbContent); 


    if(CryptAcquireContext(&hCryptProv, 
		NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_MACHINE_KEYSET)) 
	{

		if(CryptCreateHash(hCryptProv, 
			CALG_MD5,	// algorithm identifier definitions see: wincrypt.h
			0, 0, &hHash)) 
		{
			if(CryptHashData(hHash, pbContent, cbContent, 0))
			{

				if(CryptGetHashParam(hHash, HP_HASHVAL, bHash, &dwHashLen, 0)) 
				{
					// Make a string version of the numeric digest value
					csDigest.Empty();
					CString tmp;
					  for (int i = 0; i<16; i++)
					  {
						tmp.Format("%02x", bHash[i]);
						csDigest+=tmp;
					  }

				}
				else csDigest=_T("Error getting hash param"); 

			}
			else csDigest=_T("Error hashing data"); 
		}
		else csDigest=_T("Error creating hash"); 

    }
    else csDigest=_T("Error acquiring context"); 


    CryptDestroyHash(hHash); 
    CryptReleaseContext(hCryptProv, 0); 
	csBuffer.ReleaseBuffer();
    return csDigest; 


}
bool StandardEncryption::GetMD5Hash (char *szPassword, char *szOutbuf)
{
	HCRYPTPROV hCryptProv; 
    HCRYPTHASH hHash; 
    BYTE bHash[0x7f]; 
    DWORD dwHashLen= 16; // The MD5 algorithm always returns 16 bytes. 
    DWORD cbContent= strlen (szPassword);
    BYTE* pbContent= (BYTE*) szPassword;

	char szFinal[SIZE_STRING];
	ZeroMemory (szFinal, SIZE_STRING);

	char szCurchar[SIZE_NAME];
	
    if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_MACHINE_KEYSET)) {
		if(CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hHash)) {
			if(CryptHashData(hHash, pbContent, cbContent, 0)) {
				if(CryptGetHashParam(hHash, HP_HASHVAL, bHash, &dwHashLen, 0)) {
					
					for (int i=0;i<16;i++) {
						ZeroMemory (szCurchar, SIZE_NAME);
						sprintf_s (szCurchar, SIZE_NAME, "%02x", bHash[i]);

						strcat_s (szFinal, SIZE_STRING, szCurchar);
					}

				} else {
					OutputText ("GetMD5Hash: Error getting hash param!");
					return false;
				}
			} else {
				OutputText ("GetMD5Hash: Error Hashing data!");
				return false;
			}
		} else {
			OutputText ("GetMD5Hash: Error Creating Hash!");
			return false;
		}
	} else {
		OutputText ("GetMD5Hash: Error Aquiring Context!");
		return false;
	}

	ZeroMemory (szOutbuf, SIZE_STRING);
	strcpy_s (szOutbuf, SIZE_STRING, szFinal);

	CryptDestroyHash(hHash); 
    CryptReleaseContext(hCryptProv, 0); 	
    return true; 
}
Esempio n. 15
0
CryptoHash::CryptoHash(HCRYPTPROV cryptProv, ALG_ID algId, const ByteVector& data)
         :handle(NULL)
{
    TOE(CryptCreateHash(cryptProv, algId, 0, 0, &handle), "CryptCreateHash");
    try
    {
        update(data);
    }
    catch (exception&)
    {
        CryptDestroyHash(handle);
        throw;
    }
}
Esempio n. 16
0
HRESULT CAssemblyStream::Init (LPCOLESTR pszPath, DWORD dwFormat)
{
    HRESULT                            hr = S_OK;
    DWORD                              cwPath;
    BOOL                               bRet;

    _ASSERTE(pszPath);

    _dwFormat = dwFormat;
    cwPath = lstrlenW(pszPath) + 1;

    _ASSERTE(cwPath < MAX_PATH);
    memcpy(_szPath, pszPath, sizeof(TCHAR) * cwPath);

    _hf = WszCreateFile(pszPath, GENERIC_WRITE, 0 /* no sharing */,
                     NULL, CREATE_NEW, FILE_FLAG_SEQUENTIAL_SCAN, NULL);
    if (_hf == INVALID_HANDLE_VALUE) {
        hr = HRESULT_FROM_WIN32(GetLastError());
        ReleaseParent(hr);
        goto Exit;
    }

    if (!g_hProv) {
        HCRYPTPROV hProv;
  
        bRet = CryptAcquireContextA(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
        if (!bRet) {
            hr = HRESULT_FROM_WIN32(GetLastError());
            ReleaseParent(hr);
            goto Exit;

        }

        if (InterlockedCompareExchangePointer((void **)&g_hProv, (void *)hProv, 0)) {
            // Lost the race. Release our provider.
            CryptReleaseContext(hProv, 0);
        }
    }

    bRet = CryptCreateHash(g_hProv, CALG_SHA1, 0, 0, &_hHash);
    if (!bRet) {
        hr = HRESULT_FROM_WIN32(GetLastError());
        ReleaseParent(hr);
        goto Exit;
    }

Exit:
    return hr;
}
bool testHashData(bool bVerbose){

	HCRYPTHASH hHash;
	BYTE bDataToHash[32];
	BYTE bHashValue[32];
	BYTE bBenchmarkHashValue[32];
	//strtobyte( "73657479622032333D6874676E656C202C6567617373656D2073692073696854", bDataToHash );
	memcpy( bDataToHash, "This is message, length=32 bytes", 32 );
	strtobyte( "FAFF37A615A816691CFF3EF8B68CA247E09525F39F8119832EB81975D366C4B1", bBenchmarkHashValue );

	if (!(CryptCreateHash(hProv,
					  CALG_GOST_HASH,
					  0,
					  0,
					  &hHash)))
	{   
		if ( bVerbose )
			printf("CryptCreateHash Failed\n");
		return false;
	}

	DWORD dwHashLen = 32;
	if ( !CryptHashData( hHash, bDataToHash, 32, 0 ) ){
		if ( bVerbose )
			printf("CryptHashData Failed\n");
		return false;
	}

	if ( !CryptGetHashParam( hHash, HP_HASHVAL, bHashValue, &dwHashLen, 0 ) ){
		if ( bVerbose )
			printf("CryptGetHashParam Failed\n");
		return false;
	}

	if ( memcmp( bHashValue, bBenchmarkHashValue, dwHashLen ) != 0 ){
		if ( bVerbose )
			std::cout << bHashValue << std::endl;
		return false;
	}

	if ( !CryptDestroyHash( hHash ) ){
		if ( bVerbose )
			std::cout << "CryptDestroyHash failed" << std::endl;
		return false;
	}

	return true;

}
bool testHashDataLong(bool bVerbose){

	HCRYPTHASH hHash;
	BYTE bDataToHash[50];
	BYTE bHashValue[32];
	BYTE bBenchmarkHashValue[32];
	//strtobyte( "73657479622032333D6874676E656C202C6567617373656D2073692073696854", bDataToHash );
	memcpy( bDataToHash, "Suppose the original message has length = 50 bytes", 50 );
	strtobyte( "0852F5623B89DD57AEB4781FE54DF14EEAFBC1350613763A0D770AA657BA1A47", bBenchmarkHashValue );

	if (!(CryptCreateHash(hProv,
					  CALG_GOST_HASH,
					  0,
					  0,
					  &hHash)))
	{   
		if ( bVerbose )
			printf("CryptCreateHash Failed\n");
		return false;
	}

	DWORD dwHashLen = 32;
	if ( !CryptHashData( hHash, bDataToHash, 50, 0 ) ){
		if ( bVerbose )
			printf("CryptHashData Failed\n");
		return false;
	}

	if ( !CryptGetHashParam( hHash, HP_HASHVAL, bHashValue, &dwHashLen, 0 ) ){
		if ( bVerbose )
			printf("CryptGetHashParam Failed\n");
		return false;
	}

	if ( memcmp( bHashValue, bBenchmarkHashValue, dwHashLen ) != 0 ){
		if ( bVerbose )
			std::cout << bHashValue << std::endl;
		return false;
	}

	if ( !CryptDestroyHash( hHash ) ){
		if ( bVerbose )
			std::cout << "CryptDestroyHash failed" << std::endl;
		return false;
	}

	return true;

}
Esempio n. 19
0
//move to zacrypto.c
//@@implemented in harusame
VOID SfcZAVerifyFile(
	HCRYPTPROV  hProv,
	HCRYPTKEY hKey,
	MD5_CTX *ctx,		
	PBYTE Image,		
	DWORD ImageSize		
	)
{
	HCRYPTHASH          lh_hash = 0; 
	ULONG               CRC, SignSize = 0; 
	BYTE                e_sign[128];
	PBYTE               p_resource_sign; 
	PIMAGE_NT_HEADERS32 phdr; 

	phdr = (PIMAGE_NT_HEADERS32)RtlImageNtHeader(Image);
	while (phdr != NULL) {

		p_resource_sign = SfuQueryResourceData(3, Image, &SignSize);
		if (p_resource_sign == NULL)
			break;

		if (SignSize != 128)
			break;

		if (!CryptCreateHash(hProv, CALG_MD5, 0, 0, &lh_hash))
			break;

		CRC = phdr->OptionalHeader.CheckSum;

		memcpy(e_sign, p_resource_sign, sizeof(e_sign));
		memset(p_resource_sign, 0, sizeof(e_sign));

		phdr->OptionalHeader.CheckSum = 0;

		MD5Update(ctx, Image, ImageSize);

		phdr->OptionalHeader.CheckSum = CRC;

		memcpy(p_resource_sign, e_sign, sizeof(e_sign));
		MD5Final(ctx);
		if (!CryptSetHashParam(lh_hash, HP_HASHVAL, (const BYTE *)&ctx->digest, 0)) {
			CryptDestroyHash(lh_hash);
			break;
		}

		CryptVerifySignatureW(lh_hash, (const BYTE *)&e_sign, sizeof(e_sign), hKey, 0, 0);
		break;
	}
}
Esempio n. 20
0
int KSI_DataHasher_reset(KSI_DataHasher *hasher) {
	int res = KSI_UNKNOWN_ERROR;
	ALG_ID msHashAlg = 0;
	CRYPTO_HASH_CTX * pCryptoCTX = NULL;	//Crypto helper struct
	HCRYPTPROV pCSP = 0;					//Crypto service provider
	HCRYPTHASH pTmp_hash = 0;			//Hash object

	if (hasher == NULL){
		res = KSI_INVALID_ARGUMENT;
		goto cleanup;
	}
	KSI_ERR_clearErrors(hasher->ctx);

	/*Shortcuts for pointers*/
	pCryptoCTX = (CRYPTO_HASH_CTX*)hasher->hashContext;
	pCSP = pCryptoCTX->pt_CSP;

	/*Convert hash algorithm into crypto api style*/
	msHashAlg = hashAlgorithmToALG_ID(hasher->algorithm);
	if (msHashAlg == 0) {
		KSI_pushError(hasher->ctx, res = KSI_UNAVAILABLE_HASH_ALGORITHM, NULL);
		goto cleanup;
	}

	/*If hasher object already exists, destroy one*/
	if (pTmp_hash != 0){
		CryptDestroyHash(pTmp_hash);
		}

	/*Create new hasher object*/
	if (!CryptCreateHash(pCSP, msHashAlg, 0,0,&pTmp_hash)) {
		DWORD error = GetLastError();
		KSI_LOG_debug(hasher->ctx, "Cryptoapi: Create hash error %i\n", error);
		KSI_pushError(hasher->ctx, res = KSI_OUT_OF_MEMORY, NULL);
		goto cleanup;
		}

	pCryptoCTX->pt_hHash = pTmp_hash;

	pTmp_hash = 0;

	res = KSI_OK;

cleanup:

	if (pTmp_hash) CryptDestroyHash(pTmp_hash);

	return res;
}
Esempio n. 21
0
/**
 * Hashes a block of data and verifies it against an RSA signature.
 */
int verify_RSA_sig(RSA_key_t rsa, int hashtype,
                   const unsigned char *mes, unsigned int meslen,
                   unsigned char *sig, unsigned int siglen)
{
    HCRYPTHASH hash;
    ALG_ID alg;
    unsigned hashlen, i;
    int rval;
    unsigned char *insig;

    hashlen = get_hash_len(hashtype);
    alg = get_hash(hashtype);

    if (!CryptCreateHash(base_prov, alg, 0, 0, &hash)) {
        mserror("CryptCreateHash failed");
        return 0;
    }
    if (!CryptHashData(hash, mes, meslen, 0)) {
        mserror("CryptHashData failed");
        rval = 0;
        goto end;
    }
    insig = calloc(siglen, 1);
    if (insig == NULL) {
        syserror(0, 0, "calloc failed!");
        exit(1);
    }
    // CryptoAPI expects signatures in little endian, so reverse the bytes
    for (i = 0; i < siglen; i++) {
        insig[i] = sig[siglen - i - 1];
    }
    if (!CryptVerifySignature(hash, insig, siglen, rsa, NULL, 0)) {
        mserror("CryptVerifySignature failed");
        free(insig);
        rval = 0;
        goto end;
    }
    free(insig);

    rval = 1;

end:
    if (!CryptDestroyHash(hash)) {
        mserror("CryptDestroyHash failed");
    }
    return rval;
}
Esempio n. 22
0
//-----------------------------------------------------------------------------
// swCryptDeriveKey()
//-----------------------------------------------------------------------------
// Calcul de la clé de chiffrement des mots de passe par dérivation du mot de 
// passe maitre
//-----------------------------------------------------------------------------
// [in] cszMasterPwd = mot de passe maitre
// [out] hKey = handle de clé
// [out] pAESKeyData = bloc de données pour ceux qui voudraient reconstruire la clé
//-----------------------------------------------------------------------------
// Retour : 0 si OK
//-----------------------------------------------------------------------------
int swCryptDeriveKey(const char *pszMasterPwd,HCRYPTKEY *phKey,BYTE *pAESKeyData,BOOL bForceOldDerivationFunction)
{
	TRACE((TRACE_ENTER,_F_,""));

	BOOL brc;
	int rc=-1;
	HCRYPTHASH hHash=NULL;
	
	// si la clé a déjà été créée, on la libère
	if (*phKey!=NULL) { CryptDestroyKey(*phKey); *phKey=NULL; }

	// création d'un hash
	brc=CryptCreateHash(ghProv,CALG_SHA1,0,0,&hHash);           
	if (!brc) {	TRACE((TRACE_ERROR,_F_,"CryptCreateHash()")); goto end; }
	if (bForceOldDerivationFunction)
	{
		// hash du mot de passe
		brc=CryptHashData(hHash,(unsigned char*)pszMasterPwd,strlen(pszMasterPwd),0); 
		if (!brc) {	TRACE((TRACE_ERROR,_F_,"CryptHashData()")); goto end; }
		// dérivation
		brc=CryptDeriveKey(ghProv,CALG_AES_256,hHash,0,phKey); 
		TRACE((TRACE_INFO,_F_,"CryptDeriveKey(CALG_AES_256)"));
	}
	else if (atoi(gszCfgVersion)<93)
	{
		// hash du mot de passe
		brc=CryptHashData(hHash,(unsigned char*)pszMasterPwd,strlen(pszMasterPwd),0); 
		if (!brc) {	TRACE((TRACE_ERROR,_F_,"CryptHashData()")); goto end; }
		// dérivation
		brc=CryptDeriveKey(ghProv,CALG_3DES,hHash,0,phKey); 
		TRACE((TRACE_INFO,_F_,"CryptDeriveKey(CALG_3DES)"));
	}
	else // nouveau mécanisme +secure en 0.93 (PBKDF2) ISSUE#56
	{
		// Obtient 256 bits (32 octets) auprès de PBKDF2 pour générer une clé AES-256
		if (!swIsPBKDF2KeySaltReady()) { TRACE((TRACE_ERROR,_F_,"swIsPBKDF2SaltReady()=FALSE")); goto end; }
		if (swPBKDF2(pAESKeyData,AES256_KEY_LEN,pszMasterPwd,gSalts.bufPBKDF2KeySalt,PBKDF2_SALT_LEN,10000)!=0) goto end;
		if (swCreateAESKeyFromKeyData(pAESKeyData,phKey)!=0) goto end;
	}
	if (!brc) { TRACE((TRACE_ERROR,_F_,"CryptDeriveKey()=0x%08lx",GetLastError())); goto end; }
	rc=0;
end:
	if (hHash!=NULL) CryptDestroyHash(hHash);
	TRACE((TRACE_LEAVE,_F_,"rc=%d",rc));
	return rc;
}
Esempio n. 23
0
HCRYPTKEY generateKey(HCRYPTPROV provider, ALG_ID algid, LPTSTR password) {
  BOOL       res;
  DWORD      data;
  HCRYPTKEY  key;
  HCRYPTHASH hash;

  if (!CryptCreateHash(provider, CALG_SHA, 0, 0, &hash))
    return 0;
  data = strlen(password);
  if (!CryptHashData(hash, (BYTE *)password, data, 0)) {
    CryptDestroyHash(hash);
    return 0;
  }
  res = CryptDeriveKey(provider, algid, hash, CRYPT_EXPORTABLE, &key);
  CryptDestroyHash(hash);
  return (res ? key : 0);
}
Esempio n. 24
0
BOOL Create_AES256_KeyBLOB(
  HCRYPTPROV    prov,               // CSP
  unsigned char *pbPassword,        // input (Password for Key and IV)
  DWORD         cbPassword,         // input (length)
  unsigned char *pbSalt,            // input (Salt for Key and IV)
  DWORD         cbSalt,             // input (length 8 or 16)
  AES_256_KEY_BLOB  *blob,          // output
  unsigned char pbIV[16]            // output (length fixed 16)
)
{
  BOOL bStatus = FALSE;
  DWORD dwError = 0;
  EVERIFY(prov && pbPassword && pbSalt && blob && pbIV);
  const int N = 3;
  BYTE hashdata[N][HASH_MD5_LEN];
  for(int i = 0; i < N; i++){
    HCRYPTHASH hash = NULL;
    EVERIFY(CryptCreateHash(prov, CALG_MD5, 0, 0, &hash));
    BYTE hashwork[HASH_MD5_LEN * 64];
    EVERIFY(HASH_MD5_LEN + cbPassword + cbSalt <= sizeof(hashwork));
    DWORD hashlen; // must get with HP_HASHVAL (not use HP_HASHSIZE)
    if(!i) hashlen = 0;
    else CopyMemory(hashwork, hashdata[i - 1], hashlen = HASH_MD5_LEN);
    CopyMemory(hashwork + hashlen, pbPassword, cbPassword);
    CopyMemory(hashwork + hashlen + cbPassword, pbSalt, cbSalt);
    EVERIFY(CryptHashData(hash, hashwork, hashlen + cbPassword + cbSalt, 0));
    EVERIFY(CryptGetHashParam(hash, HP_HASHVAL, NULL, &hashlen, 0));
    EVERIFY(hashlen == HASH_MD5_LEN);
    EVERIFY(CryptGetHashParam(hash, HP_HASHVAL, hashdata[i], &hashlen, 0));
    if(hash) EVERIFY(CryptDestroyHash(hash));
  }
  blob->hdr.bType = PLAINTEXTKEYBLOB;
  blob->hdr.bVersion = CUR_BLOB_VERSION;
  blob->hdr.reserved = 0;
  blob->hdr.aiKeyAlg = CALG_AES_256;
  blob->cbKeySize = 32; // sizeof(blob->pbDerivedKey) is the size of pointer
  CopyMemory(blob->pbDerivedKey, hashdata[0], HASH_MD5_LEN);
  CopyMemory(blob->pbDerivedKey + HASH_MD5_LEN, hashdata[1], HASH_MD5_LEN);
  CopyMemory(pbIV, hashdata[2], HASH_MD5_LEN);
  bStatus = TRUE;

done:
  return bStatus;
}
Esempio n. 25
0
std::string CStringUtils::Encrypt(const std::string& s, const std::string& password)
{
    std::string encryptedstring;
    HCRYPTPROV hProv = NULL;
    // Get handle to user default provider.
    if (CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
    {
        HCRYPTHASH hHash = NULL;
        // Create hash object.
        if (CryptCreateHash(hProv, CALG_SHA_512, 0, 0, &hHash))
        {
            // Hash password string.
            DWORD dwLength = DWORD(sizeof(WCHAR)*password.size());
            if (CryptHashData(hHash, (BYTE *)password.c_str(), dwLength, 0))
            {
                // Create block cipher session key based on hash of the password.
                HCRYPTKEY hKey = NULL;
                if (CryptDeriveKey(hProv, CALG_AES_256, hHash, CRYPT_EXPORTABLE, &hKey))
                {
                    // Determine number of bytes to encrypt at a time.
                    std::string starname = "*";
                    starname += s;

                    dwLength = (DWORD)starname.size();
                    std::unique_ptr<BYTE[]> buffer(new BYTE[dwLength + 1024]);
                    memcpy(buffer.get(), starname.c_str(), dwLength);
                    // Encrypt data
                    if (CryptEncrypt(hKey, 0, true, 0, buffer.get(), &dwLength, dwLength + 1024))
                    {
                        encryptedstring = CStringUtils::ToHexString(buffer.get(), dwLength);
                    }
                    CryptDestroyKey(hKey);  // Release provider handle.
                }
            }
            CryptDestroyHash(hHash);
        }
        CryptReleaseContext(hProv, 0);
    }
    else
        DebugBreak();
    return encryptedstring;

}
Esempio n. 26
0
HCRYPTKEY GenKey(HCRYPTPROV hCrProv, QString keyText, QByteArray* key, DWORD& keyBlobLen, bool flag)
{
    HCRYPTKEY hKey = 0;
    HCRYPTHASH hHash = 0;
    if (flag)
    {
        CryptGenKey(hCrProv, CALG_AES_256, CRYPT_EXPORTABLE, &hKey);
    }
    else
    {
        CryptCreateHash(hCrProv, CALG_MD5, 0, 0, &hHash);
        CryptHashData(hHash, (BYTE *)keyText.toUtf8().constData(), keyText.length(), 0);
        CryptDeriveKey(hCrProv, CALG_AES_256, hHash, 0, &hKey);
    }
    CryptExportKey(hKey, 0, PLAINTEXTKEYBLOB, 0, NULL, &keyBlobLen);
    key->resize(keyBlobLen);
    CryptExportKey(hKey, 0, PLAINTEXTKEYBLOB, 0, (BYTE*)key->data(), &keyBlobLen);
    return hKey;
}
Esempio n. 27
0
bool CCommonUtils::CalcHash(ALG_ID hashType, const BYTE* lpData, DWORD dwLen, BYTE* lpHash, DWORD dwHashSize)
{
    HCRYPTPROV hProv = NULL;
    HCRYPTHASH hHash = NULL;
    bool bRet = false;

    if(!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, 0)) 
    {
        goto endFunction;
    }

    if(!CryptCreateHash(hProv, hashType, 0, 0, &hHash)) 
    {
        goto endFunction;
    }

    if(!CryptHashData(hHash, lpData, dwLen, 0)) 
    {
        goto endFunction;
    }

    if(!CryptGetHashParam(hHash, HP_HASHVAL, lpHash, &dwHashSize, 0))
    {
        goto endFunction;
    }

    bRet = true;

endFunction:

    if(hHash) 
    {
        CryptDestroyHash(hHash);
    }

    if(hProv) 
    {
        CryptReleaseContext(hProv, 0);
    }

    return bRet;
}
Esempio n. 28
0
File: Updater.cpp Progetto: desg/OBS
BOOL CalculateFileHash (TCHAR *path, BYTE *hash)
{
    BYTE buff[65536];
    HCRYPTHASH hHash;

    if (!CryptCreateHash(hProvider, CALG_SHA1, 0, 0, &hHash))
        return FALSE;

    XFile file;

    if (file.Open(path, XFILE_READ, OPEN_EXISTING))
    {
        for (;;)
        {
            DWORD read = file.Read(buff, sizeof(buff));

            if (!read)
                break;

            if (!CryptHashData(hHash, buff, read, 0))
            {
                CryptDestroyHash(hHash);
                file.Close();
                return FALSE;
            }
        }
    }
    else
    {
        CryptDestroyHash(hHash);
        return FALSE;
    }

    file.Close();

    DWORD hashLength = 20;
    if (!CryptGetHashParam(hHash, HP_HASHVAL, hash, &hashLength, 0))
        return FALSE;

    CryptDestroyHash(hHash);
    return TRUE;
}
Esempio n. 29
0
CString MD5(CString &in)
{
	CString ret;
    HCRYPTPROV hProv = 0;
    HCRYPTHASH hHash = 0;
	BYTE *rgbFile = (BYTE * ) (char *) in.data();
	DWORD cbRead = in.len();
    BYTE rgbHash[32];
    DWORD cbHash = 0;
    CHAR rgbDigits[] = "0123456789abcdef";
	if (!CryptAcquireContext(&hProv,
        NULL,
        NULL,
        PROV_RSA_FULL,
        CRYPT_VERIFYCONTEXT))
    {
		return "";
	}
	if (!CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash))
    {
        CryptReleaseContext(hProv, 0);
		return "";
    }
	if (!CryptHashData(hHash, rgbFile, cbRead, 0))
	{
		CryptReleaseContext(hProv, 0);
		CryptDestroyHash(hHash);
		return "";
	}
	cbHash = 32;
    if (CryptGetHashParam(hHash, HP_HASHVAL, rgbHash, &cbHash, 0))
	{
		for (DWORD i = 0; i < cbHash; i++)
        {
            ret += rgbDigits[rgbHash[i] >> 4];
			ret +=  rgbDigits[rgbHash[i] & 0xf];
        }
	}
	CryptDestroyHash(hHash);
    CryptReleaseContext(hProv, 0);
	return ret;
}
Esempio n. 30
0
static BOOL compare_sha1(void *data, unsigned int pitch, unsigned int bpp,
        unsigned int w, unsigned int h, const char *ref_sha1)
{
    static const char hex_chars[] = "0123456789abcdef";
    HCRYPTPROV provider;
    BYTE hash_data[20];
    HCRYPTHASH hash;
    unsigned int i;
    char sha1[41];
    BOOL ret;

    ret = CryptAcquireContextW(&provider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
    ok(ret, "Failed to acquire crypt context.\n");
    ret = CryptCreateHash(provider, CALG_SHA1, 0, 0, &hash);
    ok(ret, "Failed to create hash.\n");

    for (i = 0; i < h; ++i)
    {
        if (!(ret = CryptHashData(hash, (BYTE *)data + pitch * i, w * bpp, 0)))
            break;
    }
    ok(ret, "Failed to hash data.\n");

    i = sizeof(hash_data);
    ret = CryptGetHashParam(hash, HP_HASHVAL, hash_data, &i, 0);
    ok(ret, "Failed to get hash value.\n");
    ok(i == sizeof(hash_data), "Got unexpected hash size %u.\n", i);

    ret = CryptDestroyHash(hash);
    ok(ret, "Failed to destroy hash.\n");
    ret = CryptReleaseContext(provider, 0);
    ok(ret, "Failed to release crypt context.\n");

    for (i = 0; i < 20; ++i)
    {
        sha1[i * 2] = hex_chars[hash_data[i] >> 4];
        sha1[i * 2 + 1] = hex_chars[hash_data[i] & 0xf];
    }
    sha1[40] = 0;

    return !strcmp(ref_sha1, (char *)sha1);
}