C语言 使用Cryptdll计算文件md5值

typedef struct {
    ULONG i[2];
    ULONG buf[4];
    unsigned char in[64];
    unsigned char digest[16];
} MD5_CTX;

//定义函数指针
typedef void (WINAPI* PMD5Init)(MD5_CTX* context);
typedef void (WINAPI* PMD5Final)(MD5_CTX* context);
typedef void (WINAPI* PMD5Update)(MD5_CTX* context, const unsigned char* input, unsigned int inlen);

void GetFileMD5(CString fileName, LPWSTR strBuf)
{ 

    FILE* ff;
    unsigned long nSize = 1024;
    char* rBuff = (char*)malloc(sizeof(char) * nSize);
    unsigned long rCount = 0;
    MD5_CTX context;

    //加载微软提供MD5计算的dll文件
    HMODULE hdll = LoadLibrary(L"Cryptdll.dll");
    PMD5Init m_pFuncMD5Init = NULL;
    PMD5Final m_pFuncMD5Final = NULL;
    PMD5Update m_pFuncMD5Update = NULL;

    if (hdll == NULL)
    {
        printf("load dll Cryptdll faild\n");
        exit(1);
    }
    //获得相应的函数地址
    m_pFuncMD5Init = (PMD5Init)GetProcAddress(hdll, "MD5Init");
    m_pFuncMD5Final = (PMD5Final)GetProcAddress(hdll, "MD5Final");
    m_pFuncMD5Update = (PMD5Update)GetProcAddress(hdll, "MD5Update");

    if (!(m_pFuncMD5Update && m_pFuncMD5Init && m_pFuncMD5Final))
    {
        FreeLibrary(hdll);
        printf("get function faild\n");
        exit(2);
    }

    //初始化context
    ZeroMemory(&context, sizeof(MD5_CTX));
    m_pFuncMD5Init(&context);

    //打开一个测试文件
    if (!(ff = _wfopen(fileName, L"rb")))
    {
        printf("open file faild\n");
        exit(3);
    }


    while (rCount = fread(rBuff, sizeof(char), nSize, ff))
    {
        m_pFuncMD5Update(&context, (const unsigned char*)rBuff, rCount);
    }
    m_pFuncMD5Final(&context);
    //此处下断点,调试状态从Watch中查看cnotext.digest域为文件MD5值


    //for (int i = 0; i < 16; i++)
    //{
    //    printf("%X", context.digest[i]);
    //}

    WCHAR pbuf[32];

    for (int i = 0; i < 16; i++)
    {
        swprintf(pbuf, 32, L"%02X", context.digest[i]);
        //sprintf(pbuf, "%X", context.digest[i]);
        wcsncat(strBuf, pbuf, 33);
        //wcsncat_s(strBuf, 32, pbuf, 2);

    }

    //printf("%s", strBuf);
    fclose(ff);
    free(rBuff);
}

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页