我想计算一些内容的MD5校验和。如何在PowerShell中做到这一点?


当前回答

下面是一个尝试验证SHA256指纹的漂亮打印示例。我使用PowerShell v4下载了gpg4win v3.0.3(需要Get-FileHash)。

从https://www.gpg4win.org/download.html下载包,打开PowerShell,从下载页面抓取散列,然后运行:

cd ${env:USERPROFILE}\Downloads
$file = "gpg4win-3.0.3.exe"

# Set $hash to the hash reference from the download page:
$hash = "477f56212ee60cc74e0c5e5cc526cec52a069abff485c89c2d57d1b4b6a54971"

# If you have an MD5 hash: # $hashAlgo="MD5"
$hashAlgo = "SHA256"

$computed_hash = (Get-FileHash -Algorithm $hashAlgo $file).Hash.ToUpper()
if ($computed_hash.CompareTo($hash.ToUpper()) -eq 0 ) {
    Write-Output "Hash matches for file $file" 
} 
else { 
    Write-Output ("Hash DOES NOT match for file {0}: `nOriginal hash: {1} `nComputed hash: {2}" -f ($file, $hash.ToUpper(), $computed_hash)) 
}

输出:

Hash matches for file gpg4win-3.0.3.exe

其他回答

下面是一个单行命令示例,它计算文件的正确校验和(就像您刚刚下载的那样),并将其与原始文件的已发布的校验和进行比较。

例如,我编写了一个从Apache JMeter项目下载的示例。在这种情况下,你有:

下载的二进制文件 在文件中发布的原始文件的校验和。Md5为一个字符串,格式为:

3a84491f10fb7b147101cf3926c4a855 * apache-jmeter-4 0。zip

然后使用这个PowerShell命令,你可以验证下载文件的完整性:

PS C:\Distr> (Get-FileHash .\apache-jmeter-4.0.zip -Algorithm MD5).Hash -eq (Get-Content .\apache-jmeter-4.0.zip.md5 | Convert-String -Example "hash path=hash")

输出:

True

解释:

eq操作符的第一个操作数是计算文件校验和的结果:

(Get-FileHash .\apache-jmeter-4.0.zip -Algorithm MD5).Hash

第二个操作数是发布的校验和值。我们首先获取文件的内容。Md5,它是一个字符串,然后我们根据字符串格式提取哈希值:

Get-Content .\apache-jmeter-4.0.zip.md5 | Convert-String -Example "hash path=hash"

文件和文件。Md5必须在此命令工作的同一文件夹中。

网上有很多使用ComputeHash()的例子。我的测试显示,在网络连接上运行时速度非常慢。下面的片段对我来说运行得更快,但你的里程可能会有所不同:

