2012年7月5日星期四

IoRegisterFsRegistrationChange.C


/*
IoRegisterFsRegistrationChange这个函数,大多数人都知道.
在文件过滤驱动中大多用到,也都知道字面的意思.
本人笨拙,要刨根问底,进一步知晓,只有我编写代码,调试并查看效果,我才算掌握这个函数.
与其说回调,不如说:在一般的情况下是枚举(文件系统相关的).这是不正确但形象的说明.
这个函数费了我半天的时间.
*/

//#include <ntddk.h>
#include <Ntifs.h>

VOID DriverNotificationRoutine(__in PDEVICE_OBJECT DeviceObject,__in BOOLEAN FsActive)
{
    if (FsActive) 
    {
        DbgPrint("/////////////////////////////////////////////////////////////////////////\n");
        DbgPrint("the file system has registered\n"); //\n后面不能有空格,不然会蓝屏.
        DbgPrint("本设备对象所在的驱动对象的驱动名字:%wZ \n",&DeviceObject->DriverObject->DriverName);//\FileSystem\Fs_Rec重复出现好几次.
        if(DeviceObject->NextDevice) //不判断会蓝屏.因为有的没有.
        {
            DbgPrint("本设备对象的下一个设备对象的驱动对象的驱动名字:%wZ \n",&DeviceObject->NextDevice->DriverObject->DriverName);
        }
        if (DeviceObject->AttachedDevice)
        {
            DbgPrint("本设备对象的附加设备对象的所在驱动的驱动的名字:%wZ \n",&DeviceObject->AttachedDevice->DriverObject->DriverName);
        }

        //这个和第一个显示的是一样的.就是:&DeviceObject->DriverObject->DriverName,注释掉,不显示了.
        //DbgPrint("本设备对象的扩展信息中的驱动对象的驱动名字:%wZ \n",&DeviceObject->DeviceObjectExtension->DeviceObject->DriverObject->DriverName);
    } 
    else 
    { 
        DbgPrint("the file system has unregistered\n"); 
    }
}

VOID Unload(PDRIVER_OBJECT DriverObject)
{
    IoUnregisterFsRegistrationChange(DriverObject, DriverNotificationRoutine);
}

NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING pRegistryPath)
{
    _asm int 3
    DriverObject->DriverUnload = Unload; 
    IoRegisterFsRegistrationChange(DriverObject, DriverNotificationRoutine);     

    return STATUS_SUCCESS;
}
//made at 2012.06.29

SystemModuleInformation.C


/*
ZwQuerySystemInformation这个函数在应用层也可以使用,功能十分强大,以前是未公开的,现在是半公开的,因为内核中没有这个函数的声明.
本文修改自kmdkit的第六篇教程.以前把c/c++改为asm,现在是把asm改为c/c++.
看似简单的一个事情,费了我一天的时间.
win 7 32测试通过.
made at 2012.06.23
*/

#include <ntddk.h>

//下面的结构摘自:http://undocumented.ntinternals.net/UserMode/Undocumented%20Functions/System%20Information/SYSTEM_INFORMATION_CLASS.html
typedef enum _SYSTEM_INFORMATION_CLASS {
    SystemBasicInformation,
    SystemProcessorInformation,
    SystemPerformanceInformation,
    SystemTimeOfDayInformation,
    SystemPathInformation,
    SystemProcessInformation,
    SystemCallCountInformation,
    SystemDeviceInformation,
    SystemProcessorPerformanceInformation,
    SystemFlagsInformation,
    SystemCallTimeInformation,
    SystemModuleInformation,
    SystemLocksInformation,
    SystemStackTraceInformation,
    SystemPagedPoolInformation,
    SystemNonPagedPoolInformation,
    SystemHandleInformation,
    SystemObjectInformation,
    SystemPageFileInformation,
    SystemVdmInstemulInformation,
    SystemVdmBopInformation,
    SystemFileCacheInformation,
    SystemPoolTagInformation,
    SystemInterruptInformation,
    SystemDpcBehaviorInformation,
    SystemFullMemoryInformation,
    SystemLoadGdiDriverInformation,
    SystemUnloadGdiDriverInformation,
    SystemTimeAdjustmentInformation,
    SystemSummaryMemoryInformation,
    SystemNextEventIdInformation,
    SystemEventIdsInformation,
    SystemCrashDumpInformation,
    SystemExceptionInformation,
    SystemCrashDumpStateInformation,
    SystemKernelDebuggerInformation,
    SystemContextSwitchInformation,
    SystemRegistryQuotaInformation,
    SystemExtendServiceTableInformation,
    SystemPrioritySeperation,
    SystemPlugPlayBusInformation,
    SystemDockInformation,
    SystemPowerInformation1,//提示重复定义,后面加一个1.
    SystemProcessorSpeedInformation,
    SystemCurrentTimeZoneInformation,
    SystemLookasideInformation
} SYSTEM_INFORMATION_CLASS, *PSYSTEM_INFORMATION_CLASS;

//摘自微软:http://msdn.microsoft.com/en-us/library/windows/desktop/ms725506(v=vs.85).aspx
//NTSTATUS NTAPI ZwQuerySystemInformation( //WINAPI改为NTAPI或者去掉编译没有问题.
//    __in       SYSTEM_INFORMATION_CLASS SystemInformationClass,
//    __inout    PVOID SystemInformation,
//    __in       ULONG SystemInformationLength,
//    __out_opt  PULONG ReturnLength
//    );

//下面的摘自:http://undocumented.ntinternals.net/UserMode/Undocumented%20Functions/System%20Information/NtQuerySystemInformation.html
NTSYSAPI 
NTSTATUS
NTAPI
ZwQuerySystemInformation(//把Nt修改为Zw.
                         IN SYSTEM_INFORMATION_CLASS SystemInformationClass,
                         OUT PVOID               SystemInformation,
                         IN ULONG                SystemInformationLength,
                         OUT PULONG              ReturnLength OPTIONAL );

