如何在PowerShell中获取MD5校验和

时间:2012-05-09 17:24:27

标签: powershell powershell-v2.0

我想计算一些内容的MD5校验和。我如何在PowerShell中执行此操作?

17 个答案:

答案 0 :(得分:284)

如果内容是字符串:

$someString = "Hello World!"
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$utf8 = new-object -TypeName System.Text.UTF8Encoding
$hash = [System.BitConverter]::ToString($md5.ComputeHash($utf8.GetBytes($someString)))

如果内容是文件:

$someFilePath = "C:\foo.txt"
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($someFilePath)))

从PowerShell版本4开始,使用Get-FileHash cmdlet开箱即用的文件很容易实现:

Get-FileHash <filepath> -Algorithm MD5

这当然更可取,因为它避免了第一个解决方案提供的问题,如评论中所述(使用流,关闭它,并支持大文件)。

答案 1 :(得分:57)

如果您使用的是PowerShell Community Extensions,则可以使用Get-Hash命令行开关轻松完成此操作:

C:\PS> "hello world" | Get-Hash -Algorithm MD5


Algorithm: MD5


Path       :
HashString : E42B054623B3799CB71F0883900F2764

答案 2 :(得分:15)

以下是两行,只需更改第2行中的“hello”:

PS C:\> [Reflection.Assembly]::LoadWithPartialName("System.Web")
PS C:\> [System.Web.Security.FormsAuthentication]::HashPasswordForStoringInConfigFile("hello", "MD5")

答案 3 :(得分:14)

这是我用来处理相对和绝对路径的函数:

function md5hash($path)
{
    $fullPath = Resolve-Path $path
    $md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
    $file = [System.IO.File]::Open($fullPath,[System.IO.Filemode]::Open, [System.IO.FileAccess]::Read)
    try {
        [System.BitConverter]::ToString($md5.ComputeHash($file))
    } finally {
        $file.Dispose()
    }
}

感谢上面的@davor建议使用Open()而不是ReadAllBytes()和@jpmc26来建议使用finally块。

答案 4 :(得分:9)

使用ComputeHash()在线有很多例子。我的测试表明,当通过网络连接运行时,这非常慢。下面的代码段对我来说运行得更快,但是YMMV:

$md5 = [System.Security.Cryptography.MD5]::Create("MD5")
$fd = [System.IO.File]::OpenRead($file)
$buf = new-object byte[] (1024*1024*8) # 8mb 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 hex formatted string
$hash | foreach { $hash_txt += $_.ToString("x2") }
write-host $hash_txt

答案 5 :(得分:6)

此网站有一个示例:http://blog.brianhartsock.com/2008/12/13/using-powershell-for-md5-checksums/。它使用.NET框架实例化MD5哈希算法的实例来计算哈希值。

以下是文章中的代码,其中包含Stephen的评论:

param
(
  $file
)

$algo = [System.Security.Cryptography.HashAlgorithm]::Create("MD5")
$stream = New-Object System.IO.FileStream($Path, [System.IO.FileMode]::Open, 
    [System.IO.FileAccess]::Read)

$md5StringBuilder = New-Object System.Text.StringBuilder
$algo.ComputeHash($stream) | % { [void] $md5StringBuilder.Append($_.ToString("x2")) }
$md5StringBuilder.ToString()

$stream.Dispose()

答案 6 :(得分:5)

默认情况下,早在2003年安装的另一个内置命令是certutil,当然也可以从powershell调用。

CertUtil -hashfile file.foo MD5

(警告:MD5应该全部上限以获得最大的稳健性)

答案 7 :(得分:4)

PowerShell一线式(从字符串到哈希)

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("-","")

答案 8 :(得分:3)

这个问题已经快3年了,从那以后,正如一些评论所说,有一个非常方便的Get-FileHash功能。

PS C:\> Get-FileHash C:\Users\Andris\Downloads\Contoso8_1_ENT.iso -Algorithm SHA384 | Format-List

Algorithm : SHA384
Hash      : 20AB1C2EE19FC96A7C66E33917D191A24E3CE9DAC99DB7C786ACCE31E559144FEAFC695C58E508E2EBBC9D3C96F21FA3
Path      : C:\Users\Andris\Downloads\Contoso8_1_ENT.iso

只需使用MD5更改SHA384。

The example is from the official documentation of PowerShell 5.1

我想这个答案是keith-hill答案和所选答案版本的冗余,但它指向官方文档,它有一个更好的例子。文档中有更多示例。

答案 9 :(得分:3)

如果您从Microsoft下载FCIV,这将成为一个单行。

从此处下载Microsoft的File Checksum Integrity Verifier https://support.microsoft.com/en-us/kb/841290

运行以下命令。我有十个要检查的文件。

gci WTAM*.tar | % {.\fciv $_.Name}

答案 10 :(得分:1)

右键菜单选项的示例:

[HKEY_CLASSES_ROOT\*\shell\SHA1 PS check\command]
@="C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\powershell.exe -NoExit -Command get-filehash -algorithm SHA1 '%1'"

答案 11 :(得分:1)

这将返回远程计算机上文件的MD5哈希值:

Invoke-Command -ComputerName RemoteComputerName -ScriptBlock {
    $fullPath = Resolve-Path 'c:\Program Files\Internet Explorer\iexplore.exe'
    $md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
    $file = [System.IO.File]::OpenRead($fullPath)
    $hash = [System.BitConverter]::ToString($md5.ComputeHash($file))
    $hash -replace "-", ""
    $file.Dispose()
}

答案 12 :(得分:0)

漂亮的打印示例尝试使用powershell v4验证SHA256指纹下载的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

答案 13 :(得分:0)

这是一个单行命令示例,既可以像您刚刚下载的一样计算文件的正确校验和,也可以将其与原始文件的已发布校验和进行比较。

例如,我为downloadings from Apache Jmeter project编写了示例。在这种情况下,您可以:

  1. 下载的二进制文件
  2. 原始文件的
  3. 校验和,以一个字符串的形式发布在 file.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

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

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

file file.md5 都必须在同一文件夹中才能执行此命令。

答案 14 :(得分:0)

将我的解决方案添加到竞争中。如已接受的答案所述,Get-FileHash易于使用文件,但也可以将其用于字符串:

$s = "asdf"
Get-FileHash -InputStream ([System.IO.MemoryStream]::New([System.Text.Encoding]::ASCII.GetBytes($s)))

答案 15 :(得分:0)

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

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()
}

答案 16 :(得分:0)

这是我用来获取给定字符串的MD5的代码段:

$text = "text goes here..."
$md5  = [Security.Cryptography.MD5CryptoServiceProvider]::new()
$utf8 = [Text.UTF8Encoding]::UTF8
$bytes= $md5.ComputeHash($utf8.GetBytes($text))
$hash = [string]::Concat($bytes.foreach{$_.ToString("x2")})