如何获得在PowerShell中的MD5校验

问题描述 投票:151回答:14

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

powershell powershell-v2.0
14个回答
289
投票

如果内容是一个字符串:

$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

这当然是更好,因为它避免了在意见中确定的第一个解决方案提供的问题(使用流,关闭它,并且支持大文件)。


2
投票

添加我的解决了战斗。作为接受的答案Get-FileHash说很容易用文件来使用,但也可以用字符串使用它:

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

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

1
投票

样品右键菜单选项,以及:

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

0
投票

漂亮的印刷例如,尝试验证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

0
投票

下面是两个计算文件的正确的校验,就像你刚刚下载,并将其与原公布的校验和比较1行的命令的例子。

比如我写了downloadings from Apache Jmeter project例子。在这种情况下,您有:

  1. 下载的二进制文件
  2. 这是发表在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.md5必须是在同一文件夹此命令的工作。


56
投票

如果您使用的是PowerShell Community Extensions有一个GET-哈希命令行开关,可以轻松做到这一点:

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


Algorithm: MD5


Path       :
HashString : E42B054623B3799CB71F0883900F2764

15
投票

这里有两条线,只是改变“你好”行#2:

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

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块。


9
投票

有网上使用ComputeHash()有很多的例子。我的测试显示,通过网络连接运行时,这是非常缓慢的。下面的代码片段运行对我来说要快得多,但情况因人而异:

$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

6
投票

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

下面是文章,结合斯蒂芬的评论的代码:

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

5
投票

另一个内建在长期被默认可以追溯到2003安装在Windows命令的certutil,这当然可以从PowerShell中调用了。

CertUtil -hashfile file.foo MD5

(警告:MD5应是在最大的鲁棒性全部大写)


4
投票

这个问题几乎是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

只要改变SHA384用MD5。

The example is from the official documentation of PowerShell 5.1

我想这个答案是多余的凯斯 - 希尔的回答和所选择的答案的版本,但它指向的官方文档,它有一个更好的例子。该文档有更多的例子。


3
投票

如果您从微软下载FCIV这将成为一个班轮。

从这里下载Microsoft文件校验和完整性验证https://support.microsoft.com/en-us/kb/841290

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

gci WTAM*.tar | % {.\fciv $_.Name}
© www.soinside.com 2019 - 2024. All rights reserved.