How can I calculate in c++ windows kernel driver a HASH like MD5 or SHA256 for a file from the system ?

Iosif Daniel Kurazs 26 Reputation points
2023-02-23T14:08:15.7733333+00:00

I'm working on a windows kernel driver minifilter which needs to calculate some kind of CRC for a file path received.

I was searching the web and the only thing I found was how to do that from a windows UMD or app.

I'm looking to see if there is any provided system API for this, that is still hidden, I wouldn't want to implement my own.

Windows for business | Windows Client for IT Pros | Devices and deployment | Other
Windows for business | Windows Client for IT Pros | User experience | Other
Developer technologies | C++
{count} votes

Accepted answer
  1. Limitless Technology 44,766 Reputation points
    2023-02-24T14:20:14.37+00:00
    
    Hi. Thank you for your question and reaching out. I’d be more than happy to help you with your query
    
    You can try this code below:
    
    // Get a handle to the file
    HANDLE hFile = CreateFile("your_file_path", GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    
    // Create a SHA256 hash object
    HCRYPTPROV hProv = NULL;
    HCRYPTHASH hHash = NULL;
    if (!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_AES, 0))
        return;
    if (!CryptCreateHash(hProv, CALG_SHA_256, 0, 0, &hHash))
        return;
    
    // Read the file and add the data to the hash object
    BYTE buffer[1024];
    DWORD dwRead = 0;
    while(ReadFile(hFile, buffer, 1024, &dwRead, NULL))
    {
        if (dwRead == 0)
            break;
        if (!CryptHashData(hHash, buffer, dwRead, 0))
            return;
    }
    
    // Get the hash value
    DWORD dwHashLen = 32;
    BYTE hashValue[32];
    if (!CryptGetHashParam(hHash, HP_HASHVAL, hashValue, &dwHashLen, 0))
        return;
    
    // Clean up
    CryptDestroyHash(hHash);
    CryptReleaseContext(hProv, 0);
    
    If the reply was helpful, please don’t forget to upvote or accept as answer, thank you.
    
    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Limitless Technology 44,766 Reputation points
    2023-02-24T14:20:22.9366667+00:00

    Double post

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.