【问题标题】:How to hash strings byte arrays and io streams in PowerShell using common hashing algorithms如何使用常见的哈希算法在 PowerShell 中对字符串字节数组和 io 流进行哈希处理
【发布时间】:2020-05-01 12:07:30
【问题描述】:

如何使用常见的哈希算法(如 MD4 MD5 SHA1 等)对字符串字节数组 io 流等数据进行哈希处理... 我正在编写一个脚本来备份驱动器并防止不必要的副本并检测文件是否损坏,它需要使用诸如 MD4 之类的散列算法快速散列文件。 如果有人知道如何使用任何散列算法散列文件、io 流、字节数组、字符串......请告诉我。此外,我遇到的所有 Windows 安装中都不存在 Get-FileHash cmdlet。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    创建[System.Security.Cryptography.MD5] 的实例,然后将文件流传递给它的ComputeHash() 方法:

    function Get-MD5Sum
    {
      param(
        [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
        [Alias('PSPath')]
        [string[]]$Path
      )
      begin {
        $md5 = [System.Security.Cryptography.MD5]::Create()
      }
    
      process {
        foreach($filePath in $Path){
          # Resolve filesystem item
          $file = Get-Item -LiteralPath $Path
    
          # Skip if not a file
          if($file -isnot [System.IO.FileInfo]){
            continue
          }
    
          # Open a stream to read the file
          $filestream = $file.OpenRead()
    
          try {
            # Calculate + format hash, then output
            Write-Output $([pscustomobject]@{
              File = $file.FullName
              Hash = [BitConverter]::ToString($MD5.ComputeHash($filestream)) -replace '-'
            })
          }
          finally {
            # close file stream handle 
            $filestream.Dispose()
          }
        }
      }
    
      end {
        # Dispose of the hash provider
        $MD5.Dispose()
      }
    }
    

    现在您可以在没有Get-FileHash 的情况下计算 MD5 文件哈希:

    PS C:\> $fileHashes = Get-ChildItem . |Get-MD5Sum
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-25
      • 2015-04-24
      • 2014-05-13
      • 2021-09-19
      • 2018-11-08
      • 2011-08-24
      • 2019-09-19
      • 1970-01-01
      相关资源
      最近更新 更多