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


当前回答

这里有两行,只需在第2行中更改“hello”:

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

其他回答

这个网站有一个例子:使用Powershell进行MD5校验和。它使用. 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()

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

例如,我编写了一个从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必须在此命令工作的同一文件夹中。

现在有一个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即可。

示例来自PowerShell 5.1的官方文档。文档中有更多示例。

(
    [System.Security.Cryptography.MD5CryptoServiceProvider]::new().ComputeHash(
        [System.Text.UTF8Encoding]::new().GetBytes($yourText)
    ) `
    | %{ [Convert]::ToString($_, 16) }
) -join ''

$yourText = 'hello'输出5d41402abc4b2a76b9719d911017c592

另一个早在2003年就默认安装在Windows中的内置命令是Certutil,当然也可以从PowerShell调用它。

CertUtil -hashfile file.foo MD5

(注意:MD5应该全部大写以获得最大的健壮性)