我想计算一些内容的MD5校验和。如何在PowerShell中做到这一点?
当前回答
团队! 看看我的哈希计算函数。
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"
其他回答
下面是我使用的处理相对路径和绝对路径的函数:
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块。
(
[System.Security.Cryptography.MD5CryptoServiceProvider]::new().ComputeHash(
[System.Text.UTF8Encoding]::new().GetBytes($yourText)
) `
| %{ [Convert]::ToString($_, 16) }
) -join ''
$yourText = 'hello'输出5d41402abc4b2a76b9719d911017c592
这个网站有一个例子:使用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()
从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)))
下面是一个尝试验证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
推荐文章
- PowerShell等价于grep -f
- “Write-Host”,“Write-Output”,或“[console]::WriteLine”之间的区别是什么?
- Powershell相当于bash的&号(&),用于分叉/运行后台进程
- PowerShell脚本在机器上返回。net框架的版本?
- 如何在PowerShell中获得MD5校验和
- 如何在PowerShell格式化日期时间
- PowerShell和-contains操作符
- 使用PowerShell删除超过15天的文件
- 数组添加 vs +=
- PowerShell中用户输入的提示符
- 如何从字符串执行任意本机命令?
- 如何使用。net 4运行时运行PowerShell ?
- 在PowerShell中重新加载路径
- 函数在PowerShell中的返回值
- 如何在PowerShell中输出一些东西