$md5 = [System.Security.Cryptography.MD5]::Create("MD5")
$fd = [System.IO.File]::OpenRead($file)
$buf = New-Object byte[] (1024*1024*8) # 8 MB buffer
while (($read_len = $fd.Read($buf,0,$buf.length)) -eq $buf.length){
    $total += $buf.length
    $md5.TransformBlock($buf,$offset,$buf.length,$buf,$offset)
    Write-Progress -Activity "Hashing File" `
       -Status $file -percentComplete ($total/$fd.length * 100)
}

# Finalize the last read
$md5.TransformFinalBlock($buf, 0, $read_len)
$hash = $md5.Hash

# Convert hash bytes to a hexadecimal formatted string
$hash | foreach { $hash_txt += $_.ToString("x2") }
Write-Host $hash_txt

团队! 看看我的哈希计算函数。

Function Get-StringHash {
<#
    .DESCRIPTION
        Get string persistant hash.        
#>
    [OutputType([string])]
    [CmdletBinding()]
    Param(
        [Parameter( Mandatory = $True, Position = 0, HelpMessage = "String to calculate hash." )]
        [string] $String,
        [Parameter( Mandatory = $false, Position = 0, HelpMessage = "String encoding." )]
        [ValidateSet( 'UTF8' )]
        [string] $StringEncoding = 'UTF8',
        [Parameter( Mandatory = $false, Position = 2, HelpMessage = "Hash algoritm." )]
        [ValidateSet( 'md5', 'sha256', 'sha512' )]
        [string] $Algoritm = 'sha256'
    )
    try {
        #region functions
        #endregion

        $Result = $null

        switch ( $Algoritm ) {
            'md5' {  
                $HashProvider = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
            }
            'sha256' {  
                $HashProvider = New-Object -TypeName System.Security.Cryptography.SHA256CryptoServiceProvider
            }
            'sha512' {  
                $HashProvider = New-Object -TypeName System.Security.Cryptography.SHA512CryptoServiceProvider
            }
            Default {}
        }

        switch ( $StringEncoding ) {
            'UTF8' {  
                $Encoding = New-Object -TypeName System.Text.UTF8Encoding
            }
            Default {}
        }
        
        
        $Result = [System.BitConverter]::ToString( $HashProvider.ComputeHash( $Encoding.GetBytes( $String ) )).replace('-','')

    }
    catch {
        Get-ErrorReporting -Trap $_
    }

    return $Result
}

$String   = 'Some text'
$Algoritm = 'MD5'

$Hash = Get-StringHash -String $String -Algoritm $Algoritm

write-host "$String has $Algoritm hash $hash"

PowerShell One-Liners(字符串到散列)

MD5

([System.BitConverter]::ToString((New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider).ComputeHash((New-Object -TypeName System.Text.UTF8Encoding).GetBytes("Hello, World!")))).Replace("-","")

SHA1

([System.BitConverter]::ToString((New-Object -TypeName System.Security.Cryptography.SHA1CryptoServiceProvider).ComputeHash((New-Object -TypeName System.Text.UTF8Encoding).GetBytes("Hello, World!")))).Replace("-","")

SHA256

([System.BitConverter]::ToString((New-Object -TypeName System.Security.Cryptography.SHA256CryptoServiceProvider).ComputeHash((New-Object -TypeName System.Text.UTF8Encoding).GetBytes("Hello, World!")))).Replace("-","")

SHA384

([System.BitConverter]::ToString((New-Object -TypeName System.Security.Cryptography.SHA384CryptoServiceProvider).ComputeHash((New-Object -TypeName System.Text.UTF8Encoding).GetBytes("Hello, World!")))).Replace("-","")

SHA512

([System.BitConverter]::ToString((New-Object -TypeName System.Security.Cryptography.SHA512CryptoServiceProvider).ComputeHash((New-Object -TypeName System.Text.UTF8Encoding).GetBytes("Hello, World!")))).Replace("-","")

这是我用来获得一致哈希值的方法:

function New-CrcTable {
    [uint32]$c = $null
    $crcTable = New-Object 'System.Uint32[]' 256

    for ($n = 0; $n -lt 256; $n++) {
        $c = [uint32]$n
        for ($k = 0; $k -lt 8; $k++) {
            if ($c -band 1) {
                $c = (0xEDB88320 -bxor ($c -shr 1))
            }
            else {
                $c = ($c -shr 1)
            }
        }
        $crcTable[$n] = $c
    }

    Write-Output $crcTable
}

function Update-Crc ([uint32]$crc, [byte[]]$buffer, [int]$length, $crcTable) {
    [uint32]$c = $crc

    for ($n = 0; $n -lt $length; $n++) {
        $c = ($crcTable[($c -bxor $buffer[$n]) -band 0xFF]) -bxor ($c -shr 8)
    }

    Write-Output $c
}

function Get-CRC32 {
    <#
        .SYNOPSIS
            Calculate CRC.
        .DESCRIPTION
            This function calculates the CRC of the input data using the CRC32 algorithm.
        .EXAMPLE
            Get-CRC32 $data
        .EXAMPLE
            $data | Get-CRC32
        .NOTES
            C to PowerShell conversion based on code in https://www.w3.org/TR/PNG/#D-CRCAppendix

            Author: Øyvind Kallstad
            Date: 06.02.2017
            Version: 1.0
        .INPUTS
            byte[]
        .OUTPUTS
            uint32
        .LINK
            https://communary.net/
        .LINK
            https://www.w3.org/TR/PNG/#D-CRCAppendix

    #>
    [CmdletBinding()]
    param (
        # Array of Bytes to use for CRC calculation
        [Parameter(Position = 0, ValueFromPipeline = $true)]
        [ValidateNotNullOrEmpty()]
        [byte[]]$InputObject
    )

    $dataArray = @()
    $crcTable = New-CrcTable
    foreach ($item  in $InputObject) {
        $dataArray += $item
    }
    $inputLength = $dataArray.Length
    Write-Output ((Update-Crc -crc 0xffffffffL -buffer $dataArray -length $inputLength -crcTable $crcTable) -bxor 0xffffffffL)
}

function GetHash() {
    [CmdletBinding()]
    param(
        [Parameter(Position = 0, ValueFromPipeline = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$InputString
    )

    $bytes = [System.Text.Encoding]::UTF8.GetBytes($InputString)
    $hasCode = Get-CRC32 $bytes
    $hex = "{0:x}" -f $hasCode
    return $hex
}

function Get-FolderHash {
    [CmdletBinding()]
    param(
        [Parameter(Position = 0, ValueFromPipeline = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$FolderPath
    )

    $FolderContent = New-Object System.Collections.ArrayList
    Get-ChildItem $FolderPath -Recurse | Where-Object {
        if ([System.IO.File]::Exists($_)) {
            $FolderContent.AddRange([System.IO.File]::ReadAllBytes($_)) | Out-Null
        }
    }

    $hasCode = Get-CRC32 $FolderContent
    $hex = "{0:x}" -f $hasCode
    return $hex.Substring(0, 8).ToLower()
}