How to get an MD5 checksum in PowerShell
I would like to calculate an MD5 checksum of some content. How do I do this in PowerShell?
If the content is a string:
$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)))
If the content is a file:
$someFilePath = "C:foo.txt"
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($someFilePath)))
Starting in PowerShell version 4, this is easy to do for files out of the box with the Get-FileHash
cmdlet:
Get-FileHash <filepath> -Algorithm MD5
This is certainly preferable since it avoids the problems the first solution offers as identified in the comments (uses a stream, closes it, and supports large files).
如果您使用的是PowerShell社区扩展,则有一个Get-Hash命令行程序可以轻松完成此操作:
C:PS> "hello world" | Get-Hash -Algorithm MD5
Algorithm: MD5
Path :
HashString : E42B054623B3799CB71F0883900F2764
以下是两行,只需在第2行中更改“hello”:
PS C:> [Reflection.Assembly]::LoadWithPartialName("System.Web")
PS C:> [System.Web.Security.FormsAuthentication]::HashPasswordForStoringInConfigFile("hello", "MD5")
链接地址: http://www.djcxy.com/p/29106.html