//未公开的结构,搜索自网络:http://alter.org.ua/docs/nt_kernel/procaddr/#samples, kmdkit也有.
//与http://undocumented.ntinternals.net/UserMode/Structures/SYSTEM_MODULE_INFORMATION.html的不同.
//typedef struct _SYSTEM_MODULE_INFORMATION {
//    ULONG                ModulesCount;
//    SYSTEM_MODULE        Modules[0];
//} SYSTEM_MODULE_INFORMATION, *PSYSTEM_MODULE_INFORMATION;
typedef struct SYSTEM_MODULE_INFORMATION {
    ULONG Reserved[2];
    PVOID Base;
    ULONG Size;
    ULONG Flags;
    USHORT Index;
    USHORT Unknown;
    USHORT LoadCount;
    USHORT ModuleNameOffset;
    CHAR ImageName[256];
} SYSTEM_MODULE_INFORMATION, *PSYSTEM_MODULE_INFORMATION;

VOID Unload(PDRIVER_OBJECT DriverObject){}

NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING pRegistryPath)
{
    ULONG cb = 0;
    PSYSTEM_MODULE_INFORMATION p;
    PVOID p0;
    int dwNumModules;
    int i;
    LPSTR name;

    _asm int 3

    DriverObject->DriverUnload = Unload;  //写在前面是确保顺利卸载.

    ZwQuerySystemInformation(11,& p, 0, & cb);//#define SystemModuleInformation 11
    if (cb == 0) return 0;

    p = (PSYSTEM_MODULE_INFORMATION)ExAllocatePool( PagedPool, cb);
    if (p == 0) return 0;
    p0 = (PVOID)p;//这两个变量定义的别扭,但可以使用.

    if (ZwQuerySystemInformation(11, p, cb, & cb) != 0)
    {
        ExFreePool( p);
        return 0;
    }

    dwNumModules = *(int *) p;

    (int *) p += 1;//指针加4个字节.

    for (i = 0;i<dwNumModules;i++)
    {
        name = (LPSTR)(p->ImageName + p->ModuleNameOffset);

        if (_strnicmp(name,"ntoskrnl.exe",strlen("ntoskrnl.exe")) == 0)
        {//If your system has PAE - "ntkrnlpa.exe"
            DbgPrint("%s base: %08X size: %08X\n",name,p->Base,p->Size);
        }

        if (_strnicmp(name,"ntkrnlpa.exe",strlen("ntkrnlpa.exe")) == 0)
        {//; If you have multiprocessor system use "ntkrnlmp.exe".
            DbgPrint("%s base: %08X size: %08X\n",name,p->Base,p->Size);
        }

        if (_strnicmp(name,"ntkrpamp.exe",strlen("ntkrpamp.exe")) == 0)
        {//Multiprocessor + PAE - "ntkrpamp.exe"
            DbgPrint("%s base: %08X size: %08X\n",name,p->Base,p->Size);
        }

        //ntice.sys,不知道啥玩意,不显示了.

        DbgPrint("%s base: %08X size: %08X\n",name,p->Base,p->Size);//我要看看全部的是啥玩意.

        (unsigned char *)p += sizeof (SYSTEM_MODULE_INFORMATION);
    }

    ExFreePool( p0);

return STATUS_SUCCESS;
    //返回STATUS_DEVICE_CONFIGURATION_ERROR,也加载成功,也不需要卸载函数了,也能再次加载.
}
//made by correy

\\KnownDlls\\KnownDllPath.C

/*
本文整理自网络,
起源于WinObjEx.exe的无聊的使用.
大家都知道如何获取:%windir% = %SystemRoot%
今天的是获取:%WINDIR%\system32,注意获得的路径的后面是不带\的.
注释:%system%在2003和win 7上是无效的,别的没有测试.

注意还有个路径:L"\\KnownDlls\\KnownDllPath",这个只存在于64位的系统。
*/

#include <ntddk.h>

VOID OnUnload(PDRIVER_OBJECT DriverObject){}

NTSTATUS DriverEntry(__in PDRIVER_OBJECT pDriverObject,__in PUNICODE_STRING pRegistryPath)
{//方法一:
    ULONG ActualLength;
    HANDLE LinkHandle;
    WCHAR NameBuffer[128];//这个可能定义的小了.
    OBJECT_ATTRIBUTES ObjectAttributes;
    UNICODE_STRING LinkString, NameString;

    _asm int 3

    LinkString.Buffer = NameBuffer;
    LinkString.MaximumLength = sizeof(NameBuffer);
    RtlZeroMemory(NameBuffer, sizeof(NameBuffer));
    RtlInitUnicodeString(&NameString, L"\\KnownDlls\\KnownDllPath");//不可以用//,不然会ZwOpenSymbolicLinkObject调用失败.就是得到的句柄为0.
    InitializeObjectAttributes(&ObjectAttributes, &NameString, OBJ_KERNEL_HANDLE, NULL, NULL);
    ZwOpenSymbolicLinkObject(&LinkHandle, SYMBOLIC_LINK_QUERY, &ObjectAttributes);
    ZwQuerySymbolicLinkObject(LinkHandle, &LinkString, &ActualLength);//LinkString就是想要的值.
    KdPrint(("KnownDllPath: %wZ \n",&LinkString));
    ZwClose(LinkHandle);
    ////////////////////////////////////////////////////////////////////////////////////////////////////////
    //方法二:
    {
        NTSTATUS ZwOpenDirectoryObject(
            __out  PHANDLE DirectoryHandle,
            __in   ACCESS_MASK DesiredAccess,
            __in   POBJECT_ATTRIBUTES ObjectAttributes);

        UNICODE_STRING usDirName,usSymbolicName,usSymbolic;
        OBJECT_ATTRIBUTES ObjDir,ObjSymbolic;
        WCHAR wchBuffer[128];
        HANDLE hDir,hSymbolic;

        RtlInitUnicodeString (&usDirName,L"\\KnownDlls");
        InitializeObjectAttributes( &ObjDir,&usDirName,OBJ_CASE_INSENSITIVE|OBJ_KERNEL_HANDLE,NULL,NULL);
        ZwOpenDirectoryObject ( &hDir,DIRECTORY_QUERY,&ObjDir);
        RtlInitUnicodeString (&usSymbolicName , L"KnownDllPath");
        InitializeObjectAttributes(&ObjSymbolic,&usSymbolicName,OBJ_CASE_INSENSITIVE|OBJ_KERNEL_HANDLE,hDir,NULL);
        ZwOpenSymbolicLinkObject (&hSymbolic,GENERIC_READ,&ObjSymbolic);
        usSymbolic.Buffer = wchBuffer;
        usSymbolic.MaximumLength = 256*sizeof(WCHAR);
        usSymbolic.Length =0;
        ZwQuerySymbolicLinkObject ( hSymbolic,&usSymbolic,NULL);
        KdPrint(("KnownDllPath: %wZ \n",&usSymbolic));
    }  

    pDriverObject->DriverUnload = OnUnload; 
    return 0;
}
//made by correy

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
在驱动中把dos-name转换nt-name.
made at 20140605.
*/

