Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <windows.h>
- #include <Wincrypt.h>
- #include "mspyLog.h"
- #define BUFSIZE 1024
- #define MD5LEN 16
- DWORD hash(FILE* fp, WCHAR filename[])
- {
- DWORD dwStatus = 0;
- BOOL bResult = FALSE;
- HCRYPTPROV hProv = 0;
- HCRYPTHASH hHash = 0;
- HANDLE hFile = NULL;
- BYTE rgbFile[BUFSIZE];
- DWORD cbRead = 0;
- BYTE rgbHash[MD5LEN];
- DWORD cbHash = 0;
- CHAR rgbDigits[] = "0123456789abcdef";
- //LPCWSTR filename = L"filename.txt";
- // Logic to check usage goes here.
- fprintf(fp, "calculate %s\n", filename);
- hFile = CreateFileW(filename,
- GENERIC_READ,
- FILE_SHARE_READ,
- NULL,
- OPEN_EXISTING,
- FILE_FLAG_SEQUENTIAL_SCAN,
- NULL);
- if (INVALID_HANDLE_VALUE == hFile)
- {
- dwStatus = GetLastError();
- fprintf(fp, "Error opening file %s\nError: %d\n", filename,
- dwStatus);
- return dwStatus;
- }
- fwprintf(fp, L"Correct open: %d\n", filename,
- dwStatus);
- // Get handle to the crypto provider
- if (!CryptAcquireContext(&hProv,
- NULL,
- NULL,
- PROV_RSA_FULL,
- CRYPT_VERIFYCONTEXT))
- {
- dwStatus = GetLastError();
- printf("CryptAcquireContext failed: %d\n", dwStatus);
- CloseHandle(hFile);
- return dwStatus;
- }
- if (!CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash))
- {
- dwStatus = GetLastError();
- printf("CryptAcquireContext failed: %d\n", dwStatus);
- CloseHandle(hFile);
- CryptReleaseContext(hProv, 0);
- return dwStatus;
- }
- bResult = ReadFile(hFile, rgbFile, BUFSIZE,
- &cbRead, NULL);
- while (bResult)
- {
- if (0 == cbRead)
- {
- break;
- }
- if (!CryptHashData(hHash, rgbFile, cbRead, 0))
- {
- dwStatus = GetLastError();
- printf("CryptHashData failed: %d\n", dwStatus);
- CryptReleaseContext(hProv, 0);
- CryptDestroyHash(hHash);
- CloseHandle(hFile);
- return dwStatus;
- }
- }
- if (!bResult)
- {
- dwStatus = GetLastError();
- printf("ReadFile failed: %d\n", dwStatus);
- CryptReleaseContext(hProv, 0);
- CryptDestroyHash(hHash);
- CloseHandle(hFile);
- return dwStatus;
- }
- cbHash = MD5LEN;
- if (CryptGetHashParam(hHash, HP_HASHVAL, rgbHash, &cbHash, 0))
- {
- fprintf(fp, "MD5 hash of file %s is: ", filename);
- for (DWORD i = 0; i < cbHash; i++)
- {
- fprintf(fp, "%c%c", rgbDigits[rgbHash[i] >> 4],
- rgbDigits[rgbHash[i] & 0xf]);
- }
- fprintf(fp, "\n");
- }
- else
- {
- dwStatus = GetLastError();
- printf("CryptGetHashParam failed: %d\n", dwStatus);
- }
- CryptDestroyHash(hHash);
- CryptReleaseContext(hProv, 0);
- CloseHandle(hFile);
- return dwStatus;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement