PowerShell에서 MD5 체크섬을 얻는 방법
일부 내용 의 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)))
내용이 파일 인 경우 :
$someFilePath = "C:\foo.txt"
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($someFilePath)))
PowerShell 버전 4부터는 Get-FileHash
cmdlet 을 사용하여 즉시 사용 가능한 파일을 쉽게 수행 할 수 있습니다 .
Get-FileHash <filepath> -Algorithm MD5
이것은 주석에서 식별 된 첫 번째 솔루션이 제공하는 문제 (스트림 사용, 닫기 및 대용량 파일 지원)를 피하기 때문에 확실히 바람직합니다.
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")
다음은 상대 및 절대 경로를 처리하는 함수입니다.
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 덕분에 ReadAllBytes () 대신 Open ()을 사용하고 finally 블록을 사용하는 제안에 @ jpmc26을 제안했습니다.
ComputeHash ()를 사용하는 온라인 예제가 많이 있습니다. 내 테스트는 네트워크 연결을 통해 실행할 때 이것이 매우 느리다는 것을 보여주었습니다. 아래 스 니펫은 나에게 훨씬 빠르지 만 YMMV :
$md5 = [System.Security.Cryptography.MD5]::Create("MD5")
$fd = [System.IO.File]::OpenRead($file)
$buf = new-object byte[] (1024*1024*8) # 8mb buffer
while (($read_len = $fd.Read($buf,0,$buf.length)) -eq $buf.length){
$total += $buf.length
$md5.TransformBlock($buf,$offset,$buf.length,$buf,$offset)
write-progress -Activity "Hashing File" `
-Status $file -percentComplete ($total/$fd.length * 100)
}
# finalize the last read
$md5.TransformFinalBlock($buf,0,$read_len)
$hash = $md5.Hash
# convert hash bytes to hex formatted string
$hash | foreach { $hash_txt += $_.ToString("x2") }
write-host $hash_txt
이 사이트에는 예가 있습니다 : http://blog.brianhartsock.com/2008/12/13/using-powershell-for-md5-checksums/ . .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()
2003 년으로 거슬러 올라간 기본적으로 Windows에 오랫동안 설치되어 온 또 다른 내장 명령은 certutil이며 물론 powershell에서도 호출 할 수 있습니다.
CertUtil -hashfile file.foo MD5
(caveat: MD5 should be in all caps for maximum robustness)
This question is almost 3 years old, since then, as some commented, there is a Get-FileHash function wich is very handy.
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
Just change SHA384 with MD5.
The example is from the official documentation of PowerShell 5.1.
I guess this answer is redundant of keith-hill answer and the edition of the chosen answer, but it points to official documentation and it has a better example. The documentation has more examples.
This becomes a one-liner if you download FCIV from Microsoft.
Downloaded Microsoft's File Checksum Integrity Verifier from here https://support.microsoft.com/en-us/kb/841290
Run the following command. I had ten files to check.
gci WTAM*.tar | % {.\fciv $_.Name}
Adding my solution to the fray. As stated in the accepted answer Get-FileHash
is easy to use with files, but it is possible to use it with strings:
$s = "asdf"
Get-FileHash -InputStream ([System.IO.MemoryStream]::New([System.Text.Encoding]::ASCII.GetBytes($s)))
This will return an MD5 hash for a file on a remote computer:
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()
}
Sample for right-click menu option as well:
[HKEY_CLASSES_ROOT\*\shell\SHA1 PS check\command]
@="C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\powershell.exe -NoExit -Command get-filehash -algorithm SHA1 '%1'"
Pretty print example attempting to verify SHA256 fingerprint the downloaded gpg4win v3.0.3 using powershell v4 (requires Get-FileHash
)
Download the package from https://www.gpg4win.org/download.html , open powershell, grab the hash from the download page and run:
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 ) ) }
Output:
Hash matches for file gpg4win-3.0.3.exe
Here is one-line-command example with both computing the proper checksum of the file, like you just downloaded, and comparing it with the published checksum of the original.
For instance I wrote example for downloadings from Apache Jmeter project. In this case you have:
- downloaded binary file
- checksum of the original which is published in file.md5 as one string in the format:
3a84491f10fb7b147101cf3926c4a855 *apache-jmeter-4.0.zip
Then using this powershell command you can verify integrity of the downloaded file:
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")
Output:
True
Explanation:
The first operand of -eq
operator is a result of computing the checksum for the file:
(Get-FileHash .\apache-jmeter-4.0.zip -Algorithm MD5).Hash
The second operand is published checksum value. We firstly get content of the file.md5 which is one string and then we extract hash value base on the string format:
Get-Content .\apache-jmeter-4.0.zip.md5 | Convert-String -Example "hash path=hash"
Both file and file.md5 must be in the same folder to this command work.
참고URL : https://stackoverflow.com/questions/10521061/how-to-get-an-md5-checksum-in-powershell
'Programing' 카테고리의 다른 글
노드 : 콘솔 대신 파일에 로그인 (0) | 2020.06.09 |
---|---|
힘내 하위 모듈 추가 : "git 디렉토리가 로컬에서 발견되었습니다"문제 (0) | 2020.06.09 |
NameError를주는 모듈을 다시로드하는 중 : 이름 'reload'가 정의되지 않았습니다. (0) | 2020.06.09 |
문자열의 시작과 끝에서 공백 자르기 (0) | 2020.06.09 |
UITableView, 구분자 색은 어디에 설정합니까? (0) | 2020.06.09 |