source

PowerShell에서 MD5 체크섬을 가져오는 방법

myloves 2023. 4. 8. 10:15

PowerShell에서 MD5 체크섬을 가져오는 방법

몇 가지 콘텐츠의 MD5 체크섬을 계산하고 싶습니다.PowerShell에서 이 작업을 수행하는 방법

PowerShell 버전 4부터는 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)))

PowerShell Community Extensions를 사용하는 경우 Get-Hash 명령어를 사용하면 다음과 같은 작업을 쉽게 수행할 수 있습니다.

C:\PS> "hello world" | Get-Hash -Algorithm MD5


Algorithm: MD5


Path       :
HashString : E42B054623B3799CB71F0883900F2764

다음은 상대 경로와 절대 경로를 처리하는 기능입니다.

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()을 사용하도록 제안되고 @jpmc26에 최종 블록을 사용하도록 제안됩니다.

2행은 다음과 같습니다.2행의 "hello"를 변경해 주세요.

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

2003년부터 Windows에 기본적으로 설치되어 있는 또 다른 내장 명령어는 Certutil입니다.Certutil은 PowerShell에서도 호출할 수 있습니다.

CertUtil -hashfile file.foo MD5

(캐비닛: MD5는 내구성을 최대화하기 위해 모든 캡을 사용해야 합니다.)

수락된 답변에서 설명한 바와 같이 파일을 쉽게 사용할 수 있지만 문자열과 함께 사용할 수도 있습니다.

$s = "asdf"
Get-FileHash -InputStream ([System.IO.MemoryStream]::New([System.Text.Encoding]::ASCII.GetBytes($s)))

PowerShell One-Liner(스트링에서 해시까지)

MD5

([System.BitConverter]::ToString((New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider).ComputeHash((New-Object -TypeName System.Text.UTF8Encoding).GetBytes("Hello, World!")))).Replace("-","")

SHA1

([System.BitConverter]::ToString((New-Object -TypeName System.Security.Cryptography.SHA1CryptoServiceProvider).ComputeHash((New-Object -TypeName System.Text.UTF8Encoding).GetBytes("Hello, World!")))).Replace("-","")

SHA256

([System.BitConverter]::ToString((New-Object -TypeName System.Security.Cryptography.SHA256CryptoServiceProvider).ComputeHash((New-Object -TypeName System.Text.UTF8Encoding).GetBytes("Hello, World!")))).Replace("-","")

SHA384

([System.BitConverter]::ToString((New-Object -TypeName System.Security.Cryptography.SHA384CryptoServiceProvider).ComputeHash((New-Object -TypeName System.Text.UTF8Encoding).GetBytes("Hello, World!")))).Replace("-","")

SHA512

([System.BitConverter]::ToString((New-Object -TypeName System.Security.Cryptography.SHA512CryptoServiceProvider).ComputeHash((New-Object -TypeName System.Text.UTF8Encoding).GetBytes("Hello, World!")))).Replace("-","")

Compute Hash()를 사용하는 예는 온라인상에 많이 있습니다.테스트 결과, 네트워크 접속을 실행할 때 이 동작은 매우 느렸습니다.아래 토막은 훨씬 빠른 속도로 진행되지만 주행거리가 달라질 수 있습니다.

$md5 = [System.Security.Cryptography.MD5]::Create("MD5")
$fd = [System.IO.File]::OpenRead($file)
$buf = New-Object byte[] (1024*1024*8) # 8 MB 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 a hexadecimal formatted string
$hash | foreach { $hash_txt += $_.ToString("x2") }
Write-Host $hash_txt

Get-FileHash 기능이 있어 매우 편리합니다.

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

그냥 바꿔요SHA384로.MD5.

이 예는 PowerShell 5.1의 공식 문서에 나와 있습니다.이 문서에는 더 많은 예가 있습니다.

이 사이트에는 다음과 같은 예가 있습니다.MD5 체크섬용 Powershell 사용를 사용합니다.MD5 해시 알고리즘의 인스턴스를 인스턴스화하여 해시를 계산하는 NET 프레임워크.

다음은 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()

이것은, Microsoft 로부터 File Checksum Integrity Verifier(FCIV)를 다운로드하면, 1 행이 됩니다.

여기서 FCIV를 다운로드했습니다.File Checksum Integrity Verifier 유틸리티의 가용성 및 설명

다음 명령을 실행합니다.확인할 파일이 10개 있었어요

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

마우스 오른쪽 버튼 메뉴 옵션 샘플:

[HKEY_CLASSES_ROOT\*\shell\SHA1 PS check\command]
@="C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\powershell.exe -NoExit -Command Get-FileHash -Algorithm SHA1 '%1'"

특정 문자열의 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")}) 

원격 컴퓨터의 파일에 대한 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"

다음으로 SHA256 핑거 프린트를 확인하려고 하는 인쇄 예를 나타냅니다.PowerShell했습니다(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

다음은 다운로드 받은 파일의 적절한 체크섬을 계산하고 원본의 게시된 체크섬과 비교하는 한 줄 명령어 예제입니다.

예를 들어 Apache JMeter 프로젝트에서 다운로드하기 위한 예를 작성했습니다.이 경우 다음과 같이 됩니다.

  1. 다운로드된 바이너리 파일
  2. file.md5에 1개의 문자열로 게시된 원본 체크섬:

3a84491f10fb7b 101101cf3926c4a855 * scp-jmeter-4.0.zip

그런 다음 다음 PowerShell 명령을 사용하여 다운로드한 파일의 무결성을 확인할 수 있습니다.

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

출력:

True

설명:

의 첫 번째 .-eq연산자는 파일의 체크섬을 계산한 결과입니다.

(Get-FileHash .\apache-jmeter-4.0.zip -Algorithm MD5).Hash

두 번째 오퍼랜드는 공개된 체크섬 값입니다.먼저 1개의 문자열인 file.md5의 내용을 얻은 후 문자열 형식에 따라 해시 값을 추출합니다.

Get-Content .\apache-jmeter-4.0.zip.md5 | Convert-String -Example "hash path=hash"

이 명령어를 사용하려면 file과 file.md5모두 같은 폴더에 있어야 합니다.

일관된 해시 값을 얻기 위해 사용하는 방법은 다음과 같습니다.

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

$yourText = 'hello' 율율5d41402abc4b2a76b9719d911017c592

언급URL : https://stackoverflow.com/questions/10521061/how-to-get-an-md5-checksum-in-powershell