我想计算一些内容的MD5校验和。如何在PowerShell中做到这一点?
当前回答
这将返回远程计算机上文件的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()
}
其他回答
团队! 看看我的哈希计算函数。
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"
这个网站有一个例子:使用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()
这是我用来获得一致哈希值的方法:
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()
}
这里有两行,只需在第2行中更改“hello”:
PS C:\> [Reflection.Assembly]::LoadWithPartialName("System.Web")
PS C:\> [System.Web.Security.FormsAuthentication]::HashPasswordForStoringInConfigFile("hello", "MD5")
另一个早在2003年就默认安装在Windows中的内置命令是Certutil,当然也可以从PowerShell调用它。
CertUtil -hashfile file.foo MD5
(注意:MD5应该全部大写以获得最大的健壮性)
推荐文章
- 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中输出一些东西