如何在C#中检查文件是否已签名?

22

我正在编写一个需要加载其他文件的程序。 有没有一种方法可以检查这些文件是否已签名,而不需要右键单击并检查?我使用300-400个文件,每隔几天就会更改。 我需要检查DLL / EXE / CAB / OCX / MSI(也可能是vbs / js)。 有没有一种方法可以检查它们是否已签名?


1
除非您遇到特定的问题,否则帮助资源可能会很少,除了一些参考链接,这些链接可能是您自己找到的 - 请告诉我们您已经尝试过什么。 - Grant Thomas
1
可能是重复的问题:如何检查文件是否具有数字签名 - user195488
20
我不同意这个问题不是一个真正的问题或者没有建设性。 关闭者应该阅读他所要求的内容,即代码签名。 右键单击并检查文件属性是手动查看文件是否签名的方法。 我同意这是一个重复的问题,并已经发布了链接。 - user195488
请查看这篇文章,我认为这就是你正在寻找的内容:https://dev59.com/S3RB5IYBdhLWcg3wSVm1 - Tigran
5
这个问题被无故关闭,但我在这里发布了一个相关的解决方案:https://dev59.com/S3RB5IYBdhLWcg3wSVm1#34200959。 - OSH
显示剩余8条评论
1个回答

72

假设您想检查文件是否被Authenticode签名,并且证书是可信的,您可以pinvoke到Wintrust.dll中的WinVerifyTrust

下面是一个包装器(或多或少从这里复制), 可以按以下方式调用:

AuthenticodeTools.IsTrusted(@"path\to\some\signed\file.exe")

其中 AuthenticodeTools 的定义如下:

internal static class AuthenticodeTools
{
    [DllImport("Wintrust.dll", PreserveSig = true, SetLastError = false)]
    private static extern uint WinVerifyTrust(IntPtr hWnd, IntPtr pgActionID, IntPtr pWinTrustData);
    private static uint WinVerifyTrust(string fileName)
    {

        Guid wintrust_action_generic_verify_v2 = new Guid("{00AAC56B-CD44-11d0-8CC2-00C04FC295EE}");
        uint result=0;
        using (WINTRUST_FILE_INFO fileInfo = new WINTRUST_FILE_INFO(fileName,
                                                                    Guid.Empty))
        using (UnmanagedPointer guidPtr = new UnmanagedPointer(Marshal.AllocHGlobal(Marshal.SizeOf(typeof (Guid))),
                                                               AllocMethod.HGlobal))
        using (UnmanagedPointer wvtDataPtr = new UnmanagedPointer(Marshal.AllocHGlobal(Marshal.SizeOf(typeof (WINTRUST_DATA))),
                                                                  AllocMethod.HGlobal))
        {
            WINTRUST_DATA data = new WINTRUST_DATA(fileInfo);
            IntPtr pGuid = guidPtr;
            IntPtr pData = wvtDataPtr;
            Marshal.StructureToPtr(wintrust_action_generic_verify_v2,
                                   pGuid,
                                   true);
            Marshal.StructureToPtr(data,
                                   pData,
                                   true);
            result = WinVerifyTrust(IntPtr.Zero,
                                    pGuid,
                                    pData);
            
        }
        return result;

    }
    public static bool IsTrusted(string fileName)
    {
        return WinVerifyTrust(fileName) == 0;
    }


}

internal struct WINTRUST_FILE_INFO : IDisposable
{

    public WINTRUST_FILE_INFO(string fileName, Guid subject)
    {

        cbStruct = (uint)Marshal.SizeOf(typeof(WINTRUST_FILE_INFO));

        pcwszFilePath = fileName;



        if (subject != Guid.Empty)
        {

            pgKnownSubject = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Guid)));

            Marshal.StructureToPtr(subject, pgKnownSubject, true);

        }

        else
        {

            pgKnownSubject = IntPtr.Zero;

        }

        hFile = IntPtr.Zero;

    }

    public uint cbStruct;

    [MarshalAs(UnmanagedType.LPTStr)]

    public string pcwszFilePath;

    public IntPtr hFile;

    public IntPtr pgKnownSubject;



    #region IDisposable Members



    public void Dispose()
    {

        Dispose(true);

    }



    private void Dispose(bool disposing)
    {

        if (pgKnownSubject != IntPtr.Zero)
        {

            Marshal.DestroyStructure(this.pgKnownSubject, typeof(Guid));

            Marshal.FreeHGlobal(this.pgKnownSubject);

        }

    }



    #endregion

}

