You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PowerShell中计算未签名文件的Authenticode SHA1、SHA256哈希?

计算未签名文件的Authenticode SHA1/SHA256哈希(PowerShell/.NET方案)

如果你需要的是符合Authenticode标准的哈希值(区别于Get-FileHash输出的文件全内容哈希),且不想依赖ConfigCI模块,可以通过调用Windows原生API实现,以下是PowerShell中可直接运行的.NET/C#代码方案:

Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.IO;

public class AuthenticodeHashCalculator
{
    [DllImport("Crypt32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    private static extern bool CryptCATAdminCalcHashFromFileHandle(
        IntPtr hFile,
        ref uint pcbHash,
        byte[] pbHash,
        uint dwFlags);

    public static string GetHash(string filePath, HashAlgorithmName algorithm)
    {
        uint hashId = algorithm.Name switch
        {
            "SHA1" => 0x00008004,
            "SHA256" => 0x0000800C,
            _ => throw new ArgumentException("仅支持SHA1和SHA256算法")
        };

        using var stream = File.OpenRead(filePath);
        IntPtr fileHandle = stream.SafeFileHandle.DangerousGetHandle();

        uint bufferSize = 0;
        // 第一次调用获取所需缓冲区大小
        if (!CryptCATAdminCalcHashFromFileHandle(fileHandle, ref bufferSize, null, 0))
        {
            int error = Marshal.GetLastWin32Error();
            if (error != 0x8007000E) // ERROR_INSUFFICIENT_BUFFER
                throw new System.ComponentModel.Win32Exception(error);
        }

        byte[] hashBytes = new byte[bufferSize];
        if (!CryptCATAdminCalcHashFromFileHandle(fileHandle, ref bufferSize, hashBytes, 0))
        {
            throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
        }

        return BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant();
    }
}
"@

# ------------------------------
# 示例使用
# ------------------------------
$targetFile = "C:\Your\File\Path\example.exe"

# 获取Authenticode SHA1哈希
$sha1 = [AuthenticodeHashCalculator]::GetHash($targetFile, [HashAlgorithmName]::SHA1)
Write-Host "Authenticode SHA1: $sha1"

# 获取Authenticode SHA256哈希
$sha256 = [AuthenticodeHashCalculator]::GetHash($targetFile, [HashAlgorithmName]::SHA256)
Write-Host "Authenticode SHA256: $sha256"

说明

  • 该方案通过P/Invoke调用Windows系统的Crypt32.dll中CryptCATAdminCalcHashFromFileHandle函数,这是计算Authenticode哈希的原生方法,结果完全符合Windows Defender应用控制等场景的要求。
  • 无需加载ConfigCI模块,运行效率更高,输出仅包含所需的哈希值。
  • 支持未签名文件的哈希计算,逻辑与已签名文件的Authenticode哈希规则一致。

内容的提问来源于stack exchange,提问作者SpyNet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 23:42:12