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


当前回答

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

$yourText = 'hello'输出5d41402abc4b2a76b9719d911017c592

其他回答

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

Get-FileHash <filepath> -Algorithm MD5

这当然是更可取的,因为它避免了注释中指出的旧PowerShell解决方案所提供的问题(使用流,关闭它,并支持大文件)。

如果内容是字符串:

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

对于较旧的PowerShell版本

如果内容为文件:

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

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

CertUtil -hashfile file.foo MD5

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

下面是我用来获取给定字符串的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")}) 

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

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

如果从Microsoft下载文件校验和完整性验证器(FCIV),这将变成一行程序。

我从这里下载了FCIV: 文件校验和完整性验证工具的可用性和说明

执行如下命令。我有十份文件要检查。

Get-ChildItem WTAM*.tar | % {.\fciv $_.Name}