enum AllocMethod
{
    HGlobal,
    CoTaskMem
};
enum UnionChoice
{
    File = 1,
    Catalog,
    Blob,
    Signer,
    Cert
};
enum UiChoice
{
    All = 1,
    NoUI,
    NoBad,
    NoGood
};
enum RevocationCheckFlags
{
    None = 0,
    WholeChain
};
enum StateAction
{
    Ignore = 0,
    Verify,
    Close,
    AutoCache,
    AutoCacheFlush
};
enum TrustProviderFlags
{
    UseIE4Trust = 1,
    NoIE4Chain = 2,
    NoPolicyUsage = 4,
    RevocationCheckNone = 16,
    RevocationCheckEndCert = 32,
    RevocationCheckChain = 64,
    RecovationCheckChainExcludeRoot = 128,
    Safer = 256,
    HashOnly = 512,
    UseDefaultOSVerCheck = 1024,
    LifetimeSigning = 2048
};
enum UIContext
{
    Execute = 0,
    Install
};

[StructLayout(LayoutKind.Sequential)]

internal struct WINTRUST_DATA : IDisposable
{

    public WINTRUST_DATA(WINTRUST_FILE_INFO fileInfo)
    {

        this.cbStruct = (uint)Marshal.SizeOf(typeof(WINTRUST_DATA));

        pInfoStruct = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(WINTRUST_FILE_INFO)));

        Marshal.StructureToPtr(fileInfo, pInfoStruct, false);

        this.dwUnionChoice = UnionChoice.File;



        pPolicyCallbackData = IntPtr.Zero;

        pSIPCallbackData = IntPtr.Zero;



        dwUIChoice = UiChoice.NoUI;

        fdwRevocationChecks = RevocationCheckFlags.None;

        dwStateAction = StateAction.Ignore;

        hWVTStateData = IntPtr.Zero;

        pwszURLReference = IntPtr.Zero;

        dwProvFlags = TrustProviderFlags.Safer;



        dwUIContext = UIContext.Execute;

    }



    public uint cbStruct;

    public IntPtr pPolicyCallbackData;

    public IntPtr pSIPCallbackData;

    public UiChoice dwUIChoice;

    public RevocationCheckFlags fdwRevocationChecks;

    public UnionChoice dwUnionChoice;

    public IntPtr pInfoStruct;

    public StateAction dwStateAction;

    public IntPtr hWVTStateData;

    private IntPtr pwszURLReference;

    public TrustProviderFlags dwProvFlags;

    public UIContext dwUIContext;



    #region IDisposable Members



    public void Dispose()
    {

        Dispose(true);

    }



    private void Dispose(bool disposing)
    {

        if (dwUnionChoice == UnionChoice.File)
        {

            WINTRUST_FILE_INFO info = new WINTRUST_FILE_INFO();

            Marshal.PtrToStructure(pInfoStruct, info);

            info.Dispose();

            Marshal.DestroyStructure(pInfoStruct, typeof(WINTRUST_FILE_INFO));

        }



        Marshal.FreeHGlobal(pInfoStruct);

    }



    #endregion

}

internal sealed class UnmanagedPointer : IDisposable
{

    private IntPtr m_ptr;

    private AllocMethod m_meth;

    internal UnmanagedPointer(IntPtr ptr, AllocMethod method)
    {

        m_meth = method;

        m_ptr = ptr;

    }



    ~UnmanagedPointer()
    {

        Dispose(false);

    }



    #region IDisposable Members

    private void Dispose(bool disposing)
    {

        if (m_ptr != IntPtr.Zero)
        {

            if (m_meth == AllocMethod.HGlobal)
            {

                Marshal.FreeHGlobal(m_ptr);

            }

            else if (m_meth == AllocMethod.CoTaskMem)
            {

                Marshal.FreeCoTaskMem(m_ptr);

            }

            m_ptr = IntPtr.Zero;

        }



        if (disposing)
        {

            GC.SuppressFinalize(this);

        }

    }



    public void Dispose()
    {

        Dispose(true);

    }



    #endregion



    public static implicit operator IntPtr(UnmanagedPointer ptr)
    {

        return ptr.m_ptr;

    }

}

4
请参阅 http://www.pinvoke.net/default.aspx/wintrust.winverifytrust 获取有关 WinVerifyTrust 函数的其他互操作注释。 - tomasdeml
2
顺便提一下,现在有一个非常出色的纯.NET库可供使用 https://github.com/vcsjones/AuthenticodeExaminer - Vivek Rathod
@VivekRathod 发现不错,但我对“纯.NET库”这个术语有异议。“该库是围绕原生Windows API的包装器,提供此功能。” - spender
1
@spender同意了 - 正如你指出的那样,我使用了不太正确的术语。 - Vivek Rathod

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接