#include <ntifs.h>
#include <windef.h>

#define TAG 'tset' //test


DRIVER_UNLOAD Unload;
VOID Unload(__in PDRIVER_OBJECT DriverObject)
{   
    
}


#pragma INITCODE
DRIVER_INITIALIZE DriverEntry;
NTSTATUS DriverEntry(__in struct _DRIVER_OBJECT * DriverObject, __in PUNICODE_STRING RegistryPath)
{
    ULONG ActualLength;
    HANDLE LinkHandle = 0;
    WCHAR NameBuffer[128];//这个可能定义的小了.
    OBJECT_ATTRIBUTES ObjectAttributes;
    UNICODE_STRING LinkString, NameString;
    NTSTATUS status = STATUS_SUCCESS;

    KdBreakPoint();

    DriverObject->DriverUnload = Unload; 

    LinkString.Buffer = NameBuffer;
    LinkString.MaximumLength = sizeof(NameBuffer);
    RtlZeroMemory(NameBuffer, sizeof(NameBuffer));

    RtlInitUnicodeString(&NameString, L"\\??\\c:");//注意格式。
    InitializeObjectAttributes(&ObjectAttributes, &NameString, OBJ_KERNEL_HANDLE, NULL, NULL);
    status = ZwOpenSymbolicLinkObject(&LinkHandle, SYMBOLIC_LINK_QUERY | GENERIC_READ , &ObjectAttributes);
    status = ZwQuerySymbolicLinkObject(LinkHandle, &LinkString, &ActualLength);
    KdPrint(("%wZ \n",&LinkString));//得到的值形如:"\Device\HarddiskVolume1"。
    ZwClose(LinkHandle);

    return 0;
} 

WinHttpReadData.Cpp


/*
以前接触网络的时候,认为用户层用socket足矣(其实还有比socket更底层的),别的都不用,这样停止了几年.
后来发现有一些操作,还是用高级的好.
这就知道了.WinINet和WinHTTP等.
好像WinHTTP是WinINet的子集(IWinHttpRequest又是WinHTTP的子集),但比WinINet效率高,还可以用于服务器.
以前也知道点,但没有具体深入.
前几天算是开始了,费了一个多月的时间才把下面的小问题搞定.

下面的代码来自:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa384104(v=vs.85).aspx
等.
并加一些注释.没有精简.

再说一下:
看似简单的几个函数,如果不深刻理解总是出错的.
原因在于示例程序可以运行,修改别的就不行了.

注意参数的设置:如端口,协议等.一定要配合.

下面的代码经过简单的修改,可以成功的访问:
www.microsoft.com
www.baidu.com 
www.google.com.hk 注释:访问www.google.com,得到的数据不是我们想要的,可能又转到了:www.google.com.hk
www.126.com
*/

#include <windows.h>
#include <Winhttp.h>
#pragma comment(lib, "Winhttp.lib")

void wmain(void)
{
    DWORD dwSize = 0;
    DWORD dwDownloaded = 0;
    LPSTR pszOutBuffer;
    BOOL  bResults = FALSE;
    HINTERNET  hSession = NULL, 
        hConnect = NULL,
        hRequest = NULL;

    // Use WinHttpOpen to obtain a session handle.
    hSession = WinHttpOpen( L"WinHTTP Example/1.0",  
        WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, //WINHTTP_ACCESS_TYPE_NO_PROXY  WINHTTP_ACCESS_TYPE_DEFAULT_PROXY
        WINHTTP_NO_PROXY_NAME, //#define WINHTTP_NO_PROXY_NAME     NULL
        WINHTTP_NO_PROXY_BYPASS, 0);//#define WINHTTP_NO_PROXY_BYPASS   NULL

    // Specify an HTTP server.
    if (hSession)
    {
        DWORD data;
        DWORD dwSize = sizeof(DWORD);

        WinHttpSetTimeouts( hSession, 60000000, 60000000, 60000000, 60000000);//我这台电脑上的原始值是:60000ms,设置大点,防止因为这个而出现错误.

        // Use WinHttpQueryOption to retrieve internet options.
        if (WinHttpQueryOption( hSession, 
            WINHTTP_OPTION_CONNECT_TIMEOUT, 
            &data, &dwSize))
        {
            printf("Connection timeout: %u ms\n\n",data); //60000ms
        }
        else
        {
            printf( "Error %u in WinHttpQueryOption.\n", 
                GetLastError());
        }        

        // When finished, release the HINTERNET handle.
        // WinHttpCloseHandle(hSession);
        //以上这几行代码也摘抄自msdn .

        hConnect = WinHttpConnect( hSession, L"correy.webs.com", //www.microsoft.com www.baidu.com www.google.com.hk 支持L"220.181.112.143"格式.不要加http://和https://
            INTERNET_DEFAULT_HTTP_PORT, 0); //INTERNET_DEFAULT_HTTP_PORT INTERNET_DEFAULT_HTTPS_PORT  //设置端口,注意要和协议匹配.
    }

    // Create an HTTP request handle.
    if (hConnect)
        hRequest = WinHttpOpenRequest( hConnect, L"GET", NULL,//可以改为"POST","HEAD".等.
        NULL, //Pointer to a string that contains the HTTP version. If this parameter is NULL, the function uses HTTP/1.1.
        WINHTTP_NO_REFERER, //还可以写具体的相对位置.如果没有,可以设置为WINHTTP_NO_REFERER
        WINHTTP_DEFAULT_ACCEPT_TYPES, //see Media Types defined by IANA at http://www.iana.org/assignments/media-types/.
        WINHTTP_FLAG_REFRESH);//WINHTTP_FLAG_REFRESH  WINHTTP_FLAG_SECURE 设置协议, 注意要和端口匹配.

    // Send a request.
    if (hRequest)
        bResults = WinHttpSendRequest( hRequest,//这个很费时间.
        WINHTTP_NO_ADDITIONAL_HEADERS,
        0, WINHTTP_NO_REQUEST_DATA, 0, 
        0, 0); //用GetLastError返回的错误码,结合函数说明在头文件里面查,msdn上也有的.
    int x = ERROR_WINHTTP_CANNOT_CONNECT; //goto definition用的.
    //具体的查看信息是:http://msdn.microsoft.com/en-us/library/windows/desktop/aa383770(v=vs.85).aspx

    // End the request.
    if (bResults)
        bResults = WinHttpReceiveResponse( hRequest, NULL); //ERROR_WINHTTP_CANNOT_CONNECT

    // Keep checking for data until there is nothing left.
    if (bResults)
    {
        do 
        {
            // Check for available data.
            dwSize = 0;
            if (!WinHttpQueryDataAvailable( hRequest, &dwSize)) 
            {
                printf( "Error %u in WinHttpQueryDataAvailable.\n",
                    GetLastError());
                break;
            }

            // No more available data.
            if (!dwSize)
                break;

            // Allocate space for the buffer.
            pszOutBuffer = new char[dwSize+1];
            if (!pszOutBuffer)
            {
                printf("Out of memory\n");
                break;
            }

            // Read the Data.
            ZeroMemory(pszOutBuffer, dwSize+1);

            if (!WinHttpReadData( hRequest, (LPVOID)pszOutBuffer, 
                dwSize, &dwDownloaded))
            {                                  
                printf( "Error %u in WinHttpReadData.\n", GetLastError());
            }
            else
            {
                printf("%s", pszOutBuffer);
            }

            // Free the memory allocated to the buffer.
            delete [] pszOutBuffer;

            // This condition should never be reached since WinHttpQueryDataAvailable
            // reported that there are bits to read.
            if (!dwDownloaded)
                break;

        } while (dwSize > 0);
    }
    else
    {
        // Report any errors.
        printf( "Error %d has occurred.\n", GetLastError() );
    }

    // Close any open handles.
    if (hRequest) WinHttpCloseHandle(hRequest);
    if (hConnect) WinHttpCloseHandle(hConnect);
    if (hSession) WinHttpCloseHandle(hSession);
}
//made by correy

