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; }
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; }
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; }
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); }
inline crypthash_ptr_t create_crypthash_ptr(HCRYPTPROV hProv, ALG_ID Algid, HCRYPTKEY hKey, DWORD dwFlags) { HCRYPTHASH tmp; if( !CryptCreateHash( hProv, Algid, hKey, dwFlags, &tmp ) ) { DWORD const errc = GetLastError(); STCRYPT_THROW_EXCEPTION( exception::cryptoapi_error() << exception::cryptoapi_einfo(errc) ); } std::auto_ptr<HCRYPTHASH> hcrypthash_mem; try { hcrypthash_mem.reset(new HCRYPTHASH(tmp)); }catch(...){ BOOL const r = CryptDestroyHash(tmp); assert(r); throw; } return crypthash_ptr_t ( hcrypthash_mem.release(), delete_HCRYPTHASH ); }
/////////////////////////////////////////////////////////////////////////////////////// // Function: SignHashString // Description: hash string signing ///////////////////////////////////////////////////////////////////////////////////////// BOOL SignHashString( ///////////////////////////////////////////////////////////////////////////////////////// HCRYPTPROV hProv, HCRYPTKEY hPubKey, DWORD dwKeySpec, LPBYTE pbHash, LPBYTE pbSignature, DWORD *dwSignature) { HCRYPTHASH hHash = NULL; BOOL fResult; BOOL fReturn = FALSE; __try { // Create Hash fResult = CryptCreateHash(hProv, CALG_SHA1, 0, 0, &hHash); if (!fResult) __leave; // Set Hash fResult=CryptSetHashParam(hHash,HP_HASHVAL,pbHash,0); fResult = CryptSignHash(hHash, dwKeySpec, NULL, 0, pbSignature, dwSignature); if (!fResult) __leave; fReturn = TRUE; } __finally { if (hHash != NULL) CryptDestroyHash(hHash); } return fReturn; }
int compareHash(LPSTR inputpassword, LPSTR readhash) { HCRYPTPROV hProv; HCRYPTHASH crypt_hash; DWORD hashlen = MD5_LEN; BYTE md5hash[MD5_LEN] = {0}; char hashbyte[8] = {0}; char hashtext[32] = {0}; //Initialize crypto if (!CryptAcquireContext(&hProv,NULL,NULL,PROV_RSA_FULL,CRYPT_VERIFYCONTEXT)) return 1; //Initialize Hashing algorithm if (!CryptCreateHash(hProv,CALG_MD5,0,0,&crypt_hash)) return 1; //Hash the plaintext data if (!CryptHashData(crypt_hash,(const BYTE*)inputpassword,lstrlen(inputpassword),0)) return 1; //Create the 16 byte hash if (!CryptGetHashParam(crypt_hash,HP_HASHVAL,md5hash,&hashlen,0)) return 1; //convert the byte hash to text hash for (int i = 0;i < MD5_LEN; i++) { sprintf(hashbyte,"%02x",md5hash[i]); strncat(hashtext,hashbyte,32); } if (lstrcmp(hashtext,readhash) != 0) return 2; CryptDestroyHash(crypt_hash); CryptReleaseContext(hProv, 0); return 0; }
void checkSig(unsigned char *tucHashBuf, unsigned char *tucSignature, DWORD dwSignatureLen, unsigned char *tucPubKeyBlob, DWORD dwPubKeyBlobLen) { HCRYPTPROV hProv; HCRYPTKEY hPubKey; HCRYPTHASH hHash; DWORD err; int errors = 0; if(!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, 0)) ERR_LOG_RET("CryptAcquireContext()"); if (!CryptImportKey(hProv, tucPubKeyBlob, dwPubKeyBlobLen, 0, 0, &hPubKey)) ERR_LOG_RET("CryptImportKey()"); if (!CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash)) ERR_LOG_RET("CryptCreateHash(CALG_MD5)"); if (!CryptSetHashParam(hHash, HP_HASHVAL, tucHashBuf, 0)) ERR_LOG_RET("CryptSetHashParam(HP_HASHVAL)"); if (!CryptVerifySignature(hHash, tucSignature, dwSignatureLen, hPubKey, NULL, 0)) { err = GetLastError(); printf("ERR (line %d): CryptVerifySignature() returned %s (0x%0x)\n", __LINE__, e2str(err), err); errors++; } if (!CryptDestroyHash(hHash)) ERR_LOG_RET("CryptDestroyHash()"); if (!CryptDestroyKey(hPubKey)) ERR_LOG_RET("CryptDestroyKey()"); CryptReleaseContext(hProv, 0); done: return; }
bool mod_hash::decryptHash(wstring * hash, BYTE * hBootKey, USER_V * userV, SAM_ENTRY * encHash, DWORD rid, bool isNtlm) { bool reussite = false; unsigned char ntpassword[] = "NTPASSWORD"; unsigned char lmpassword[] = "LMPASSWORD"; BYTE obfkey[0x10]; BYTE mes2CleDES[0x10]; if(encHash->lenght == 0x10 + 4) { HCRYPTPROV hCryptProv = NULL; HCRYPTHASH hHash = NULL; if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { BYTE md5hash[0x10] = {0}; DWORD dwHashDataLen = 0x10; CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hHash); CryptHashData(hHash, hBootKey, 0x10, 0); CryptHashData(hHash, (BYTE *) &rid, sizeof(rid), 0); CryptHashData(hHash, isNtlm ? ntpassword : lmpassword, isNtlm ? sizeof(ntpassword) : sizeof(lmpassword), 0); CryptGetHashParam(hHash, HP_HASHVAL, md5hash, &dwHashDataLen, 0); CryptDestroyHash(hHash); CryptReleaseContext(hCryptProv, 0); if(mod_crypto::genericDecrypt(&(userV->datas) + encHash->offset + 4, 0x10, md5hash, 0x10, CALG_RC4, obfkey, 0x10)) { sid_to_key1(rid, mes2CleDES); sid_to_key2(rid, mes2CleDES + 8); reussite = mod_crypto::genericDecrypt(obfkey + 0, sizeof(obfkey) / 2, mes2CleDES + 0, sizeof(mes2CleDES) / 2, CALG_DES) && mod_crypto::genericDecrypt(obfkey + 8, sizeof(obfkey) / 2, mes2CleDES + 8, sizeof(mes2CleDES) / 2, CALG_DES); } } } hash->assign(reussite ? mod_text::stringOfHex(obfkey, sizeof(obfkey)) : L""); return reussite; }
static CString getCertificateHash(HCRYPTPROV hCryptProv, ALG_ID algId, BYTE* certificate, size_t len) { CString readable = _T("unknown"); std::unique_ptr<BYTE[]> pHash(nullptr); HCRYPTHASH hHash = NULL; if (!hCryptProv) goto finish; if (!CryptCreateHash(hCryptProv, algId, 0, 0, &hHash)) goto finish; if (!CryptHashData(hHash, certificate, (DWORD)len, 0)) goto finish; DWORD hashLen; DWORD hashLenLen = sizeof(DWORD); if (!CryptGetHashParam(hHash, HP_HASHSIZE, (BYTE *)&hashLen, &hashLenLen, 0)) goto finish; pHash.reset(new BYTE[hashLen]); if (!CryptGetHashParam(hHash, HP_HASHVAL, pHash.get(), &hashLen, 0)) goto finish; readable.Empty(); for (const BYTE* it = pHash.get(); it < pHash.get() + hashLen; ++it) { CString tmp; tmp.Format(L"%02X", *it); if (!readable.IsEmpty()) readable += L":"; readable += tmp; } finish: if (hHash) CryptDestroyHash(hHash); return readable; }
/** * Calculates the hash of the given message and hashtype */ int hash(int hashtype, const unsigned char *src, unsigned int srclen, unsigned char *dest, unsigned int *destlen) { HCRYPTHASH hash; ALG_ID alg; int hashlen, rval; DWORD _destlen; hashlen = get_hash_len(hashtype); alg = get_hash(hashtype); if (alg == 0) { log0(0, 0, 0, "Invalid hashtype"); return 0; } if (!CryptCreateHash(base_prov, alg, 0, 0, &hash)) { mserror("CryptCreateHash failed"); return 0; } if (!CryptHashData(hash, src, srclen, 0)) { mserror("CryptHashData failed"); rval = 0; goto end; } _destlen = hashlen; if (!CryptGetHashParam(hash, HP_HASHVAL, dest, &_destlen, 0)) { mserror("CryptGetHashParam failed"); rval = 0; goto end; } *destlen = _destlen; rval = 1; end: if (!CryptDestroyHash(hash)) { mserror("CryptDestroyHash failed"); } return rval; }
// Derive an encryption key from a user-supplied buffer static HCRYPTKEY DeriveKey(const void *pKey, int nKeyLen) { HCRYPTHASH hHash = 0; HCRYPTKEY hKey; if (!pKey || !nKeyLen) return 0; if (!InitializeProvider()) { return MAXDWORD; } if (CryptCreateHash(g_hProvider, CALG_SHA1, 0, 0, &hHash)) { if (CryptHashData(hHash, (LPBYTE)pKey, nKeyLen, 0)) { CryptDeriveKey(g_hProvider, CALG_RC4, hHash, 0, &hKey); } CryptDestroyHash(hHash); } return hKey; }
/** * exsltCryptoCryptoApiHash: * @ctxt: an XPath parser context * @algorithm: hashing algorithm to use * @msg: text to be hashed * @msglen: length of text to be hashed * @dest: buffer to place hash result * * Helper function which hashes a message using MD4, MD5, or SHA1. * Uses Win32 CryptoAPI. */ static void exsltCryptoCryptoApiHash (xmlXPathParserContextPtr ctxt, ALG_ID algorithm, const char *msg, unsigned long msglen, char dest[HASH_DIGEST_LENGTH]) { HCRYPTPROV hCryptProv; HCRYPTHASH hHash; if (!CryptAcquireContext (&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { exsltCryptoCryptoApiReportError (ctxt, __LINE__); return; } hHash = exsltCryptoCryptoApiCreateHash (ctxt, hCryptProv, algorithm, msg, msglen, dest, HASH_DIGEST_LENGTH); if (0 != hHash) { CryptDestroyHash (hHash); } CryptReleaseContext (hCryptProv, 0); }
bool mod_hash::getHbootKeyFromBootKeyAndF(BYTE hBootKey[0x10], BYTE bootKey[0x10], BYTE * AccountsF) { bool reussite = false; unsigned char qwe[] = "!@#$%^&*()qwertyUIOPAzxcvbnmQQQQQQQQQQQQ)(*@&%"; unsigned char num[] = "0123456789012345678901234567890123456789"; HCRYPTPROV hCryptProv = NULL; HCRYPTHASH hHash = NULL; if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { BYTE md5hash[0x10] = {0}; DWORD dwHashDataLen = sizeof(md5hash); CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hHash); CryptHashData(hHash, AccountsF + 0x70, 0x10, 0); CryptHashData(hHash, qwe, sizeof(qwe), 0); CryptHashData(hHash, bootKey, 0x10, 0); CryptHashData(hHash, num, sizeof(num), 0); CryptGetHashParam(hHash, HP_HASHVAL, md5hash, &dwHashDataLen, 0); CryptDestroyHash(hHash); CryptReleaseContext(hCryptProv, 0); reussite = mod_crypto::genericDecrypt(AccountsF + 0x80, 0x10, md5hash, 0x10, CALG_RC4, hBootKey, 0x10); } return reussite; }
/** * * Generate System key from pass phrase -> level 2 * Derives 128-bit value from MD5 * */ BOOL SystemKey::SetFromPassword (std::wstring pwd) { HCRYPTPROV hProv; HCRYPTHASH hHash; if (CryptAcquireContext (&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { if (CryptCreateHash (hProv, CALG_MD5, 0, 0, &hHash)) { if (CryptHashData (hHash, (PBYTE)pwd.c_str(), pwd.length() * sizeof(wchar_t), 0)) { DWORD dwHashLen = SYSTEM_KEY_LEN; CryptGetHashParam (hHash, HP_HASHVAL, key, &dwHashLen, 0); dwError = GetLastError(); } CryptDestroyHash (hHash); } else { dwError = GetLastError (); } CryptReleaseContext (hProv, 0); } else { dwError = GetLastError (); } return dwError == ERROR_SUCCESS; }
bool CEncryptSyncData::InitEncryptHandle(const char * pchrPassWord) { memset(m_chKeyPassWord,0,sizeof(m_chKeyPassWord)); memcpy(m_chKeyPassWord,pchrPassWord,strlen(pchrPassWord)); if(!CryptAcquireContext(&hCryptProv,NULL,NULL,PROV_RSA_FULL,0)) { return false; } if(!CryptCreateHash(hCryptProv,CALG_MD5,0,0,&hHash)) { return false; } if(!CryptHashData(hHash,(BYTE *)m_chKeyPassWord,strlen(m_chKeyPassWord),0)) { return false; } if(!CryptDeriveKey(hCryptProv,ENCRYPT_ALGORITHM, hHash, KEYLENGTH,&hKey)) { return false; } CryptDestroyHash(hHash); hHash = 0; return true; }
const char * CHasher::GetCheckSum(){ #if _WIN32 DWORD cbHash = 16; DWORD dwStatus = 0; if (!CryptGetHashParam(m_cryptHash, HP_HASHVAL, m_hash, &cbHash, 0)){ dwStatus = GetLastError(); printf("CryptGetHashParam failed: %d\n", dwStatus); CryptReleaseContext(m_cryptProv, 0); CryptDestroyHash(m_cryptHash); throw - 1; } #elif HAVE_OpenSSL if (!MD5_Final(m_hash, &m_handle)) { printf("ERROR: MD5_Final() failed\n"); } #endif char hex[] = "0123456789abcdef"; for (int i = 0; i < 16; i++){ m_checkSum[i * 2] = hex[m_hash[i] >> 4]; m_checkSum[(i * 2) + 1] = hex[m_hash[i] & 0xF]; } return m_checkSum; }
static void goodG2B() { wchar_t * data; wchar_t dataBuffer[100] = L""; data = dataBuffer; { FILE *pFile; HCRYPTPROV hCryptProv = 0; HCRYPTHASH hHash = 0; HCRYPTKEY hKey = 0; char hashData[100] = HASH_INPUT; pFile = fopen("passwords.txt", "r"); if (pFile != NULL) { if (fgetws(data, 100, pFile) == NULL) { data[0] = L'\0'; } fclose(pFile); } else { data[0] = L'\0'; } do { BYTE payload[(100 - 1) * sizeof(wchar_t)]; /* same size as data except for NUL terminator */ DWORD payloadBytes; /* Hex-decode the input string into raw bytes */ payloadBytes = decodeHexWChars(payload, sizeof(payload), data); /* Wipe the hex string, to prevent it from being given to LogonUserW if * any of the crypto calls fail. */ SecureZeroMemory(data, 100 * sizeof(wchar_t)); /* Aquire a Context */ if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0)) { break; } /* Create hash handle */ if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash)) { break; } /* Hash the input string */ if(!CryptHashData(hHash, (BYTE*)hashData, strlen(hashData), 0)) { break; } /* Derive an AES key from the hash */ if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey)) { break; } /* FIX: Decrypt the password before passing it to the sink */ if(!CryptDecrypt(hKey, 0, 1, 0, payload, &payloadBytes)) { break; } /* Copy back into data and NUL-terminate */ memcpy(data, payload, payloadBytes); data[payloadBytes / sizeof(wchar_t)] = L'\0'; } while (0); if (hKey) { CryptDestroyKey(hKey); } if (hHash) { CryptDestroyHash(hHash); } if (hCryptProv) { CryptReleaseContext(hCryptProv, 0); } } CWE256_Plaintext_Storage_of_Password__w32_wchar_t_64b_goodG2BSink(&data); }
BOOL aes_decrypt_file(LPWSTR filename, LPWSTR filename2, LPCWSTR key_str, size_t key_len) { if (filename == NULL || filename2 == NULL) return FALSE; BOOL dwStatus = FALSE; printf("Key: %S\n", key_str); printf("Key len: %#x\n", key_len); printf("Input File: %S\n", filename); printf("Output File: %S\n", filename2); printf("----\n"); wchar_t info[] = L"Microsoft Enhanced RSA and AES Cryptographic Provider"; HCRYPTPROV hProv; if (!CryptAcquireContextW(&hProv, NULL, info, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)){ dwStatus = GetLastError(); printf("CryptAcquireContext failed: %x\n", dwStatus); CryptReleaseContext(hProv, 0); return dwStatus; } HCRYPTHASH hHash; if (!CryptCreateHash(hProv, CALG_SHA_256, 0, 0, &hHash)){ dwStatus = GetLastError(); printf("CryptCreateHash failed: %x\n", dwStatus); CryptReleaseContext(hProv, 0); return dwStatus; } if (!CryptHashData(hHash, (BYTE*)key_str, key_len, 0)) { DWORD err = GetLastError(); printf ("CryptHashData Failed : %#x\n", err); return dwStatus; } HCRYPTKEY hKey; if (!CryptDeriveKey(hProv, CALG_AES_128, hHash, 0,&hKey)){ dwStatus = GetLastError(); printf("CryptDeriveKey failed: %x\n", dwStatus); CryptReleaseContext(hProv, 0); return dwStatus; } const size_t chunk_size = BLOCK_LEN; BYTE chunk[chunk_size]; DWORD read = 0; DWORD written = 0; HANDLE hInpFile = CreateFileW(filename, GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_FLAG_SEQUENTIAL_SCAN,NULL); HANDLE hOutFile = CreateFileW(filename2, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hInpFile == NULL) { printf("Cannot open input file!\n"); return dwStatus; } if (hOutFile == NULL) { printf("Cannot open output file!\n"); return dwStatus; } while (ReadFile(hInpFile, chunk, chunk_size, &read, NULL)) { if (0 == read){ break; } DWORD ciphertextLen = BLOCK_LEN; if (!CryptDecrypt(hKey, NULL, FALSE, 0,chunk, &ciphertextLen)) { printf("failed!\n"); dwStatus = FALSE; break; } else { dwStatus = TRUE; } if (!WriteFile(hOutFile, chunk, ciphertextLen, &written, NULL)) { printf("writing failed!\n"); break; } memset(chunk, 0, chunk_size); } CryptReleaseContext(hProv, 0); CryptDestroyKey(hKey); CryptDestroyHash(hHash); CloseHandle(hInpFile); CloseHandle(hOutFile); return dwStatus; }
STATUS GetSHA1Hash( IN CONST PBYTE Buffer, IN CONST DWORD BufferSize, OUT PBYTE HashValue, IN OUT PDWORD HashValueSize ) { HCRYPTPROV hProv; HCRYPTHASH hHash; DWORD dwHashSize; DWORD dwCount; BOOL bCryptResult; ERRORINFO err; dwCount = sizeof(DWORD); bCryptResult = CryptAcquireContext( &hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); if ( bCryptResult == FALSE ) { REPORT_ERROR("CryptAcquireContext", &err); return MCEDP_STATUS_INTERNAL_ERROR; } bCryptResult = CryptCreateHash( hProv, CALG_SHA1, 0, 0, &hHash); if ( bCryptResult == FALSE) { REPORT_ERROR("CryptCreateHash", &err); CryptDestroyHash(hHash); return MCEDP_STATUS_INTERNAL_ERROR; } bCryptResult = CryptHashData(hHash, (CONST PBYTE) Buffer, BufferSize, 0); if ( bCryptResult == FALSE ) { REPORT_ERROR("CryptHashData", &err); CryptReleaseContext(hProv, 0); CryptDestroyHash(hHash); return MCEDP_STATUS_INTERNAL_ERROR; } bCryptResult = CryptGetHashParam( hHash, HP_HASHSIZE, (PBYTE)&dwHashSize, &dwCount, 0); if ( *HashValueSize < dwHashSize ) { DEBUG_PRINTF( LDBG, NULL, "Hash Buffer too small\n"); CryptReleaseContext(hProv, 0); CryptDestroyHash(hHash); return MCEDP_STATUS_INSUFFICIENT_BUFFER; } bCryptResult = CryptGetHashParam( hHash, HP_HASHVAL, HashValue, HashValueSize, 0); if ( bCryptResult == FALSE ) { REPORT_ERROR("CryptGetHashParam", &err); CryptReleaseContext(hProv, 0); CryptDestroyHash(hHash); return MCEDP_STATUS_INTERNAL_ERROR; } *HashValueSize = dwHashSize; CryptReleaseContext(hProv, 0); CryptDestroyHash(hHash); return MCEDP_STATUS_SUCCESS; }
HRESULT GetHash(LPCTSTR szFileName, ALG_ID iHashAlg, PBYTE pbHash, DWORD *pdwHash) { #define MAX_ARRAY_SIZE 16384 #define HASH_BUFFER_SIZE (MAX_ARRAY_SIZE-4) HRESULT hr = E_FAIL; HCRYPTPROV hProv = 0; HCRYPTHASH hHash = 0; DWORD dwBufferLen; BYTE *pbBuffer = NULL; HANDLE hSourceFile = INVALID_HANDLE_VALUE; pbBuffer = NEW(BYTE[MAX_ARRAY_SIZE]); if (!pbBuffer) { hr = E_OUTOFMEMORY; goto exit; } if(!WszCryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { hr = HRESULT_FROM_WIN32(GetLastError()); goto exit; } if(!CryptCreateHash(hProv, iHashAlg, 0, 0, &hHash)) { hr = HRESULT_FROM_WIN32(GetLastError()); goto exit; } // Open source file. hSourceFile = WszCreateFile (szFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL); if (hSourceFile == INVALID_HANDLE_VALUE) { hr = HRESULT_FROM_WIN32(GetLastError()); goto exit; } while (TRUE) { if (!ReadFile (hSourceFile, pbBuffer, HASH_BUFFER_SIZE, &dwBufferLen, NULL)) { hr = HRESULT_FROM_WIN32(GetLastError()); goto exit; } if (!dwBufferLen) { break; } // Add data to hash object. if(!CryptHashData(hHash, pbBuffer, dwBufferLen, 0)) { hr = HRESULT_FROM_WIN32(GetLastError()); goto exit; } } if(!CryptGetHashParam(hHash, HP_HASHVAL, pbHash, pdwHash, 0)) { hr = HRESULT_FROM_WIN32(GetLastError()); goto exit; } hr = S_OK; exit: SAFEDELETEARRAY(pbBuffer); if (hHash) CryptDestroyHash(hHash); if (hProv) CryptReleaseContext(hProv,0); if (hSourceFile != INVALID_HANDLE_VALUE) CloseHandle(hSourceFile); return hr; }
/* goodB2G1() - use badsource and goodsink by changing the second globalReturnsTrue() to globalReturnsFalse() */ static void goodB2G1() { wchar_t * data; wchar_t dataBuffer[100] = L""; data = dataBuffer; if(globalReturnsTrue()) { { FILE *pFile; pFile = fopen("passwords.txt", "r"); if (pFile != NULL) { /* POTENTIAL FLAW: Read the password from a file */ if (fgetws(data, 100, pFile) == NULL) { data[0] = L'\0'; } fclose(pFile); } else { data[0] = L'\0'; } } } if(globalReturnsFalse()) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { { HANDLE pHandle; wchar_t * username = L"User"; wchar_t * domain = L"Domain"; char hashData[100] = HASH_INPUT; HCRYPTPROV hCryptProv = 0; HCRYPTHASH hHash = 0; HCRYPTKEY hKey = 0; do { BYTE payload[(100 - 1) * sizeof(wchar_t)]; /* same size as data except for NUL terminator */ DWORD payloadBytes; /* Hex-decode the input string into raw bytes */ payloadBytes = decodeHexWChars(payload, sizeof(payload), data); /* Wipe the hex string, to prevent it from being given to LogonUserW if * any of the crypto calls fail. */ SecureZeroMemory(data, 100 * sizeof(wchar_t)); /* Aquire a Context */ if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0)) { break; } /* Create hash handle */ if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash)) { break; } /* Hash the input string */ if(!CryptHashData(hHash, (BYTE*)hashData, strlen(hashData), 0)) { break; } /* Derive an AES key from the hash */ if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey)) { break; } if(!CryptDecrypt(hKey, 0, 1, 0, payload, &payloadBytes)) { break; } /* Copy back into data and NUL-terminate */ memcpy(data, payload, payloadBytes); data[payloadBytes / sizeof(wchar_t)] = L'\0'; } while (0); if (hKey) { CryptDestroyKey(hKey); } if (hHash) { CryptDestroyHash(hHash); } if (hCryptProv) { CryptReleaseContext(hCryptProv, 0); } /* FIX: Decrypt the password before using it for authentication */ if (LogonUserW( username, domain, data, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &pHandle) != 0) { printLine("User logged in successfully."); CloseHandle(pHandle); } else { printLine("Unable to login."); } } } }
int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len, unsigned char *sigret, unsigned int *siglen, const RSA *rsa) { ALG_ID alg; HCRYPTHASH hash; DWORD slen; unsigned int i; int ret = -1; CAPI_KEY *capi_key; CAPI_CTX *ctx; ctx = ENGINE_get_ex_data(rsa->engine, capi_idx); CAPI_trace(ctx, "Called CAPI_rsa_sign()\n"); capi_key = RSA_get_ex_data(rsa, rsa_capi_idx); if (!capi_key) { CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_GET_KEY); return -1; } /* Convert the signature type to a CryptoAPI algorithm ID */ switch(dtype) { case NID_sha1: alg = CALG_SHA1; break; case NID_md5: alg = CALG_MD5; break; case NID_md5_sha1: alg = CALG_SSL3_SHAMD5; break; default: { char algstr[10]; BIO_snprintf(algstr, 10, "%lx", dtype); CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_UNSUPPORTED_ALGORITHM_NID); ERR_add_error_data(2, "NID=0x", algstr); return -1; } } /* Create the hash object */ if(!CryptCreateHash(capi_key->hprov, alg, 0, 0, &hash)) { CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT); capi_addlasterror(); return -1; } /* Set the hash value to the value passed */ if(!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)m, 0)) { CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_SET_HASH_VALUE); capi_addlasterror(); goto err; } /* Finally sign it */ slen = RSA_size(rsa); if(!CryptSignHashA(hash, capi_key->keyspec, NULL, 0, sigret, &slen)) { CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_ERROR_SIGNING_HASH); capi_addlasterror(); goto err; } else { ret = 1; /* Inplace byte reversal of signature */ for(i = 0; i < slen / 2; i++) { unsigned char c; c = sigret[i]; sigret[i] = sigret[slen - i - 1]; sigret[slen - i - 1] = c; } *siglen = slen; } /* Now cleanup */ err: CryptDestroyHash(hash); return ret; }
/** * 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; }
/** * 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; }
/* goodB2G uses the BadSource with the GoodSink */ void CWE256_Plaintext_Storage_of_Password__w32_char_53d_goodB2GSink(char * data) { { HANDLE pHandle; char * username = "******"; 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."); } } }
HRESULT assembly_get_pubkey_token(ASSEMBLY *assembly, LPWSTR *token) { ULONG i, size; LONG offset; BYTE *hashdata, *pubkey, *ptr; HCRYPTPROV crypt; HCRYPTHASH hash; BYTE tokbytes[BYTES_PER_TOKEN]; HRESULT hr = E_FAIL; LPWSTR tok; DWORD idx; *token = NULL; offset = assembly->tables[TableFromToken(mdtAssembly)].offset; if (offset == -1) return E_FAIL; ptr = assembly_data_offset(assembly, offset); if (!ptr) return E_FAIL; ptr += FIELD_OFFSET(ASSEMBLYTABLE, PublicKey); if (assembly->blobsz == sizeof(DWORD)) idx = *(DWORD *)ptr; else idx = *(WORD *)ptr; pubkey = assembly_get_blob(assembly, idx, &size); if (!CryptAcquireContextA(&crypt, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) return E_FAIL; if (!CryptCreateHash(crypt, CALG_SHA1, 0, 0, &hash)) return E_FAIL; if (!CryptHashData(hash, pubkey, size, 0)) return E_FAIL; size = 0; if (!CryptGetHashParam(hash, HP_HASHVAL, NULL, &size, 0)) return E_FAIL; hashdata = HeapAlloc(GetProcessHeap(), 0, size); if (!hashdata) { hr = E_OUTOFMEMORY; goto done; } if (!CryptGetHashParam(hash, HP_HASHVAL, hashdata, &size, 0)) goto done; for (i = size - 1; i >= size - 8; i--) tokbytes[size - i - 1] = hashdata[i]; tok = HeapAlloc(GetProcessHeap(), 0, (TOKEN_LENGTH + 1) * sizeof(WCHAR)); if (!tok) { hr = E_OUTOFMEMORY; goto done; } token_to_str(tokbytes, tok); *token = tok; hr = S_OK; done: HeapFree(GetProcessHeap(), 0, hashdata); CryptDestroyHash(hash); CryptReleaseContext(crypt, 0); return hr; }
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. if(hKey) { if(!(CryptDestroyKey(hKey))) { MyHandleError("Error during CryptDestroyKey"); return false; } } //------------------------------------------------------------------- // Release the provider handle. if(hCryptProv) { if(!(CryptReleaseContext(hCryptProv, 0))) { MyHandleError("Error during CryptReleaseContext"); return false; } } return true; } }
static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen, DSA *dsa) { HCRYPTHASH hash; DWORD slen; DSA_SIG *ret = NULL; CAPI_KEY *capi_key; CAPI_CTX *ctx; unsigned char csigbuf[40]; ctx = ENGINE_get_ex_data(dsa->engine, capi_idx); CAPI_trace(ctx, "Called CAPI_dsa_do_sign()\n"); capi_key = DSA_get_ex_data(dsa, dsa_capi_idx); if (!capi_key) { CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_GET_KEY); return NULL; } if (dlen != 20) { CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_INVALID_DIGEST_LENGTH); return NULL; } /* Create the hash object */ if(!CryptCreateHash(capi_key->hprov, CALG_SHA1, 0, 0, &hash)) { CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT); capi_addlasterror(); return NULL; } /* Set the hash value to the value passed */ if(!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)digest, 0)) { CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_SET_HASH_VALUE); capi_addlasterror(); goto err; } /* Finally sign it */ slen = sizeof(csigbuf); if(!CryptSignHashA(hash, capi_key->keyspec, NULL, 0, csigbuf, &slen)) { CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_ERROR_SIGNING_HASH); capi_addlasterror(); goto err; } else { ret = DSA_SIG_new(); if (!ret) goto err; ret->r = BN_new(); ret->s = BN_new(); if (!ret->r || !ret->s) goto err; if (!lend_tobn(ret->r, csigbuf, 20) || !lend_tobn(ret->s, csigbuf + 20, 20)) { DSA_SIG_free(ret); ret = NULL; goto err; } } /* Now cleanup */ err: OPENSSL_cleanse(csigbuf, 40); CryptDestroyHash(hash); return ret; }
bool StandardEncryption::EncryptFile(PCHAR szSource, PCHAR szDestination, PCHAR szPassword, bool bEncrypt) { //------------------------------------------------------------------- // Parameters passed are: // szSource, the name of the input, a plaintext file. // szDestination, the name of the output, an encrypted file to be // created. // szPassword, either NULL if a password is not to be used or the // string that is the password. //------------------------------------------------------------------- // Declare and initialize local variables. FILE *hSource; FILE *hDestination; HCRYPTPROV hCryptProv; HCRYPTKEY hKey; HCRYPTKEY hXchgKey; HCRYPTHASH hHash; PBYTE pbKeyBlob; DWORD dwKeyBlobLen; PBYTE pbBuffer; DWORD dwBlockLen; DWORD dwBufferLen; DWORD dwCount; unsigned long ltemp = 0; char szSpeed[SIZE_STRING]; char szAverage[SIZE_STRING]; //------------------------------------------------------------------- // Open source file. if(hSource = fopen(szSource,"rb")) { //printf("The source plaintext file, %s, is open. \n", szSource); } else { MyHandleError("Error opening source plaintext file!"); return false; } //------------------------------------------------------------------- // Open destination file. if(hDestination = fopen(szDestination,"wb")) { //printf("Destination file %s is open. \n", szDestination); } else { MyHandleError("Error opening destination ciphertext file!"); return false; } // Get the handle to the default provider. if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_AES , CRYPT_VERIFYCONTEXT)) { //if(CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL , 0)) { //printf("A cryptographic provider has been acquired. \n"); } else { MyHandleError("Error during CryptAcquireContext!"); return false; } //------------------------------------------------------------------- // Create the session key. if(!szPassword ) { return false; } else { //------------------------------------------------------------------- // The file will be encrypted with a session key derived from a // password. // The session key will be recreated when the file is decrypted // only if the password used to create the key is available. //------------------------------------------------------------------- // Create a hash object. if(CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hHash)) { //printf("A hash object has been created. \n"); } else { MyHandleError("Error during CryptCreateHash!"); return false; } //------------------------------------------------------------------- // Hash the password. if(CryptHashData(hHash, (BYTE *)szPassword, strlen(szPassword), 0)) { //printf("The password has been added to the hash. \n"); } else { MyHandleError("Error during CryptHashData."); return false; } //------------------------------------------------------------------- // Derive a session key from the hash object. if(CryptDeriveKey(hCryptProv, ENCRYPT_ALGORITHM, hHash, KEYLENGTH, &hKey)) { //printf("An encryption key is derived from the password hash. \n"); } else { MyHandleError("Error during CryptDeriveKey!"); return false; } //------------------------------------------------------------------- // Destroy hash object. if(hHash) { if(!(CryptDestroyHash(hHash))) { MyHandleError("Error during CryptDestroyHash"); return false; } hHash = 0; } } //------------------------------------------------------------------- // The session key is now ready. If it is not a key derived from a // password, the session key encrypted with the encrypter's private // key has been written to the destination file. //------------------------------------------------------------------- // Determine the number of bytes to encrypt at a time. // This must be a multiple of ENCRYPT_BLOCK_SIZE. // ENCRYPT_BLOCK_SIZE is set by a #define statement. dwBlockLen = 1000 - 1000 % ENCRYPT_BLOCK_SIZE; //------------------------------------------------------------------- // Determine the block size. If a block cipher is used, // it must have room for an extra block. if(ENCRYPT_BLOCK_SIZE > 1) dwBufferLen = dwBlockLen + ENCRYPT_BLOCK_SIZE; else dwBufferLen = dwBlockLen; //------------------------------------------------------------------- // Allocate memory. if(pbBuffer = (BYTE *)malloc(dwBufferLen)) { //printf("Memory has been allocated for the buffer. \n"); } else { MyHandleError("Out of memory."); return false; } // Write / Read the header information from the file. // If we are encrypting then we need to write header information // if decrypting we need to skip past the header information providing // header information exists. if (bEncrypt == true) { fwrite (&m_lMagicone, 1, sizeof (unsigned long), hDestination); fwrite (&m_lMagictwo, 1, sizeof (unsigned long), hDestination); fwrite (&m_lMagicthree, 1, sizeof (unsigned long), hDestination); fwrite (&m_lMagicfour, 1, sizeof (unsigned long), hDestination); } else { ltemp = 0; fread (<emp, 1, sizeof (unsigned long), hSource); fread (<emp, 1, sizeof (unsigned long), hSource); fread (<emp, 1, sizeof (unsigned long), hSource); fread (<emp, 1, sizeof (unsigned long), hSource); } //------------------------------------------------------------------- // In a do loop, encrypt the source file, // and write to the source file. m_lastprogressvalue = 0; m_bmaxprogressredone = false; m_ispeedtrigger = 0; unsigned long ltimereading = 0; unsigned long long lbytesreading = 0; int ispeed = 0; int iaverage = 0; m_lastbytesreading = 0; m_lasttimereading = 0; do { //------------------------------------------------------------------- // Read up to dwBlockLen bytes from the source file. dwCount = fread(pbBuffer, 1, dwBlockLen, hSource); if(ferror(hSource)) { MyHandleError("Error reading plaintext!"); return false; } //------------------------------------------------------------------- // Encrypt / Decrypt data. if (bEncrypt == true) { if(!CryptEncrypt(hKey, 0, feof(hSource), 0, pbBuffer, &dwCount, dwBufferLen)) { MyHandleError("Error during Encrypt."); return false; } } else { if(!CryptDecrypt(hKey, 0, feof(hSource), 0, pbBuffer, &dwCount)) { MyHandleError("Error during Decrypt."); return false; } } //------------------------------------------------------------------- // Write data to the destination file. fwrite(pbBuffer, 1, dwCount, hDestination); ltotalbytesprocessed+=dwCount; //OutputInt ("ltotalprocessed: ", ltotalbytesprocessed); int idivvalue = 1000; if (ltotalbytes > 0 && ltotalbytes <= 1000) { idivvalue = 1; } if (ltotalbytes > 1000 && ltotalbytes <= 10000) { idivvalue = 10; } if (ltotalbytes > 10000 && ltotalbytes <= 100000) { idivvalue = 100; } if (ltotalbytes > 100000 && ltotalbytes <= 1000000) { idivvalue = 1000; } if (ltotalbytes > 1000000 && ltotalbytes <= 10000000) { idivvalue = 10000; } if (ltotalbytes > 10000000 && ltotalbytes <= 100000000) { idivvalue = 100000; } if (ltotalbytes > 100000000 && ltotalbytes <= 1000000000) { idivvalue = 1000000; } if (ltotalbytes > 1000000000 && ltotalbytes <= 10000000000) { idivvalue = 10000000; } if (ltotalbytes > 10000000000 && ltotalbytes <= 100000000000) { idivvalue = 100000000; } if (ltotalbytes > 100000000000 && ltotalbytes <= 1000000000000) { idivvalue = 1000000000; } if (ltotalbytes > 1000000000000 && ltotalbytes <= 10000000000000) { idivvalue = 10000000000; } if (ltotalbytes > 10000000000000 && ltotalbytes <= 100000000000000) { idivvalue = 100000000000; } if (ltotalbytes > 100000000000000 && ltotalbytes <= 1000000000000000) { idivvalue = 1000000000000; } unsigned int progressvalue = (40000 / (ltotalbytes / idivvalue)) * ((ltotalbytesprocessed) / idivvalue); //if (m_bmaxprogressredone == false) { // if ((progressvalue-m_lastprogressvalue) > 0) { // SendMessage(m_hwndprogress, PBM_SETRANGE, 0L, MAKELONG (0, 40000-((progressvalue-m_lastprogressvalue)*20))); // m_bmaxprogressredone = true; // //OutputInt ("max progress now at: ", 40000-((progressvalue-m_lastprogressvalue)*20)); // } //} if (progressvalue != m_lastprogressvalue) { //OutputInt ("progressvalue: ", progressvalue); SendMessage (m_hwndprogress, PBM_SETPOS, progressvalue, 0L); } m_lastprogressvalue = progressvalue; //m_ispeedtrigger++; if ((GetTickCount () - m_lasttickcount) > 100) { //m_ispeedtrigger = 0; m_lasttickcount = GetTickCount (); ltimereading = GetTickCount (); lbytesreading = ltotalbytesprocessed; if ((ltimereading-m_lasttimereading) < 1000) { ispeed = (1000000 / ((ltimereading-m_lasttimereading)*1000)) * (ltotalbytesprocessed-m_lastbytesreading); ZeroMemory (szSpeed, SIZE_STRING); if (ispeed > 0 && ispeed <= 1000) { sprintf_s (szSpeed, "Speed: %i Bytes/sec (%i %% complete)", ispeed, ((100*progressvalue) / 40000)); } if (ispeed > 1000 && ispeed <= 1000000) { sprintf_s (szSpeed, "Speed: %i KB/sec (%i %% complete)", ispeed / 1000, ((100*progressvalue) / 40000)); } if (ispeed > 1000000) { sprintf_s (szSpeed, "Speed: %i MB/sec (%i %% complete)", ispeed / 1000000, ((100*progressvalue) / 40000)); } m_addedspeed+=ispeed; m_iaveragetrigger++; if (m_iaveragetrigger > 120) { iaverage = m_addedspeed / m_iaveragetrigger; m_addedspeed = 0; m_iaveragetrigger = 0; ZeroMemory (szAverage, SIZE_STRING); if (iaverage > 0 && iaverage <= 1000) { if ((((ltotalbytes-ltotalbytesprocessed) / iaverage) / 60) == 0) { sprintf_s (szAverage, " Average Speed: %i Bytes/sec Time Remaining: Less than a minute", iaverage); } else { sprintf_s (szAverage, " Average Speed: %i Bytes/sec Time Remaining: %i mins", iaverage, ((ltotalbytes-ltotalbytesprocessed) / iaverage) / 60); } } if (iaverage > 1000 && iaverage <= 1000000) { if ((((ltotalbytes-ltotalbytesprocessed) / iaverage) / 60) == 0) { sprintf_s (szAverage, " Average Speed: %i KB/sec Time Remaining: Less than a minute", iaverage / 1000); } else { sprintf_s (szAverage, " Average Speed: %i KB/sec Time Remaining: %i mins", iaverage / 1000, ((ltotalbytes-ltotalbytesprocessed) / iaverage) / 60); } } if (iaverage > 1000000) { if ((((ltotalbytes-ltotalbytesprocessed) / iaverage) / 60) == 0) { sprintf_s (szAverage, " Average Speed: %i MB/sec Time Remaining: Less than a minute", iaverage / 1000000); } else { sprintf_s (szAverage, " Average Speed: %i MB/sec Time Remaining: %i mins", iaverage / 1000000, ((ltotalbytes-ltotalbytesprocessed) / iaverage) / 60); } } ZeroMemory (m_szLastaverage, SIZE_STRING); strcpy_s (m_szLastaverage, SIZE_STRING, szAverage); } strcat_s (szSpeed, SIZE_STRING, m_szLastaverage); SetDlgItemText (m_hwndspeed, ID_LBLSPEED, szSpeed); } else { //SetDlgItemText (m_hwndspeed, ID_LBLSPEED, "Calculating speed..."); } m_lastbytesreading = ltotalbytesprocessed; m_lasttimereading = ltimereading; } if(ferror(hDestination)) { //MyHandleError("Error writing ciphertext."); return false; } } while(!feof(hSource)); //------------------------------------------------------------------- // End the do loop when the last block of the source file has been // read, encrypted, and written to the destination file. //------------------------------------------------------------------- // Close files. //SendMessage (m_hwndprogress, PBM_SETPOS, 40000, 0L); if(hSource) { if(fclose(hSource)) { MyHandleError("Error closing source file"); return false; } } if(hDestination) { if(fclose(hDestination)) { MyHandleError("Error closing destination file"); return false; } } //------------------------------------------------------------------- // Free memory. if(pbBuffer) { free(pbBuffer); } //------------------------------------------------------------------- // Destroy the session key. if(hKey) { if(!(CryptDestroyKey(hKey))) { MyHandleError("Error during CryptDestroyKey"); return false; } } //------------------------------------------------------------------- // Release the provider handle. if(hCryptProv) { if(!(CryptReleaseContext(hCryptProv, 0))) { MyHandleError("Error during CryptReleaseContext"); return false; } } return true; } // end Encryptfile