minifilter.c


/*
最简单的minifilter.
修改自wdk的nullFilter.c.
安装的办法可以用.inf 
也可以编程操作注册表的办法,但我还没有实现.
*/
#include <fltKernel.h>
PFLT_FILTER FilterHandle;
NTSTATUS NullUnload (__in FLT_FILTER_UNLOAD_FLAGS Flags)
{ //这个也可以不要的.
    DbgPrint("minifilter stop");//方便net stop或者fltmc load或者sc stop查询.
    FltUnregisterFilter( FilterHandle );
    return STATUS_SUCCESS;
}
FLT_REGISTRATION FilterRegistration = {sizeof(FLT_REGISTRATION),FLT_REGISTRATION_VERSION,0,0,0,NullUnload,0,0,0,0,0,0,0};
NTSTATUS DriverEntry (__in PDRIVER_OBJECT DriverObject,__in PUNICODE_STRING RegistryPath)
{
    DbgPrint("minifilter entry");//方便net start或者fltmc unload或者sc stop查询.
    FltRegisterFilter( DriverObject,&FilterRegistration,&FilterHandle );
    FltStartFiltering( FilterHandle );
    return 0;
}
//made at 2012.05.20
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//下面的精简自wdk的passThrough.c
#include <fltKernel.h>
PFLT_FILTER gFilterHandle;
ULONG_PTR OperationStatusCtx = 1;
ULONG gTraceFlags = 1;
#define PT_DBG_PRINT( _dbgLevel, _string )          (FlagOn(gTraceFlags,(_dbgLevel)) ?  DbgPrint _string :  ((int)0))
VOID PtOperationStatusCallback (__in PCFLT_RELATED_OBJECTS FltObjects,__in PFLT_IO_PARAMETER_BLOCK ParameterSnapshot,__in NTSTATUS OperationStatus,__in PVOID RequesterContext)
{
    PT_DBG_PRINT( 1,("PassThrough!PtOperationStatusCallback: Entered\n") );
    PT_DBG_PRINT( 2,("PassThrough!PtOperationStatusCallback: Status=%08x ctx=%p IrpMj=%02x.%02x \"%s\"\n",
        OperationStatus,RequesterContext,ParameterSnapshot->MajorFunction,ParameterSnapshot->MinorFunction,
        FltGetIrpName(ParameterSnapshot->MajorFunction)) );
}
BOOLEAN PtDoRequestOperationStatus(__in PFLT_CALLBACK_DATA Data)
{
    PFLT_IO_PARAMETER_BLOCK iopb = Data->Iopb;
    return (BOOLEAN)(((iopb->MajorFunction == IRP_MJ_FILE_SYSTEM_CONTROL) &&
        ((iopb->Parameters.FileSystemControl.Common.FsControlCode == FSCTL_REQUEST_FILTER_OPLOCK)  ||
        (iopb->Parameters.FileSystemControl.Common.FsControlCode == FSCTL_REQUEST_BATCH_OPLOCK)   ||
        (iopb->Parameters.FileSystemControl.Common.FsControlCode == FSCTL_REQUEST_OPLOCK_LEVEL_1) ||
        (iopb->Parameters.FileSystemControl.Common.FsControlCode == FSCTL_REQUEST_OPLOCK_LEVEL_2))) ||
        ((iopb->MajorFunction == IRP_MJ_DIRECTORY_CONTROL) && (iopb->MinorFunction == IRP_MN_NOTIFY_CHANGE_DIRECTORY)));
}
FLT_PREOP_CALLBACK_STATUS PtPreOperationPassThrough (__inout PFLT_CALLBACK_DATA Data,__in PCFLT_RELATED_OBJECTS FltObjects,__deref_out_opt PVOID *CompletionContext)
{
    NTSTATUS status;
    PT_DBG_PRINT( 1,("PassThrough!PtPreOperationPassThrough: Entered\n") );
    if (PtDoRequestOperationStatus( Data )) 
    {
        status = FltRequestOperationStatusCallback( Data,PtOperationStatusCallback,(PVOID)(++OperationStatusCtx) );
        if (!NT_SUCCESS(status)) 
        {
            PT_DBG_PRINT( 2,("PassThrough!PtPreOperationPassThrough: FltRequestOperationStatusCallback Failed, status=%08x\n",status) );
        }
    }
    return FLT_PREOP_SUCCESS_WITH_CALLBACK;
}
FLT_POSTOP_CALLBACK_STATUS PtPostOperationPassThrough (__inout PFLT_CALLBACK_DATA Data,__in PCFLT_RELATED_OBJECTS FltObjects,
                                                       __in_opt PVOID CompletionContext,__in FLT_POST_OPERATION_FLAGS Flags)
{
    PT_DBG_PRINT( 1,("PassThrough!PtPostOperationPassThrough: Entered\n") );
    return FLT_POSTOP_FINISHED_PROCESSING;
}
FLT_PREOP_CALLBACK_STATUS PtPreOperationNoPostOperationPassThrough (__inout PFLT_CALLBACK_DATA Data,__in PCFLT_RELATED_OBJECTS FltObjects,__deref_out_opt PVOID *CompletionContext)
{
    PT_DBG_PRINT( 1,("PassThrough!PtPreOperationNoPostOperationPassThrough: Entered\n") );
    return FLT_PREOP_SUCCESS_NO_CALLBACK;
}
CONST FLT_OPERATION_REGISTRATION Callbacks[] = {//用编程的办法,实现,只有一处是特殊的.
    { IRP_MJ_CREATE, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_CREATE_NAMED_PIPE, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_CLOSE, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_READ, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_WRITE, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_QUERY_INFORMATION, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_SET_INFORMATION, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_QUERY_EA, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_SET_EA, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_FLUSH_BUFFERS, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_QUERY_VOLUME_INFORMATION, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_SET_VOLUME_INFORMATION, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_DIRECTORY_CONTROL, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_FILE_SYSTEM_CONTROL, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_DEVICE_CONTROL, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_INTERNAL_DEVICE_CONTROL, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_SHUTDOWN, 0, PtPreOperationNoPostOperationPassThrough, NULL },   //post operations not supported
    { IRP_MJ_LOCK_CONTROL, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_CLEANUP, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_CREATE_MAILSLOT, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_QUERY_SECURITY, 0, PtPreOperationPassThrough,  PtPostOperationPassThrough },
    { IRP_MJ_SET_SECURITY, 0, PtPreOperationPassThrough,  PtPostOperationPassThrough },
    { IRP_MJ_QUERY_QUOTA, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_SET_QUOTA, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_PNP, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_ACQUIRE_FOR_SECTION_SYNCHRONIZATION, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_RELEASE_FOR_SECTION_SYNCHRONIZATION, 0, PtPreOperationPassThrough,  PtPostOperationPassThrough },
    { IRP_MJ_ACQUIRE_FOR_MOD_WRITE, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_RELEASE_FOR_MOD_WRITE, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_ACQUIRE_FOR_CC_FLUSH, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_RELEASE_FOR_CC_FLUSH, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_FAST_IO_CHECK_IF_POSSIBLE, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_NETWORK_QUERY_OPEN, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_MDL_READ, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_MDL_READ_COMPLETE, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_PREPARE_MDL_WRITE, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_MDL_WRITE_COMPLETE, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_VOLUME_MOUNT, 0, PtPreOperationPassThrough,  PtPostOperationPassThrough },
    { IRP_MJ_VOLUME_DISMOUNT, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
    { IRP_MJ_OPERATION_END }
};
#pragma PAGEDCODE
NTSTATUS PtInstanceSetup (__in PCFLT_RELATED_OBJECTS FltObjects,__in FLT_INSTANCE_SETUP_FLAGS Flags,__in DEVICE_TYPE VolumeDeviceType,__in FLT_FILESYSTEM_TYPE VolumeFilesystemType)
{
    PT_DBG_PRINT( 1,("PassThrough!PtInstanceSetup: Entered\n") );
    return STATUS_SUCCESS;
}
#pragma PAGEDCODE
NTSTATUS PtInstanceQueryTeardown (__in PCFLT_RELATED_OBJECTS FltObjects,__in FLT_INSTANCE_QUERY_TEARDOWN_FLAGS Flags)
{
    PT_DBG_PRINT( 1,("PassThrough!PtInstanceQueryTeardown: Entered\n") );
    return STATUS_SUCCESS;
}
#pragma PAGEDCODE
VOID PtInstanceTeardownStart (__in PCFLT_RELATED_OBJECTS FltObjects,__in FLT_INSTANCE_TEARDOWN_FLAGS Flags)
{
    PT_DBG_PRINT( 1, ("PassThrough!PtInstanceTeardownStart: Entered\n") );
}
#pragma PAGEDCODE
VOID PtInstanceTeardownComplete (__in PCFLT_RELATED_OBJECTS FltObjects,__in FLT_INSTANCE_TEARDOWN_FLAGS Flags)
{
    PT_DBG_PRINT( 1,("PassThrough!PtInstanceTeardownComplete: Entered\n") );
}
#pragma PAGEDCODE
NTSTATUS PtUnload (__in FLT_FILTER_UNLOAD_FLAGS Flags)
{
    PT_DBG_PRINT( 1,("PassThrough!PtUnload: Entered\n") );
    FltUnregisterFilter( gFilterHandle );
    return STATUS_SUCCESS;
}
CONST FLT_REGISTRATION FilterRegistration = {
    sizeof( FLT_REGISTRATION ),         //  Size
    FLT_REGISTRATION_VERSION,           //  Version
    0,                                  //  Flags
    NULL,                               //  Context
    Callbacks,                          //  Operation callbacks
    PtUnload,                           //  MiniFilterUnload
    PtInstanceSetup,                    //  InstanceSetup
    PtInstanceQueryTeardown,            //  InstanceQueryTeardown
    PtInstanceTeardownStart,            //  InstanceTeardownStart
    PtInstanceTeardownComplete,         //  InstanceTeardownComplete
    NULL,                               //  GenerateFileName
    NULL,                               //  GenerateDestinationFileName
    NULL                                //  NormalizeNameComponent
};
#pragma INITCODE
NTSTATUS DriverEntry (__in PDRIVER_OBJECT DriverObject,__in PUNICODE_STRING RegistryPath)
{
    PT_DBG_PRINT( 1,("PassThrough!DriverEntry: Entered\n") );
    FltRegisterFilter( DriverObject, &FilterRegistration,&gFilterHandle );
    FltStartFiltering( gFilterHandle );
    return 0;
}
//made by correy

WinVerifyTrust.Cpp


/*
检查一个pe文件是不是一个有效的数字签名。
开始以为用检查pe文件结构的办法就能实现,可是这个办法不全面,易出错。
还是用这个方便,安全。
本文修改自msdn.
*/

#include <windows.h>
#include <Softpub.h>
#pragma comment (lib, "wintrust")

BOOL VerifyEmbeddedSignature(LPCWSTR pwszSourceFile)
{
    WINTRUST_FILE_INFO FileData;
    memset(&FileData, 0, sizeof(FileData));
    FileData.cbStruct = sizeof(WINTRUST_FILE_INFO);
    FileData.pcwszFilePath = pwszSourceFile;
    FileData.hFile = NULL;
    FileData.pgKnownSubject = NULL;    

    WINTRUST_DATA WinTrustData;
    memset(&WinTrustData, 0, sizeof(WinTrustData));
    WinTrustData.cbStruct = sizeof(WinTrustData);    
    WinTrustData.pPolicyCallbackData = NULL;// Use default code signing EKU.    
    WinTrustData.pSIPClientData = NULL;// No data to pass to SIP.   
    WinTrustData.dwUIChoice = WTD_UI_NONE;// Disable WVT UI.    
    WinTrustData.fdwRevocationChecks = WTD_REVOKE_NONE; // No revocation checking.    
    WinTrustData.dwUnionChoice = WTD_CHOICE_FILE;// Verify an embedded signature on a file.    
    WinTrustData.dwStateAction = 0;// Default verification.    
    WinTrustData.hWVTStateData = NULL;// Not applicable for default verification of embedded signature.    
    WinTrustData.pwszURLReference = NULL;// Not used.
    WinTrustData.dwUIContext = 0;    
    WinTrustData.pFile = &FileData;// Set pFile.

    GUID WVTPolicyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2;
    LONG lStatus = WinVerifyTrust(NULL,&WVTPolicyGUID,&WinTrustData);// 真正的开始.
    if (ERROR_SUCCESS == lStatus)
    {
        MessageBox(0,L"The file you selected is signed and the signature was verified.",0,0);
    }
    else 
    {
        MessageBox(0,L"其他的众多的失败之一",0,0);
        return false;
    }

    return true;
}

int _tmain(int argc, _TCHAR* argv[])
{
    VerifyEmbeddedSignature(L"E:\\signature\\exe.exe");
    return 0;
}

用户层链表操作

/*
以前知道,要用链表需要自己定义结构,自己操作。
简便和复杂的方法有stl里面的list。
以后发现驱动里面有操作双链表的函数,
又发现用户层也有操作单链表函数(xp开始)。
好像这些操作都是在链表的末尾(头部)插入/删除,能否在中间(或者指定的位置)插入呢/删除?可以参考我写的用驱动(API)操作链表的思路.

本程序修改自msdn,只使用于SLIST_ENTRY是结构的第一个成员的,若要用于别的可以调整代码。
*/
#include <windows.h>

typedef struct _PROGRAM_ITEM {
    SLIST_ENTRY ItemEntry;
    ULONG Signature;
} PROGRAM_ITEM, *PPROGRAM_ITEM;

int main( )
{
    PSLIST_HEADER pListHead = (PSLIST_HEADER)_aligned_malloc(sizeof(SLIST_HEADER),MEMORY_ALLOCATION_ALIGNMENT);//crt函数
    InitializeSListHead(pListHead);//结构清零而已,注意这个结构的第一个成员是:Alignment。

    for(ULONG Count = 1; Count <= 10; Count += 1 )
    {
        PPROGRAM_ITEM pProgramItem;//好像是临时的成员变量。
        pProgramItem = (PPROGRAM_ITEM)_aligned_malloc(sizeof(PROGRAM_ITEM),MEMORY_ALLOCATION_ALIGNMENT);
        pProgramItem->Signature = Count;

        PSLIST_ENTRY pFirstEntry = InterlockedPushEntrySList(pListHead, &(pProgramItem->ItemEntry)); //插入到pListHead的头部,被插入的是后面的。
    }

    for(ULONG Count = 10; Count >= 1; Count -= 1 )
    {
        PSLIST_ENTRY pListEntry = InterlockedPopEntrySList(pListHead);//从头移除
        if( NULL == pListEntry )  return -1;

        PPROGRAM_ITEM pProgramItem;//好像是临时的成员变量。
        pProgramItem = (PPROGRAM_ITEM)pListEntry;
        printf("Signature is %d\n", pProgramItem->Signature);

        _aligned_free(pListEntry);//crt函数。
    }

    PSLIST_ENTRY pListEntry = InterlockedFlushSList(pListHead);
    PSLIST_ENTRY pFirstEntry = InterlockedPopEntrySList(pListHead);
    if (pFirstEntry != NULL)    return -1;

    _aligned_free(pListHead);
    return 1;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//改进的如下:
//加入了遍历的功能,最好加上临界区以支持多线程安全的访问.

/*
made by correy
made at 0:25 2014/2/16
email:kouleguan at hotmail dot com
homepage:http://correy.webs.com

参考资料:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms686962(v=vs.85).aspx
*/

#include <windows.h>

typedef struct _PROGRAM_ITEM {
    SLIST_ENTRY ItemEntry;
    ULONG Signature;
} PROGRAM_ITEM, *PPROGRAM_ITEM;

typedef  PSLIST_ENTRY (WINAPI  * pRtlFirstEntrySList) (_In_  PSLIST_HEADER ListHead);//WINAPI

int main( )
{
    pRtlFirstEntrySList RtlFirstEntrySList = (pRtlFirstEntrySList)GetProcAddress(LoadLibrary(L"ntdll.dll"), "RtlFirstEntrySList");
    PSLIST_HEADER pListHead = (PSLIST_HEADER)_aligned_malloc(sizeof(SLIST_HEADER),MEMORY_ALLOCATION_ALIGNMENT);//crt函数
    InitializeSListHead(pListHead);//结构清零而已,注意这个结构的第一个成员是:Alignment。

    USHORT us = QueryDepthSList(pListHead);//测试,个数是0.

    PSLIST_ENTRY pFirstEntry;

    //插入头部.
    for(ULONG Count = 1; Count <= 10; Count += 1 )
    {
        PPROGRAM_ITEM pProgramItem;//好像是临时的成员变量。
        pProgramItem = (PPROGRAM_ITEM)_aligned_malloc(sizeof(PROGRAM_ITEM),MEMORY_ALLOCATION_ALIGNMENT);
        pProgramItem->Signature = Count;

        pFirstEntry = InterlockedPushEntrySList(pListHead, &(pProgramItem->ItemEntry)); //插入到pListHead的头部,被插入的是后面的。
    }

    us = QueryDepthSList(pListHead);//测试,个数是10.

    //遍历.
    for (pFirstEntry = RtlFirstEntrySList(pListHead) ; pFirstEntry != 0; pFirstEntry = pFirstEntry->Next)
    {
        //PPROGRAM_ITEM ppi = CONTAINING_RECORD(pFirstEntry, PROGRAM_ITEM, );
        PPROGRAM_ITEM ppi = (PPROGRAM_ITEM)pFirstEntry;
        printf("Signature is %d\n", ppi->Signature);
    }

    //删除.
    for(ULONG Count = 10; Count >= 1; Count -= 1 )
    {
        PSLIST_ENTRY pListEntry = InterlockedPopEntrySList(pListHead);//从头移除
        if( NULL == pListEntry )  return -1;

        PPROGRAM_ITEM pProgramItem;//好像是临时的成员变量。
        pProgramItem = (PPROGRAM_ITEM)pListEntry;
        printf("Signature is %d\n", pProgramItem->Signature);

        _aligned_free(pListEntry);//crt函数。
    }

    PSLIST_ENTRY pListEntry = InterlockedFlushSList(pListHead);//Removes all items from a singly linked list.
    us = QueryDepthSList(pListHead);//测试,个数是0.
    pFirstEntry = InterlockedPopEntrySList(pListHead);
    us = QueryDepthSList(pListHead);//测试,个数是0.
    if (pFirstEntry != NULL) {
        return -1;
    }

    _aligned_free(pListHead);
    return 1;
}

CryptoAPI.Cpp


//引子,这些知识内容来源于网络加解密或其他的需要。
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//示例一:加解密一个文件。
//本文精简自msdn。
//下一个版本的,即CNG,需要vista或者server 2008.或者特殊的开发包。
#include <windows.h>

void MyEncryptFile(LPTSTR pszSourceFile, LPTSTR pszDestinationFile, LPTSTR pszPassword)
{ 
    HCRYPTPROV hCryptProv = NULL; 
    CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL,0);

    HCRYPTHASH hHash = NULL;
    CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hHash);
    CryptHashData(hHash, (BYTE *)pszPassword,lstrlen(pszPassword), 0);

    HCRYPTKEY hKey = NULL; 
    CryptDeriveKey(hCryptProv, CALG_RC4, hHash, 0x00800000, &hKey); 

    HANDLE hSourceFile = CreateFile(pszSourceFile, FILE_READ_DATA,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
    HANDLE hDestinationFile = CreateFile(pszDestinationFile, FILE_WRITE_DATA,FILE_SHARE_READ,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);

    PBYTE pbBuffer = (BYTE *)malloc(1000 - 1000 % 8 + 8);
    bool fEOF = FALSE;
    do 
    { 
        DWORD dwCount; 
        ReadFile(hSourceFile, pbBuffer, 1000 - 1000 % 8, &dwCount, NULL);
        if(dwCount < 1000 - 1000 % 8)   fEOF = TRUE;
        CryptEncrypt(hKey, NULL, fEOF,0, pbBuffer,&dwCount, 1000 - 1000 % 8 + 8);
        WriteFile(hDestinationFile, pbBuffer,dwCount,&dwCount,NULL);
    } while(!fEOF);

    CloseHandle(hDestinationFile);//立即写入文件。
} 

void MyDecryptFile(LPTSTR pszSourceFile, LPTSTR pszDestinationFile, LPTSTR pszPassword)
{  
    HCRYPTPROV hCryptProv = NULL; 
    CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, 0);

    HCRYPTHASH hHash = NULL;
    CryptCreateHash(hCryptProv,CALG_MD5, 0, 0, &hHash);    
    CryptHashData(hHash, (BYTE *)pszPassword, lstrlen(pszPassword), 0);  

    HCRYPTKEY hKey = NULL; 
    CryptDeriveKey(hCryptProv, CALG_RC4,hHash, 0x00800000, &hKey); 

    HANDLE hSourceFile = CreateFile(pszSourceFile, FILE_READ_DATA,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
    HANDLE hDestinationFile = CreateFile(pszDestinationFile,FILE_WRITE_DATA,FILE_SHARE_READ,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);

    PBYTE pbBuffer = (PBYTE)malloc(1000 - 1000 % 8);
    bool fEOF = false;
    do
    {
        DWORD dwCount;
        ReadFile(hSourceFile, pbBuffer, 1000 - 1000 % 8, &dwCount, NULL);
        if(dwCount < 1000 - 1000 % 8)   fEOF = TRUE;        
        CryptDecrypt(hKey, 0, fEOF, 0, pbBuffer, &dwCount);         
        WriteFile(hDestinationFile, pbBuffer, dwCount,&dwCount,NULL);
    }while(!fEOF);

    CloseHandle(hDestinationFile);//立即写入文件。
}

int _tmain(int argc, _TCHAR* argv[])
{
    MyEncryptFile((LPTSTR)L"c:\\test.txt", (LPTSTR)L"c:\\en.txt", (LPTSTR)L"correy");
    MyDecryptFile((LPTSTR)L"c:\\en.txt", (LPTSTR)L"c:\\test_de.txt", (LPTSTR)L"correy");
    return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//示例二:加解密一段字符。//修改自msdn
#include <windows.h>
#pragma comment(lib, "crypt32.lib")

#define MY_ENCODING_TYPE  (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)

void main(void)
{
    BYTE* pbContent = (BYTE*) "This is a Encoding and Decoding a Hashed Message example from msdn\n"
        "made by correy;QQ:112426112;email:leguanyuan@126.com;website:http://correy.webs.com";
    DWORD cbContent = strlen((char *)pbContent)+1;  

    HCRYPTPROV hCryptProv;
    CryptAcquireContext(&hCryptProv,NULL,NULL,PROV_RSA_FULL,0);

    CRYPT_ALGORITHM_IDENTIFIER HashAlgorithm;
    DWORD HashAlgSize = sizeof(HashAlgorithm);
    memset(&HashAlgorithm, 0, HashAlgSize);   
    HashAlgorithm.pszObjId = szOID_RSA_MD5;  

    CMSG_HASHED_ENCODE_INFO HashedEncodeInfo;
    memset(&HashedEncodeInfo, 0, sizeof(CMSG_HASHED_ENCODE_INFO));
    HashedEncodeInfo.cbSize = sizeof(CMSG_HASHED_ENCODE_INFO);
    HashedEncodeInfo.hCryptProv = hCryptProv;
    HashedEncodeInfo.HashAlgorithm = HashAlgorithm;
    HashedEncodeInfo.pvHashAuxInfo = NULL;

    DWORD cbEncodedBlob = CryptMsgCalculateEncodedLength(MY_ENCODING_TYPE,0, CMSG_HASHED,&HashedEncodeInfo,NULL,cbContent);
    BYTE * pbEncodedBlob = (BYTE *) malloc(cbEncodedBlob);

    HCRYPTMSG hMsg = CryptMsgOpenToEncode(MY_ENCODING_TYPE,0,CMSG_HASHED,&HashedEncodeInfo,NULL,NULL);
    CryptMsgUpdate(hMsg,pbContent,cbContent,TRUE);
    HCRYPTMSG hDupMsg = CryptMsgDuplicate(hMsg);

    CryptMsgGetParam(hDupMsg,CMSG_CONTENT_PARAM,0,pbEncodedBlob,&cbEncodedBlob);//加密 Encoding 
    CryptMsgClose(hMsg);
    CryptMsgClose(hDupMsg);//加密结束,下面是解密。

    hMsg = CryptMsgOpenToDecode(MY_ENCODING_TYPE,0,0,hCryptProv,NULL,NULL);
    CryptMsgUpdate(hMsg,pbEncodedBlob,cbEncodedBlob,TRUE); 

    DWORD cbData = sizeof(DWORD);
    DWORD dwMsgType;
    CryptMsgGetParam(hMsg,CMSG_TYPE_PARAM,0,&dwMsgType,&cbData);//if(dwMsgType == CMSG_HASHED) printf("The message is a hashed message. Proceed. \n");
    
    DWORD cbDecoded;
    CryptMsgGetParam(hMsg,CMSG_CONTENT_PARAM,0,NULL,&cbDecoded);//获取应得的内存大小。
    BYTE  * pbDecoded = (BYTE *) malloc(cbDecoded);

    CryptMsgGetParam(hMsg,CMSG_CONTENT_PARAM,0, pbDecoded,&cbDecoded);//解密 Decoding
    CryptMsgControl(hMsg,0,CMSG_CTRL_VERIFY_HASH,NULL);

    if(pbEncodedBlob)        free(pbEncodedBlob);
    if(pbDecoded)        free(pbDecoded);
    CryptMsgClose(hMsg); 
    if(hCryptProv)         CryptReleaseContext(hCryptProv,0);
} 
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//示例三:计算一个文件的MD5 hash,其实用这个dll里面的别的api也可以实现的。//修改自msdn
#include <windows.h>

DWORD main()
{ 
    HANDLE hFile = CreateFile(L"c:\\a.txt",GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_FLAG_SEQUENTIAL_SCAN,NULL);

    HCRYPTPROV hProv = 0;
    CryptAcquireContext(&hProv,NULL,NULL,PROV_RSA_FULL,CRYPT_VERIFYCONTEXT);// Get handle to the crypto provider

    HCRYPTHASH hHash = 0;
    CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash);

    BYTE rgbFile[1024] = {0};
    DWORD cbRead = 0;
    while (ReadFile(hFile, rgbFile, 1024, &cbRead, NULL))
    {
        if (0 == cbRead)          break;
        CryptHashData(hHash, rgbFile, cbRead, 0);
    }

    DWORD cbHash = 16;
    BYTE rgbHash[16];
    if (CryptGetHashParam(hHash, HP_HASHVAL, rgbHash, &cbHash, 0))
    { //下面是显示。
        printf("MD5 hash of you select file is: ");
        for (DWORD i = 0; i < cbHash; i++)
        {
            CHAR rgbDigits[] = "0123456789abcdef";
            printf("%c%c", rgbDigits[rgbHash[i] >> 4],rgbDigits[rgbHash[i] & 0xf]);
        }
        //printf("\n");
    }

    CryptDestroyHash(hHash);
    CryptReleaseContext(hProv, 0);
    CloseHandle(hFile);
    return 0; 
}   
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//示例四:Example C++ Program: Creating an HMAC.made from msdn
#include <windows.h>

int main()
{      
    HCRYPTPROV  hProv       = NULL;
    CryptAcquireContext(&hProv,NULL,NULL,PROV_RSA_FULL,CRYPT_VERIFYCONTEXT);

    HCRYPTHASH  hHash       = NULL;
    CryptCreateHash(hProv, CALG_SHA1, 0, 0, &hHash);
    BYTE        Data1[]     = {0x70,0x61,0x73,0x73,0x77,0x6F,0x72,0x64};
    CryptHashData(hHash,Data1,sizeof(Data1),0); 
    HCRYPTKEY   hKey        = NULL;
    CryptDeriveKey(hProv, CALG_RC4, hHash, 0,  &hKey); 

    HMAC_INFO   HmacInfo;
    ZeroMemory(&HmacInfo, sizeof(HmacInfo));
    HmacInfo.HashAlgid = CALG_SHA1;

    HCRYPTHASH  hHmacHash   = NULL;
    CryptCreateHash(hProv,CALG_HMAC,hKey, 0, &hHmacHash);
    CryptSetHashParam(hHmacHash,HP_HMAC_INFO,(BYTE*)&HmacInfo,0);
    BYTE        Data2[]     = {0x6D,0x65,0x73,0x73,0x61,0x67,0x65};
    CryptHashData(hHmacHash,Data2,sizeof(Data2),0);

    DWORD       dwDataLen   = 0;
    CryptGetHashParam(hHmacHash,HP_HASHVAL,NULL,&dwDataLen,0);

    PBYTE       pbHash      = NULL;
    pbHash = (BYTE*)malloc(dwDataLen);
    CryptGetHashParam(hHmacHash,HP_HASHVAL,pbHash,&dwDataLen,0);

    printf("The hash is:  ");
    for(DWORD i = 0 ; i < dwDataLen ; i++) 
    {
        printf("%2.2x ",pbHash[i]);
    }
    printf("\n");

    if(hHmacHash)        CryptDestroyHash(hHmacHash);
    if(hKey)        CryptDestroyKey(hKey);
    if(hHash)        CryptDestroyHash(hHash);    
    if(hProv)        CryptReleaseContext(hProv, 0);
    if(pbHash)        free(pbHash);
    return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//暂时到此为止,以后可以添加和修改。